3.0 University logo
  • Home
  • About us
  • All Courses
    • Cybersecurity Programs
      • Certified Ethical Hacker (CEH v13)
      • Certified SOC Analyst
      • Certified Penitration Testing Professional
      • Computer Hacking Forensic Investigator
      • Certified Cybersecurity Technician (CCT)
      • Certified AI Program Manager
      • Certified Offensive AI Security Professional
      • Certified Responsible AI Governance & Ethics Professional
      • Artificial Intelligence Essentials
    • Crypto Market Programs
    • Blockchain & Web3 Programs
      • Digital Assets Trading & Analysis Program
      • Certified Web3 Strategy & Growth Specialist
      • Certified Web3 Governance & Compliance Expert
      • Full Stack Blockchain Developer Program
      • Private Blockchain Developer Program
      • Public Blockchain Developer Program
    • Designs Programs
      • Jewellery Design Executive Program
      • Gems & Diamond Specialist Program
      • Jewellery Business Specialist Program
  • Schools
    • School of Decentralized Economics
    • School of Cyber Resilience
    • School of Intelligent Systems
    • School of Design Thinking
  • Partners
    • Certification & Knowledge Partner
    • Academic Partner
    • Hiring Partner
    • Delivery Partner
    • Affiliate Partner
    • Hybrid Center Partner
  • Blog
  • Home
  • About us
  • All Courses
    • Cybersecurity Programs
      • Certified Ethical Hacker (CEH v13)
      • Certified SOC Analyst
      • Certified Penitration Testing Professional
      • Computer Hacking Forensic Investigator
      • Certified Cybersecurity Technician (CCT)
      • Certified AI Program Manager
      • Certified Offensive AI Security Professional
      • Certified Responsible AI Governance & Ethics Professional
      • Artificial Intelligence Essentials
    • Crypto Market Programs
    • Blockchain & Web3 Programs
      • Digital Assets Trading & Analysis Program
      • Certified Web3 Strategy & Growth Specialist
      • Certified Web3 Governance & Compliance Expert
      • Full Stack Blockchain Developer Program
      • Private Blockchain Developer Program
      • Public Blockchain Developer Program
    • Designs Programs
      • Jewellery Design Executive Program
      • Gems & Diamond Specialist Program
      • Jewellery Business Specialist Program
  • Schools
    • School of Decentralized Economics
    • School of Cyber Resilience
    • School of Intelligent Systems
    • School of Design Thinking
  • Partners
    • Certification & Knowledge Partner
    • Academic Partner
    • Hiring Partner
    • Delivery Partner
    • Affiliate Partner
    • Hybrid Center Partner
  • Blog
    Login
    ₹0.00 0 Cart

    Learn Articles

    • Home
    • Learn Articles

    Top 50 SQL Interview Questions and Answers for 2026

    • Posted by 3.0 University
    • Date July 31, 2026
    • Comments 0 comment

    SQL interview questions test your ability to query, join, filter, and aggregate data in relational databases. The most common topics are JOINs, GROUP BY with HAVING, subqueries, window functions, and the difference between DELETE and TRUNCATE. This guide covers 50 questions from basic to advanced, with answers and example queries you can use immediately.

    According to a 2024 survey by StrataScratch, over 85% of data analyst interviews include at least one live SQL coding round. This guide covers the top 50 SQL interview questions, grouped from basic to advanced, with short answers and example queries you can actually memorize before your next interview.

    • Key Takeaway 1: Joins, GROUP BY, and subqueries are the three most-tested SQL topics across analyst roles.
    • Key Takeaway 2: Window functions like RANK() and ROW_NUMBER() separate mid-level from senior candidates.
    • Key Takeaway 3: Understanding WHERE vs HAVING, and DELETE vs TRUNCATE, is a near-universal interview filter.
    • Key Takeaway 4: SQL is the single highest-ROI technical skill you can add before an analyst interview, per LinkedIn’s 2024 Jobs on the Rise report.
    • Key Takeaway 5: Scenario-based SQL questions are increasingly common at companies like Flipkart, Swiggy, and Razorpay.

    Basic SQL Interview Questions (Q1–Q20)

    These basic sql interview questions filter out candidates who listed SQL on a resume but haven’t actually written queries. Don’t skip them. Interviewers at Indian product companies like Zomato and CRED still use these as openers to gauge confidence. If you’re preparing sql interview questions for freshers, start here before moving to joins and window functions.

    Q1. What is SQL and what is it used for?

    SQL (Structured Query Language) is a standard language for querying and managing relational databases. You use it to retrieve, insert, update, and delete data stored in tables.

    Q2. What are the main SQL sublanguages?

    DDL (Data Definition Language) handles structure: CREATE, ALTER, DROP. DML (Data Manipulation Language) handles data: SELECT, INSERT, UPDATE, DELETE. DCL covers permissions: GRANT, REVOKE. TCL manages transactions: COMMIT, ROLLBACK.

    Q3. What is the difference between WHERE and HAVING?

    WHERE filters rows before aggregation. HAVING filters groups after aggregation. A classic mistake is using WHERE with aggregate functions like COUNT() or SUM(), which throws an error.

    Example: SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;

    Q4. What is a PRIMARY KEY?

    A PRIMARY KEY uniquely identifies each row in a table. It can’t be NULL and must be unique. A table can have only one primary key, though it can span multiple columns (composite key).

    Q5. What is a FOREIGN KEY?

    A FOREIGN KEY is a column that references the PRIMARY KEY of another table. It enforces referential integrity, meaning you can’t insert a value that doesn’t exist in the parent table.

    Q6. What is the difference between DELETE, TRUNCATE, and DROP?

    Command What it does Rollback possible? Removes structure?
    DELETE Removes specific rows Yes No
    TRUNCATE Removes all rows fast No (in most DBs) No
    DROP Removes entire table No Yes

    Q7. What is normalization? Name the normal forms.

    Normalization organizes a database to reduce redundancy. The main forms are 1NF (atomic values), 2NF (no partial dependency), 3NF (no transitive dependency), and BCNF. Most production databases target 3NF.

    Q8. What is a NULL value in SQL?

    NULL means the absence of a value. It’s not zero and it’s not an empty string. You check for NULL using IS NULL or IS NOT NULL, not with = NULL.

    Q9. What is the difference between CHAR and VARCHAR?

    CHAR is fixed-length. If you define CHAR(10) and store “SQL”, it pads with spaces to fill 10 characters. VARCHAR is variable-length and only uses as much space as needed. Use VARCHAR for names and emails, CHAR for fixed codes like country codes.

    Q10. What are aggregate functions?

    Aggregate functions operate on a set of rows and return a single value: COUNT(), SUM(), AVG(), MIN(), MAX(). They’re always used with GROUP BY unless you’re aggregating the entire table.

    Q11. What is the DISTINCT keyword?

    SELECT DISTINCT city FROM customers; returns unique cities only. It removes duplicate rows from the result set.

    Q12. What is the ORDER BY clause?

    ORDER BY sorts your result set. Default is ascending (ASC). Use DESC for descending. You can sort by multiple columns: ORDER BY last_name ASC, first_name DESC;

    Q13. What is the LIMIT clause?

    LIMIT restricts the number of rows returned. SELECT * FROM orders LIMIT 10; returns the first 10 rows. MySQL and PostgreSQL use LIMIT; SQL Server uses TOP; Oracle uses ROWNUM or FETCH FIRST.

    Q14. What is a VIEW?

    A VIEW is a virtual table built from a SELECT query. It doesn’t store data itself. You use views to simplify complex queries, restrict column access, or present a consistent interface to application code.

    Q15. What is an INDEX?

    An index speeds up data retrieval by creating a data structure (usually a B-tree) on one or more columns. The trade-off: indexes slow down INSERT, UPDATE, and DELETE because the index must be updated too.

    Q16. What is a UNIQUE constraint?

    UNIQUE ensures all values in a column are different. Unlike PRIMARY KEY, a table can have multiple UNIQUE constraints, and UNIQUE columns can contain NULL values (in most databases).

    Q17. What is the difference between UNION and UNION ALL?

    UNION removes duplicate rows from the combined result. UNION ALL keeps all rows including duplicates. UNION ALL is faster because it skips the deduplication step.

    Q18. What is a stored procedure?

    A stored procedure is a saved block of SQL code you can call by name. It can accept parameters, contain logic, and return results. Think of it as a function for your database.

    Q19. What is a trigger?

    A trigger is SQL code that runs automatically when a specific event happens on a table: INSERT, UPDATE, or DELETE. They’re used for audit logging, enforcing business rules, or syncing data.

    Q20. What is a transaction?

    A transaction is a unit of work that either completes fully or not at all. It follows ACID properties: Atomicity, Consistency, Isolation, Durability. You control transactions with COMMIT and ROLLBACK.

    SQL Joins Interview Questions and Advanced Queries (Q21–Q40)

    SQL joins interview questions are where most candidates stumble. According to Interview Query’s 2023 Data Science Interview Report, joins appeared in 72% of SQL interview questions across top tech companies. Get these right and you’re already ahead of most applicants.

    If you’re also prepping for broader analyst roles, the data analyst interview questions guide at 3.0 University covers Python, statistics, and business case questions alongside SQL.

    Q21. What are the types of SQL JOINs?

    Join Type Returns Common Use
    INNER JOIN Rows matching in both tables Most common; strict match
    LEFT JOIN All rows from left + matches from right Find records with or without a match
    RIGHT JOIN All rows from right + matches from left Less common; often rewritten as LEFT
    FULL OUTER JOIN All rows from both tables Reconciliation queries
    CROSS JOIN Cartesian product of both tables Generating combinations
    SELF JOIN Table joined with itself Hierarchical data like org charts

    Q22. Write an INNER JOIN query example.

    Find all orders along with the customer name:

    SELECT o.order_id, c.customer_name FROM orders o INNER JOIN customers c ON o.customer_id = c.customer_id;

    Q23. What is a LEFT JOIN and when do you use it?

    A LEFT JOIN returns every row from the left table, plus matching rows from the right. Where there’s no match, the right-side columns return NULL. Use it when you want “all customers, whether or not they placed an order.”

    Q24. What is a SELF JOIN?

    A SELF JOIN joins a table to itself. It’s useful for hierarchical data. Example: find each employee and their manager from an employees table where manager_id references employee_id in the same table.

    SELECT e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.employee_id;

    Q25. What is a subquery?

    A subquery is a SELECT statement nested inside another query. It can appear in the SELECT, FROM, or WHERE clause. Subqueries that return a single value are scalar; those that return a list work with IN or EXISTS.

    Q26. What is a correlated subquery?

    A correlated subquery references a column from the outer query. It runs once per row of the outer query, making it slower than a regular subquery. Use it when you need row-by-row comparison, like finding employees who earn more than the average in their own department.

    Q27. What is a CTE (Common Table Expression)?

    A CTE is a named temporary result set defined with the WITH keyword. It makes complex queries readable and can be referenced multiple times in the same query. Unlike a subquery, it appears at the top of your SQL statement.

    WITH high_value AS (SELECT customer_id FROM orders WHERE total > 10000) SELECT * FROM customers WHERE customer_id IN (SELECT customer_id FROM high_value);

    Q28. What is a window function?

    A window function performs a calculation across a set of rows related to the current row, without collapsing them into a single output row. The OVER() clause defines the window. Common ones: RANK(), DENSE_RANK(), ROW_NUMBER(), LAG(), LEAD(), SUM() OVER. These advanced sql interview questions on window functions are standard at senior analyst rounds.

    Q29. What is the difference between RANK() and DENSE_RANK()?

    RANK() skips numbers after a tie. If two rows tie at rank 2, the next rank is 4. DENSE_RANK() doesn’t skip. The next rank after a tie at 2 is still 3. Use DENSE_RANK() when gaps in ranking would confuse stakeholders.

    Q30. What does ROW_NUMBER() do?

    ROW_NUMBER() assigns a unique sequential integer to each row within a partition. Unlike RANK(), it never ties. Use it to deduplicate records or pick the latest record per group.

    SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn FROM orders;

    Q31. What is the difference between LAG() and LEAD()?

    LAG() accesses a value from a previous row. LEAD() accesses a value from a following row. Both are window functions used heavily in time-series analysis, like comparing this month’s sales to last month’s.

    Q32. How do you find duplicate rows in a table?

    SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;

    This groups by the column you suspect has duplicates and filters for any group with more than one row.

    Q33. How do you find the second-highest salary?

    Classic sql query interview question. Two common approaches:

    • Subquery: SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
    • Window function: SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees) t WHERE rnk = 2;

    Q34. What is COALESCE()?

    COALESCE() returns the first non-NULL value from a list of arguments. It’s the clean way to handle NULLs in output: SELECT COALESCE(phone, email, 'No contact') FROM users;

    Q35. What is the difference between IN and EXISTS?

    IN checks if a value matches any value in a list or subquery result. EXISTS checks if a subquery returns any rows at all. EXISTS is generally faster when the subquery result is large because it stops at the first match.

    Q36. What is CASE WHEN in SQL?

    CASE WHEN is SQL’s conditional expression. It works like an if-else block inside a query.

    SELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 75 THEN 'B' ELSE 'C' END AS grade FROM students;

    Q37. How do you pivot data in SQL?

    Pivoting turns row values into column headers. In MySQL or PostgreSQL, you do this with conditional aggregation using CASE WHEN inside SUM() or COUNT(). SQL Server has a native PIVOT operator.

    Q38. What is a recursive CTE?

    A recursive CTE references itself to process hierarchical or tree-structured data, like an org chart or a bill of materials. It has an anchor member (base case) and a recursive member joined with UNION ALL.

    Q39. What is query optimization and how do you approach it?

    Query optimization means reducing query execution time and resource use. Start by checking the execution plan with EXPLAIN (MySQL/PostgreSQL) or EXPLAIN PLAN (Oracle). Common fixes: add indexes on WHERE and JOIN columns, avoid SELECT *, rewrite correlated subqueries as JOINs, and filter early with WHERE before aggregating.

    Q40. What are covering indexes?

    A covering index includes all columns a query needs, so the database engine never has to touch the actual table. The query is served entirely from the index, which is dramatically faster for read-heavy workloads.

    Scenario-Based SQL Queries for Analyst Interviews (Q41–Q50)

    These advanced SQL interview questions appear in rounds at companies like PhonePe, Meesho, and Paytm. They test whether you can translate a business problem into a working query, not just recite syntax.

    Pair your SQL prep with the Python interview questions guide at 3.0 University since most analyst roles expect both. And if you’re targeting data science roles, check the data scientist interview prep page for ML and stats questions.

    Q41. Find customers who placed orders in every month of 2024.

    SELECT customer_id FROM orders WHERE YEAR(order_date) = 2024 GROUP BY customer_id HAVING COUNT(DISTINCT MONTH(order_date)) = 12;

    Q42. Write a query to calculate a 7-day rolling average of daily sales.

    SELECT order_date, AVG(daily_sales) OVER (ORDER BY order_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS rolling_avg FROM daily_sales_summary;

    Q43. Find the top 3 products by revenue in each category.

    SELECT * FROM (SELECT category, product_name, revenue, RANK() OVER (PARTITION BY category ORDER BY revenue DESC) AS rnk FROM products) t WHERE rnk <= 3;

    Q44. Identify users who churned (no activity in the last 30 days).

    SELECT user_id FROM users WHERE user_id NOT IN (SELECT DISTINCT user_id FROM activity WHERE activity_date >= CURDATE() - INTERVAL 30 DAY);

    Q45. Write a query to detect gaps in a sequence of IDs.

    SELECT id + 1 AS gap_start FROM orders o WHERE NOT EXISTS (SELECT 1 FROM orders WHERE id = o.id + 1) ORDER BY id;

    Q46. Calculate month-over-month revenue growth percentage.

    SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev_revenue, ROUND((revenue - LAG(revenue) OVER (ORDER BY month)) / LAG(revenue) OVER (ORDER BY month) * 100, 2) AS growth_pct FROM monthly_revenue;

    Q47. Find pairs of customers who bought the same product.

    SELECT a.customer_id, b.customer_id, a.product_id FROM purchases a JOIN purchases b ON a.product_id = b.product_id AND a.customer_id < b.customer_id;

    Q48. Write a query to find the median salary.

    SQL doesn’t have a native MEDIAN() function in most databases. In MySQL: use PERCENTILE_CONT in analytical extensions or sort and pick the middle row using ROW_NUMBER() and COUNT().

    SELECT AVG(salary) FROM (SELECT salary, ROW_NUMBER() OVER (ORDER BY salary) AS rn, COUNT(*) OVER () AS total FROM employees) t WHERE rn IN (FLOOR((total+1)/2), CEIL((total+1)/2));

    Q49. How do you handle slowly changing dimensions in SQL?

    Slowly Changing Dimensions (SCDs) track historical changes in dimension tables. Type 1 overwrites old data. Type 2 adds a new row with effective dates, keeping history. Type 2 is standard in data warehouses like those built on Snowflake or BigQuery.

    Q50. What’s the difference between a star schema and a snowflake schema?

    A star schema has a central fact table connected directly to denormalized dimension tables. A snowflake schema normalizes those dimension tables into sub-dimensions. Star schemas are faster to query; snowflake schemas save storage and reduce redundancy.

    SQL is consistently the most-listed technical skill in analytics job postings. According to LinkedIn’s 2024 Jobs on the Rise report, SQL appeared in over 60% of all data analyst job descriptions in India, ahead of Python (52%) and Excel (48%). A 2023 report by Glassdoor found that analysts who list SQL as a primary skill earn a median salary 18% higher than those who don’t. That’s a concrete ROI for a skill you can learn in a few weeks of focused practice.

    For a broader technical interview strategy, the niche IT interview questions guide at 3.0 University covers domain-specific rounds across cloud, cybersecurity, and DevOps roles.

    Frequently Asked Questions

    What are the most asked SQL interview questions?

    The most-tested topics are JOINs (especially INNER vs LEFT), GROUP BY with HAVING, subqueries, window functions like RANK() and ROW_NUMBER(), and the difference between DELETE and TRUNCATE. According to StrataScratch’s 2024 analysis, these five areas appear in over 70% of SQL rounds at data-focused companies.

    How do I prepare SQL for data analyst interviews?

    Start with SELECT, WHERE, GROUP BY, and JOINs. Then move to subqueries and CTEs. Finish with window functions and query optimization. Practice on real datasets using LeetCode SQL, StrataScratch, or HackerRank. Aim for 30 minutes of daily query writing for four weeks before your interview.

    What SQL interview questions are asked for freshers?

    Freshers are typically asked about DDL vs DML, primary and foreign keys, basic SELECT queries, WHERE vs HAVING, and simple JOIN operations. Questions on normalization, NULL handling, and aggregate functions like COUNT() and SUM() are also standard. Companies like Infosys, Wipro, and TCS commonly use these as screening filters for entry-level data roles.

    What SQL topics are asked in interviews?

    Expect questions on DDL vs DML, normalization, indexes, joins, aggregate functions, window functions, CTEs, subqueries, and transactions. Scenario-based questions on deduplication, ranking, rolling averages, and cohort analysis are common at product companies like Swiggy, Razorpay, and Flipkart.

    What is the difference between join types?

    INNER JOIN returns only rows with matches in both tables. LEFT JOIN returns all rows from the left table, NULLs where there’s no match on the right. FULL OUTER JOIN returns all rows from both tables. CROSS JOIN returns every combination. Each serves a different analytical purpose depending on whether you want strict or inclusive matching.

    How do I write complex SQL queries?

    Break the problem into steps. Identify the tables you need, the join conditions, the filters, and the aggregations. Write the base query first, then layer on CTEs or subqueries. Use window functions for ranking or running totals. Test each step separately before combining. Reading your own EXPLAIN plan helps you catch performance issues early.

    The best way to close gaps in your SQL knowledge is to write queries every single day against real data. Pick a public dataset on Kaggle, define a business question, and answer it with SQL. Do that for 30 days and you’ll walk into any analyst interview with genuine confidence, not just memorized answers.

    Start with the questions in this guide, then work through the complete data analyst interview guide at 3.0 University to cover every other part of the hiring process.

    Last updated: July 2026. Reviewed by the 3University editorial team.

    • Share:
    3.0 University

    Previous post

    Power BI vs Tableau: Which BI Tool Should You Learn in 2026?
    July 31, 2026

    Next post

    Career Options After BTech in 2026: Jobs, Higher Studies & Salaries
    July 31, 2026

    You may also like

    Free AI Certificate Course by Government of India
    FREE AI Course with Certificate Launched by Govt of India
    June 19, 2026
    Highest Paid Professions in India
    Highest Paid Profession in India
    June 12, 2026
    Cyber Security Course Eligibility
    Cyber Security Course Eligibility
    June 11, 2026

    Leave A Reply Cancel reply

    You must be logged in to post a comment.

    3.0 University is a pioneering academic initiative for creating a comprehensive knowledge ecosystem for emerging technologies. We have developed an in-house suite of course offerings for retail, institutional market participants and industry-at-large. 

    Facebook X-twitter Instagram Linkedin
    Quick Links
    • About us
    • Courses
    • Become a Partner
    • Contact Us
    • Blog
    • Learn
    Trending Courses
    • Certified SOC Analyst
    • Certified Ethical Hacker v13 Program
    • Certified Penitration Testing Professional
    • Full Stack Blockchain Developer
    • Certified AI Program Manager
    Policies
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer
    • Refund Policy
    Contact Us
    FT Tower, CTS No. 256 & 257,
    Suren Road, Chakala, Andheri (E), Mumbai-400093 India.

    +91 8657961141

    support@3university.io

    Login with your site account

    Lost your password?

    Not a member yet? Register now

    Register a new account

    Are you a member? Login now

    Login with your site account

    Lost your password?

    Not a member yet? Register now

    Register a new account

    Are you a member? Login now

    Sign In

    Welcome back! Or create an account

    OR
    Forgot password?

    Need a new verification email?

    Don't have an account? Register

    Create Account

    Already have an account? Sign in

    OR

    Already have an account? Log in

    Reset Password

    Enter your email and we'll send you a reset link.

    ← Back to login

    Check Your Email

    Almost there!
    We have sent a verification link to your email address. Please check your inbox (and spam folder) and click the link to activate your account.

    Didn't receive the email? Enter your address to resend:

    Already verified? Sign in