Interview Prep � 2026 Guide

Top 50 SQL Interview Questions � Crack Your Next Interview

The definitive SQL interview preparation guide for 2026. 50 carefully curated questions with code examples, explanations, and optimization tips. Real questions asked at TCS, Infosys, Wipro, Amazon, and top startups. From fresher-level basics to advanced window functions.

Why SQL Is the #1 Interview Skill

In 2026, SQL remains the most in-demand skill for data-related roles. A comprehensive analysis of job postings on Naukri.com and LinkedIn shows that 92% of Data Analyst roles, 85% of Data Scientist roles, and 95% of Data Engineer roles require SQL proficiency. Whether you are interviewing in Lucknow, Bangalore, or for remote positions, SQL questions are a certainty.

But here is the reality most candidates face: they know SQL basics but freeze when asked about window functions, correlated subqueries, or query optimization. The gap between "I know SQL" and "I can solve complex SQL problems under pressure" is significant. This guide bridges that gap with 50 questions organized from basic to advanced, each with code examples and interview tips.

At DSWallah, we have prepared over 300 students for SQL interviews. Our curriculum covers every question in this guide with hands-on practice on real datasets. Students who complete our program report 3x higher confidence in SQL interviews.

How to Use This Guide

This guide covers 50 SQL questions organized into three difficulty tiers. Each question includes the answer, code example, and an interview tip explaining what the interviewer is really testing. Work through all three tiers sequentially � do not skip to advanced questions without solidifying basics.

Basic Questions (1-15): Foundation

These appear in every SQL interview. If you cannot answer these fluently, you will not pass. Master these first.

Intermediate Questions (16-35): Core Skills

These separate good candidates from great ones. Window functions, CTEs, and optimization knowledge are tested here.

Advanced Questions (36-50): Expert Level

These are asked at top companies and for senior roles. Recursive CTEs, complex analytics, and performance optimization.

Basic SQL Questions (1�15)

1. What is the difference between WHERE and HAVING?

WHERE filters rows before the GROUP BY clause is applied. HAVING filters groups after GROUP BY aggregation. You cannot use aggregate functions (COUNT, SUM, AVG) in WHERE.

SELECT city, COUNT(*) as cnt
FROM students WHERE age > 18
GROUP BY city HAVING COUNT(*) > 5;

Interview Tip: Always mention that WHERE cannot use aggregate functions � this shows deeper understanding.

2. What is the difference between DELETE and TRUNCATE?

DELETE: DML operation. Uses WHERE clause. Logged, can rollback. Triggers fire. Slower.

TRUNCATE: DDL operation. No WHERE clause. Minimal logging. Cannot rollback. Resets identity. Faster.

Interview Tip: Mention that TRUNCATE resets the identity counter � this detail impresses interviewers.

3. What is a PRIMARY KEY?

A column or set of columns that uniquely identifies each row. Cannot be NULL. Must be unique. Only one per table. Automatically creates a clustered index.

CREATE TABLE students (
 id INT PRIMARY KEY,
 name VARCHAR(100) NOT NULL
);

4. What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN: Returns rows with matches in both tables.

LEFT JOIN: Returns all rows from the left table. Matching rows from right. NULLs where no match.

SELECT s.name, e.course_id
FROM students s LEFT JOIN enrollments e ON s.id = e.student_id;

5. What is a FOREIGN KEY?

A column that references the PRIMARY KEY of another table. Ensures referential integrity � prevents inserting orphan records.

6. What are aggregate functions?

COUNT(), SUM(), AVG(), MAX(), MIN() � perform calculations on sets of rows and return single values. Used with GROUP BY.

SELECT department, AVG(salary) as avg_salary
FROM employees GROUP BY department;

7. What is GROUP BY?

Groups rows with identical values into summary rows. Used with aggregates. Every non-aggregate column in SELECT must appear in GROUP BY.

8. What is a subquery?

A query nested inside another query. Can appear in WHERE, SELECT, FROM, or HAVING.

SELECT name FROM students
WHERE id IN (SELECT student_id FROM enrollments WHERE course_id = 1);

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

UNION: Combines and removes duplicates. Slower.

UNION ALL: Combines and keeps all rows. Faster. Use when duplicates are acceptable.

10. What is NULL?

Represents missing or unknown data. Not zero, not empty string. Use IS NULL / IS NOT NULL for comparison. Aggregate functions ignore NULLs except COUNT(*).

11. What is the difference between WHERE and ON?

WHERE: Filters after joins. ON: Defines join condition. In LEFT JOINs, ON vs WHERE produces different results.

12. What is ORDER BY?

Sorts results by columns. ASC (default) or DESC. Can sort by column name, alias, or position.

SELECT name, salary FROM employees ORDER BY salary DESC;

13. What is DISTINCT?

Removes duplicate rows from results. Applies to all selected columns. Can be expensive on large datasets � the database must sort or hash all rows.

14. What is the difference between CHAR and VARCHAR?

CHAR: Fixed-length. Padded with spaces. Faster for fixed-size data.

VARCHAR: Variable-length. More efficient for varying data. Uses extra byte for length.

15. What is a view?

A stored query that acts as a virtual table. Does not store data. Simplifies complex queries, provides security, maintains consistency.

CREATE VIEW high_earners AS
SELECT name, salary FROM employees WHERE salary > 80000;

Intermediate SQL Questions (16�35)

16. What are Window Functions?

Calculations across rows related to the current row without collapsing them. Use OVER() clause. Essential for ranking, running totals, and analytics.

SELECT name, department, salary,
 RANK() OVER (PARTITION BY department ORDER BY salary DESC) as dept_rank
FROM employees;

17. ROW_NUMBER vs RANK vs DENSE_RANK?

ROW_NUMBER: Unique sequential numbers. No ties. 1, 2, 3, 4.

RANK: Same rank for ties, skips numbers. 1, 2, 2, 4.

DENSE_RANK: Same rank for ties, no gaps. 1, 2, 2, 3.

18. What is a CTE?

Common Table Expression � temporary named result set using WITH. Improves readability. Can be referenced multiple times. Supports recursion.

WITH dept_avg AS (
 SELECT department, AVG(salary) as avg_sal FROM employees GROUP BY department
)
SELECT e.name, e.salary FROM employees e
JOIN dept_avg d ON e.department = d.department WHERE e.salary > d.avg_sal;

19. What is a correlated subquery?

References columns from the outer query. Executes once per outer row. Often slow � can usually rewrite with JOINs.

20. What is an Index?

Data structure that speeds up data retrieval. Like a book index. Types: B-tree, hash, composite. Trade-off: faster reads, slower writes.

CREATE INDEX idx_email ON students(email);

21. What is a Self Join?

Table joined with itself. Used for hierarchical data like employee-manager relationships.

SELECT e.name, m.name as manager
FROM employees e LEFT JOIN employees m ON e.manager_id = m.id;

22. What is the difference between WHERE and HAVING with GROUP BY?

WHERE filters rows before grouping. HAVING filters groups after aggregation. WHERE cannot use aggregate functions.

23. What is a Stored Procedure?

Precompiled SQL statements stored in database. Accepts parameters. Improves performance, security, reusability.

24. What is a Transaction?

Sequence of operations as single logical unit. ACID properties. BEGIN, COMMIT, ROLLBACK.

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 1000 WHERE id = 1;
UPDATE accounts SET balance = balance + 1000 WHERE id = 2;
COMMIT;

25. What are ACID properties?

Atomicity: All or nothing. Consistency: Valid state. Isolation: Concurrent transactions independent. Durability: Committed changes persist.

26. What is Normalization?

Organizing tables to reduce redundancy. Normal forms: 1NF, 2NF, 3NF, BCNF. Goal: each fact stored once.

27. What is Denormalization?

Intentionally adding redundancy for performance. Avoids expensive JOINs. Common in data warehouses and read-heavy systems.

28. What is the difference between DELETE and DROP?

DELETE: Removes rows. Table structure remains. Can use WHERE.

DROP: Removes entire table structure and data. Cannot recover without backup.

29. What is a Trigger?

Special stored procedure that executes automatically on INSERT, UPDATE, DELETE events. Enforces business rules, audit trails.

30. What is the difference between IN and EXISTS?

IN: Compares against list. Subquery runs once. Good for small sets.

EXISTS: Returns TRUE on first match. Short-circuits. Better for large sets.

31. What is a Clustered Index?

Determines physical data order. One per table. Typically on PRIMARY KEY. Like dictionary alphabetical order.

32. What is a Non-Clustered Index?

Separate structure with indexed columns and pointers. Multiple per table. Like book index with page numbers.

33. What is a Execution Plan?

Shows how database executes a query. Displays operations, join types, index usage. Use EXPLAIN to view. Essential for optimization.

EXPLAIN SELECT * FROM employees WHERE department = 'Engineering';

34. What is the difference between ALL and ANY?

ALL: Compares value against all values in subquery. Returns TRUE if condition is true for all.

ANY: Returns TRUE if condition is true for at least one value.

35. What is COALESCE?

Returns the first non-NULL value from a list. Useful for handling missing data and providing defaults.

SELECT name, COALESCE(email, 'No email') as email FROM students;

Advanced SQL Questions (36�50)

36. What is LAG() and LEAD()?

LAG(): Accesses previous row. LEAD(): Accesses next row. Used for growth calculations and trend analysis.

SELECT month, revenue,
 LAG(revenue, 1) OVER (ORDER BY month) as prev_month,
 revenue - LAG(revenue, 1) OVER (ORDER BY month) as growth
FROM monthly_sales;

37. What is a Recursive CTE?

Self-referencing CTE for hierarchical data. Anchor member + recursive member. Traverses org charts, categories, graphs.

WITH RECURSIVE tree AS (
 SELECT id, name, manager_id, 1 as level FROM employees WHERE manager_id IS NULL
 UNION ALL
 SELECT e.id, e.name, e.manager_id, t.level + 1
 FROM employees e JOIN tree t ON e.manager_id = t.id
)
SELECT * FROM tree;

38. How to find the second highest salary?

SELECT DISTINCT salary FROM employees
ORDER BY salary DESC LIMIT 1 OFFSET 1;

-- Or with subquery
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

39. How to delete duplicate rows?

DELETE FROM students WHERE id IN (
 SELECT id FROM (
 SELECT id, ROW_NUMBER() OVER (PARTITION BY name, email ORDER BY id) as rn
 FROM students
 ) t WHERE rn > 1
);

40. What is a Pivot Table?

Transforms rows into columns. Uses CASE statements or PIVOT operator. Creates cross-tabulation reports.

SELECT department,
 SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) as male,
 SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) as female
FROM employees GROUP BY department;

41. What is a Gap-and-Island problem?

Finding consecutive sequences (islands) or missing sequences (gaps) in data. Solved with ROW_NUMBER() and date arithmetic.

42. What is query optimization?

Techniques: indexes, avoid SELECT *, EXPLAIN analysis, avoid correlated subqueries, LIMIT large results, partition tables, update statistics.

43. What is the difference between COUNT(*) and COUNT(column)?

COUNT(*): Counts all rows including NULLs.

COUNT(column): Counts only non-NULL values.

44. What is a Materialized View?

Stores query results physically on disk. Must be refreshed periodically. Used for expensive aggregations and reporting.

45. What is the difference between UNION and INTERSECT?

UNION: All rows from both queries. INTERSECT: Only rows in both. EXCEPT: Rows in first but not second.

46. What is a Window Function frame clause?

ROWS BETWEEN or RANGE BETWEEN defines which rows participate in calculation. ROWS uses physical offset, RANGE uses logical offset.

SELECT date, revenue,
 AVG(revenue) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) as moving_avg
FROM daily_sales;

47. What is the difference between RANK and PERCENT_RANK?

RANK: Position in ordered set. PERCENT_RANK: Relative position as percentage (0 to 1). Useful for percentile calculations.

48. What is the difference between FIRST_VALUE and NTH_VALUE?

FIRST_VALUE: Returns value from first row in window. NTH_VALUE: Returns value from nth row in window.

49. What is the difference between OVER(ORDER BY) and OVER(PARTITION BY ORDER BY)?

OVER(ORDER BY): Window function operates over entire result set.

PARTITION BY ORDER BY: Window function restarts for each partition.

50. How would you optimize this query?

Given: SELECT * FROM orders WHERE YEAR(order_date) = 2025 AND status = 'completed';

Optimization: (1) Avoid function on indexed column � use range instead. (2) Don't SELECT *. (3) Add composite index.

-- Optimized
SELECT order_id, customer_id, amount
FROM orders
WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01'
AND status = 'completed';

CREATE INDEX idx_date_status ON orders(order_date, status);

Practice Strategy

Consistent practice beats weekend cramming. Follow this schedule:

Week 1-2: Basics

Week 3-4: Intermediate

Week 5-6: Advanced

External Resources

Key Takeaways

SQL Interview Success Roadmap:

  • Basics are non-negotiable: WHERE, HAVING, JOINs, and GROUP BY appear in every interview. If these are weak, nothing else matters.
  • Window functions are the differentiator: ROW_NUMBER, RANK, LAG, LEAD � mastering these puts you ahead of 70% of candidates.
  • Practice 50+ problems minimum: LeetCode, HackerRank, and StrataScratch have real interview questions. Solve at least 2-3 per day.
  • Learn to read execution plans: EXPLAIN is your best friend for optimization questions. Interviewers love candidates who think about performance.
  • Talk through your thought process: In interviews, explain your approach before writing code. This shows problem-solving ability.
  • Build a SQL portfolio: Create GitHub repos with complex queries, optimization examples, and data analysis projects.
  • Study the company's SQL dialect: MySQL, PostgreSQL, and SQL Server have syntax differences. Know which one the company uses.

Related Courses

Data Science Course Python Course SQL Course AI Course All Courses

Related Blog Posts

SQL Interview Q&A Python Roadmap 2026 Interview Prep Guide Learn SQL for Data Science

Quick Links

Best Institute Lucknow About Vaibhav Gupta Success Stories Free Resources

Frequently Asked Questions

What are the top SQL interview questions for freshers?

Top SQL interview questions for freshers include: What is a primary key? What is the difference between DELETE and TRUNCATE? What are JOINs and their types? What is the difference between WHERE and HAVING? What are aggregate functions? What is normalization? What is a subquery? What is the difference between UNION and UNION ALL? These basics appear in every interview.

How many SQL questions should I practice before an interview?

You should practice at least 50 SQL questions covering basic, intermediate, and advanced topics. Focus on JOINs, GROUP BY, window functions, subqueries, and query optimization. Practice on LeetCode, HackerRank, or StrataScratch with real interview questions from companies. Consistent daily practice of 2-3 problems is more effective than weekend cramming.

What is the hardest SQL interview question?

The hardest SQL questions typically involve: recursive CTEs for hierarchical data, complex window functions with frame clauses, gap-and-island problems, pivot operations, and query optimization challenges. These require deep understanding of SQL concepts, creative problem-solving, and the ability to explain your thought process clearly under pressure.

Do I need to know SQL for data science interviews?

Yes, SQL is essential for data science interviews. 92% of data-related job postings require SQL proficiency. You need to know SELECT, JOINs, GROUP BY, window functions, subqueries, and basic optimization. SQL is tested in virtually every data analyst, data scientist, and data engineer interview. Mastering SQL significantly improves your chances of landing the role.

What SQL version should I study for interviews?

Focus on MySQL or PostgreSQL as they are the most commonly used in interviews. Most SQL concepts are universal across databases, but syntax differences exist for LIMIT (MySQL) vs TOP (SQL Server) and specific functions. MySQL is recommended for beginners due to its widespread use and free availability. Check the company's tech stack if possible.

How long does it take to prepare for SQL interviews?

With dedicated practice (2-3 hours daily), most people need 4-6 weeks to prepare for SQL interviews. Start with basics (Week 1-2), move to intermediate (Week 3-4), then advanced topics (Week 5-6). Consistent daily practice is more effective than weekend cramming. Mock interviews in the final week help build confidence and identify weak areas.

SQL Interview Question Patterns � How to Approach Any Query Problem

SQL interview questions follow patterns that you can learn to recognize and solve systematically. The DSWallah SQL interview prep module teaches a 4-step approach for any query problem. Step 1 (Understand): restate the problem in your own words, clarify edge cases (what if there are ties, what if there are nulls, what if the table is empty), and identify the expected output format. Step 2 (Break down): identify which SQL concepts are needed � is it a JOIN problem (combining data from multiple tables), a GROUP BY problem (aggregation), a window function problem (ranking or running totals), or a subquery problem (filtering based on derived values). Step 3 (Write): start with the simplest version that works, then add complexity. For top-N problems, write the base query first, then add ROW_NUMBER. For running totals, write the SUM first, then add the OVER clause. Step 4 (Optimize): check if the query can be simplified, if indexes would help, and if the same result can be achieved with fewer operations. Common patterns to memorize: deduplication with ROW_NUMBER and CTE, pivoting with CASE WHEN and GROUP BY, year-over-year comparison with self-join or LAG, median calculation with PERCENTILE_CONT, and hierarchical traversal with recursive CTEs. The DSWallah course includes 50 SQL interview questions with solutions, organized by pattern type, so you build recognition speed for each pattern.

SQL Performance Optimization Questions � Advanced Interview Topics

Advanced SQL interviews focus heavily on performance optimization, and these questions separate mid-level candidates from senior professionals. Common optimization questions include: "How would you optimize a query that takes 30 seconds to run?" The answer involves multiple steps: first, analyze the execution plan using EXPLAIN to identify bottlenecks (full table scans, expensive sorts, unnecessary joins). Then apply targeted fixes: add indexes on columns used in WHERE and JOIN clauses, rewrite subqueries as JOINs or CTEs, avoid SELECT * and retrieve only needed columns, and consider partitioning for large tables. Another common question: "What is the difference between a clustered and non-clustered index?" A clustered index determines the physical order of data in the table (only one per table), while a non-clustered index creates a separate structure that points to the data rows (multiple per table). Understanding these concepts is crucial because Indian companies with large databases (e-commerce, banking, telecom) specifically test optimization knowledge. Questions about query plan analysis, index strategy, and database design normalization come up frequently at companies like Flipkart, Amazon India, and banking institutions. DSWallah's SQL interview prep module includes 20+ optimization exercises with real execution plan analysis, giving students hands-on experience with the exact scenarios they will encounter in interviews.

SQL Interview Patterns � How Companies in India Structure Their Tests

Understanding how Indian companies structure SQL interview tests helps you prepare strategically. Most companies follow a three-round format. Round 1 (Online Assessment): 15-20 SQL questions on platforms like HackerRank or HackerEarth, testing basic to intermediate concepts (JOINs, GROUP BY, subqueries) under time pressure (90 minutes). Speed and accuracy both matter � practice solving problems quickly. Round 2 (Technical Interview): 3-5 complex SQL problems solved live on a whiteboard or shared screen. The interviewer evaluates your thought process, communication, and ability to handle ambiguity. Explain your approach before writing code, ask clarifying questions, and discuss trade-offs between different solutions. Round 3 (Advanced Technical): System design and optimization questions � design a data warehouse schema, optimize a slow query, handle real-time data processing. These questions test architectural thinking beyond basic SQL. Common Indian company-specific patterns: e-commerce companies love window function questions (find top 3 products per category by sales), banking companies focus on aggregation and date functions (monthly transaction summaries, year-over-year comparisons), and tech companies test optimization and scalability (how to handle billion-row tables efficiently). DSWallah's interview preparation module includes company-specific question sets based on actual student interview experiences, providing the most relevant practice material for Indian data science and analytics interviews.

SQL Performance Optimization Questions � Advanced Interview Topics

Advanced SQL interviews focus heavily on performance optimization, and these questions separate mid-level candidates from senior professionals. Common optimization questions include: "How would you optimize a query that takes 30 seconds to run?" The answer involves multiple steps: first, analyze the execution plan using EXPLAIN to identify bottlenecks (full table scans, expensive sorts, unnecessary joins). Then apply targeted fixes: add indexes on columns used in WHERE and JOIN clauses, rewrite subqueries as JOINs or CTEs, avoid SELECT * and retrieve only needed columns, and consider partitioning for large tables. Another common question: "What is the difference between a clustered and non-clustered index?" A clustered index determines the physical order of data in the table (only one per table), while a non-clustered index creates a separate structure that points to the data rows (multiple per table). Understanding these concepts is crucial because Indian companies with large databases (e-commerce, banking, telecom) specifically test optimization knowledge. Questions about query plan analysis, index strategy, and database design normalization come up frequently at companies like Flipkart, Amazon India, and banking institutions. DSWallah's SQL interview prep module includes 20+ optimization exercises with real execution plan analysis, giving students hands-on experience with the exact scenarios they will encounter in interviews.

SQL Interview Patterns � How Companies in India Structure Their Tests

Understanding how Indian companies structure SQL interview tests helps you prepare strategically. Most companies follow a three-round format. Round 1 (Online Assessment): 15-20 SQL questions on platforms like HackerRank or HackerEarth, testing basic to intermediate concepts (JOINs, GROUP BY, subqueries) under time pressure (90 minutes). Speed and accuracy both matter � practice solving problems quickly. Round 2 (Technical Interview): 3-5 complex SQL problems solved live on a whiteboard or shared screen. The interviewer evaluates your thought process, communication, and ability to handle ambiguity. Explain your approach before writing code, ask clarifying questions, and discuss trade-offs between different solutions. Round 3 (Advanced Technical): System design and optimization questions � design a data warehouse schema, optimize a slow query, handle real-time data processing. These questions test architectural thinking beyond basic SQL. Common Indian company-specific patterns: e-commerce companies love window function questions (find top 3 products per category by sales), banking companies focus on aggregation and date functions (monthly transaction summaries, year-over-year comparisons), and tech companies test optimization and scalability (how to handle billion-row tables efficiently). DSWallah's interview preparation module includes company-specific question sets based on actual student interview experiences, providing the most relevant practice material for Indian data science and analytics interviews.

SQL Interview Preparation Timeline � Week-by-Way Study Plan

Preparing for SQL interviews requires structured practice over 4 to 6 weeks. Week 1: master basic SELECT, WHERE, ORDER BY, and GROUP BY with HAVING. Practice 20 simple queries on a sample database. Week 2: learn INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN. Practice 15 join problems including self-joins and multi-table joins. Week 3: study subqueries (correlated and non-correlated), EXISTS, IN, and ANY/ALL operators. Practice 10 problems combining subqueries with joins. Week 4: learn window functions (ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, SUM OVER, AVG OVER). Practice 15 window function problems. Week 5: study CTEs (WITH clause), recursive CTEs, and query optimization (EXPLAIN plans, indexing strategies). Practice 10 optimization problems. Week 6: solve 30 mixed problems under timed conditions (30 minutes per problem). This structured approach ensures you cover all topics systematically rather than jumping randomly between concepts. The DSWallah SQL interview guide includes this exact timeline with daily practice problems and progress tracking.

Common SQL Anti-Patterns to Avoid in Interviews

Interviewers watch for anti-patterns that signal a lack of production experience. Using SELECT star in production queries wastes bandwidth and breaks code when schema changes. Always specify columns explicitly. Using subqueries where a JOIN would be more efficient shows you do not understand query optimization. Correlated subqueries executed row by row are performance killers. Using DISTINCT to hide duplicate results from a poorly written query masks the real problem. Using OR in WHERE clauses when UNION ALL would be more efficient prevents the optimizer from using indexes effectively. Not using EXPLAIN to verify your query plan shows you cannot diagnose performance issues. These anti-patterns are not just style issues. They signal to interviewers that you have only practiced in isolation and never worked with production databases where performance and maintainability matter. The DSWallah SQL module specifically trains you to write interview-quality queries that are both correct and optimized, building the habits that hiring managers look for in strong candidates.