SQL interview questions

20 SQL interview questions and answers

SQL questions for data analyst, data scientist, data engineer and backend interviews: joins, NULL behaviour, window functions, top N per group, indexing, query tuning, normalisation and transactions. Each question has a short answer, a fuller explanation, a query you can run and the follow-ups interviewers ask.

20 questions with a 30-second answer, a deeper explanation and the follow-ups interviewers usually ask.

How to use these questions

SQL rounds mix concept questions (what is the difference between WHERE and HAVING) with live query writing (find the second highest salary, the top three products per category, customers who never ordered). Interviewers watch how you approach the problem as much as the final query: do you clarify the schema, handle NULLs and ties, and check your result on a small example?

Four patterns cover a large share of live questions: joining and anti-joining (customers without orders), aggregating with GROUP BY and HAVING, ranking within groups with window functions, and comparing a row with the previous one using LAG. Later questions move on to how queries perform: indexes, execution plans and transactions.

Read each question, write your own query on paper or in a sandbox, then compare with the answer. Questions marked Often asked come up most. After the reading, practise on real problems in SQL practice, which generates problems and grades your query.

SQL

Joins, aggregation, window functions and indexes

Q1EasyFresherOften asked

INNER JOIN vs LEFT JOIN?

30-second answer: Inner join keeps only matching rows. Left join keeps every row from the left table and fills missing right-side values with NULL. Left join plus IS NULL finds rows with no match.

INNER JOIN returns only rows with a match in both tables. LEFT JOIN returns every row from the left table and fills the right-side columns with NULL when there is no match.

A common pattern is LEFT JOIN … WHERE right.id IS NULL to find rows with no related record.

SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;  -- customers who never ordered

Follow-up questions interviewers ask next

  • What is a self join and when do you use it?
  • How do FULL OUTER and CROSS joins differ?
Q2EasyFresher

WHERE vs HAVING?

30-second answer: WHERE filters rows before grouping. HAVING filters groups after aggregation.

WHERE filters rows before grouping and cannot use aggregates. HAVING filters groups after aggregation.

SELECT dept, AVG(salary) AS avg_sal
FROM employees
WHERE active = 1
GROUP BY dept
HAVING AVG(salary) > 80000;

Follow-up questions interviewers ask next

  • Can you use a column alias in HAVING?
  • What is the logical order of execution of a query?
Q3Medium2–5 yearsOften asked

Find the second highest salary.

30-second answer: Rank salaries in descending order with DENSE_RANK and pick rank two. Dense rank handles ties correctly.

Use DENSE_RANK() so ties are handled correctly, then filter on rank 2. A subquery with MAX also works when you only need the value.

SQL
SELECT DISTINCT salary FROM (
  SELECT salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) t
WHERE rnk = 2;
Pandas
df["salary"].drop_duplicates().nlargest(2).iloc[-1]

Follow-up questions interviewers ask next

  • Find the Nth highest salary per department.
  • Solve it without window functions.
  • How do RANK and DENSE_RANK differ?
Q4Medium2–5 years

ROW_NUMBER vs RANK vs DENSE_RANK?

30-second answer: ROW_NUMBER is always unique. RANK gives ties the same number and leaves gaps. DENSE_RANK gives ties the same number with no gaps.

All three number rows within a window. ROW_NUMBER is always unique (1,2,3,4). RANK gives ties the same number and skips the next (1,2,2,4). DENSE_RANK gives ties the same number without gaps (1,2,2,3).

Follow-up questions interviewers ask next

  • Use ROW_NUMBER to remove duplicate rows.
  • What does PARTITION BY do?
  • Use it to find the second highest salary
Q5Medium2–5 years

How does an index speed up a query, and what does it cost?

30-second answer: An index is a sorted structure that lets the database jump to rows instead of scanning the table. It speeds up reads but slows writes and uses storage.

An index (usually a B-tree) keeps a sorted copy of one or more columns so the database can seek directly to matching rows instead of scanning the table.

The cost is extra storage and slower writes, since every insert, update or delete must maintain the index. Index columns used in WHERE, JOIN and ORDER BY, and put the most selective column first in a composite index.

Follow-up questions interviewers ask next

  • What is a covering index?
  • Why might the optimiser ignore an index?
Q6EasyFresher

What is the difference between UNION and UNION ALL?

30-second answer: UNION removes duplicates and costs an extra step; UNION ALL keeps every row and is faster. Prefer UNION ALL unless you need deduplication.

UNION combines the results of two queries and removes duplicate rows, which needs an extra sort or hash step. UNION ALL combines them and keeps every row, so it is faster and uses less memory.

Use UNION ALL unless you specifically need duplicates removed. Both queries must return the same number of columns with compatible types, and the column names come from the first query.

SELECT email FROM customers
UNION ALL
SELECT email FROM newsletter_subscribers;  -- keeps duplicates, faster

Follow-up questions interviewers ask next

  • How do INTERSECT and EXCEPT differ from UNION?
  • What happens if the two queries return different column counts?
Q7EasyFresherOften asked

How does NULL behave in comparisons and aggregates?

30-second answer: NULL means unknown, so comparisons with it are never true; use IS NULL. Aggregates ignore NULLs except COUNT(*), and NOT IN with a NULL in the list returns nothing.

NULL means unknown, so any comparison with it, including NULL = NULL, evaluates to unknown rather than true, and a WHERE clause keeps only rows where the condition is true. Test for it with IS NULL and IS NOT NULL.

Aggregates such as SUM, AVG and COUNT(column) ignore NULLs, while COUNT(*) counts rows. NOT IN with a subquery that returns a NULL matches nothing, so prefer NOT EXISTS. Use COALESCE(col, default) to replace NULLs.

SELECT COUNT(*)        AS all_rows,
       COUNT(phone)    AS rows_with_phone,
       COALESCE(AVG(discount), 0) AS avg_discount
FROM customers;

-- Safer than NOT IN when the subquery may contain NULL
SELECT c.id FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

Follow-up questions interviewers ask next

  • Why does NOT IN return no rows when the list contains NULL?
  • What is the difference between COUNT(*) and COUNT(column)?
Q8EasyFresher

What is the logical order of execution of a SQL query?

30-second answer: Logically a query runs FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT. That is why aliases aren't visible in WHERE but are in ORDER BY.

SQL is written as SELECT ... FROM ... WHERE ... but evaluated in a different logical order: FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and finally LIMIT.

That explains common errors. You cannot use a SELECT alias in WHERE because it has not been computed yet, you must use HAVING to filter on aggregates, and ORDER BY can use aliases because it runs after SELECT. Some databases relax the alias rule in other clauses, so do not depend on it.

Follow-up questions interviewers ask next

  • Why can't you filter on a window function in WHERE?
  • At which step are aggregates computed?
Q9Medium2–5 years

What is a self join and when do you use it?

30-second answer: A self join joins a table to itself under two aliases, for example employees to their managers. Use a left join to keep rows with no match.

A self join joins a table to itself using two aliases. It is how you relate rows within the same table, such as an employee and their manager, or each row and another row in the same group.

Because both sides are the same table, aliases are essential. Use a LEFT JOIN when you want to keep rows that have no match, such as the top manager who has no manager.

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

Follow-up questions interviewers ask next

  • How would you find pairs of customers in the same city?
  • How does a recursive CTE help with multi-level hierarchies?
Q10Medium2–5 yearsOften asked

How do you find and remove duplicate rows?

30-second answer: Find duplicates with GROUP BY and HAVING COUNT(*) > 1. Delete them by numbering rows per group with ROW_NUMBER and removing those after the first, then add a unique constraint.

To find duplicates, group by the columns that define a duplicate and keep groups with more than one row: GROUP BY email HAVING COUNT(*) > 1. To delete them while keeping one row per group, number the rows inside each group with ROW_NUMBER() and delete everything after the first.

Always run the SELECT version first to see what would be deleted, and wrap the change in a transaction. Prevent the problem later with a unique constraint.

-- Find duplicate emails
SELECT email, COUNT(*) AS n
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

-- Keep the oldest row per email, delete the rest
DELETE FROM users
WHERE id IN (
  SELECT id FROM (
    SELECT id,
           ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at, id) AS rn
    FROM users
  ) t
  WHERE rn > 1
);

Follow-up questions interviewers ask next

  • How do you choose which duplicate to keep?
  • How would you remove duplicates from a table with no primary key?
Q11Medium2–5 yearsOften asked

How do you calculate a running total or compare each row with the previous one?

30-second answer: Use window functions: SUM(...) OVER (ORDER BY ...) for a running total and LAG or LEAD to read the previous or next row. PARTITION BY restarts the calculation per group.

Use window functions, which compute over a set of related rows without collapsing them the way GROUP BY does. A running total is SUM(amount) OVER (ORDER BY day). The previous row's value is LAG(amount) OVER (ORDER BY day), and LEAD looks forward.

The OVER clause can include PARTITION BY to restart the calculation for each group, for example per customer. With an ORDER BY, the default frame runs from the first row to the current row (rows with the same sort value count together), which is what produces a running total.

SELECT day,
       amount,
       SUM(amount) OVER (ORDER BY day)           AS running_total,
       amount - LAG(amount) OVER (ORDER BY day)  AS change_from_prev
FROM daily_sales;

Follow-up questions interviewers ask next

  • How does the window frame change a moving average?
  • What is the difference between a window function and GROUP BY?
Q12Medium2–5 yearsOften asked

How do you get the top N rows per group?

30-second answer: Rank rows within each group using ROW_NUMBER, RANK or DENSE_RANK with PARTITION BY, then filter on the rank in an outer query or CTE.

Number the rows within each group with ROW_NUMBER() (or RANK() if ties should share a position), then keep the rows whose number is at most N. You cannot filter on a window function in the same WHERE, so wrap the query in a subquery or CTE.

Choose ROW_NUMBER for exactly N rows per group, and RANK or DENSE_RANK when tied rows should all be included. Some databases also offer LATERAL joins or a QUALIFY clause for this pattern.

WITH ranked AS (
  SELECT department_id, name, salary,
         ROW_NUMBER() OVER (
           PARTITION BY department_id ORDER BY salary DESC
         ) AS rn
  FROM employees
)
SELECT department_id, name, salary
FROM ranked
WHERE rn <= 3;  -- top 3 earners per department

Follow-up questions interviewers ask next

  • When would you choose DENSE_RANK over ROW_NUMBER?
  • How would you write this with a LATERAL join?
Q13EasyFresher

What is the difference between a primary key, a unique key and a foreign key?

30-second answer: A primary key uniquely identifies rows and can't be NULL; a unique key prevents duplicates and a table can have many; a foreign key references another table's key to enforce integrity.

A primary key uniquely identifies each row, cannot be NULL and a table has only one. A unique constraint also prevents duplicates but a table can have several, and most databases allow NULLs in it. A foreign key is a column that references a primary or unique key in another table and enforces referential integrity, so you cannot insert an orphan row or delete a parent that still has children (unless you cascade).

Primary and unique keys create an index automatically. Foreign key columns usually need an explicit index to keep joins and deletes fast, and in some databases they do not get one by default.

CREATE TABLE orders (
  id          BIGINT PRIMARY KEY,
  order_ref   TEXT UNIQUE,
  customer_id BIGINT NOT NULL REFERENCES customers (id)
);
CREATE INDEX orders_customer_idx ON orders (customer_id);

Follow-up questions interviewers ask next

  • What do ON DELETE CASCADE and ON DELETE RESTRICT do?
  • Why index a foreign key column?
Q14Medium2–5 years

What is normalisation, and when would you denormalise?

30-second answer: Normalisation splits data so each fact is stored once, avoiding update anomalies (1NF atomic values, 2NF no partial dependencies, 3NF no transitive dependencies). Denormalise deliberately for read performance.

Normalisation organises tables to reduce redundancy and update anomalies. First normal form means atomic values with no repeating groups. Second normal form removes attributes that depend on only part of a composite key. Third normal form removes attributes that depend on other non-key attributes, so every non-key column depends on the key, the whole key and nothing but the key.

Denormalisation deliberately reintroduces some redundancy, such as a stored total or a copied name, to make reads faster in reporting or high-read systems. Normalise by default and denormalise only where measured query cost justifies it and you can keep the copies consistent.

Follow-up questions interviewers ask next

  • What anomalies does an unnormalised table cause?
  • How would you keep a denormalised total consistent?
Q15EasyFresher

What is the difference between DELETE, TRUNCATE and DROP?

30-second answer: DELETE removes chosen rows and is fully logged; TRUNCATE empties the table fast; DROP removes the table and its structure. Rollback behaviour of TRUNCATE depends on the database.

DELETE removes the rows matching a WHERE clause, is logged row by row, fires triggers and can be rolled back. TRUNCATE removes all rows quickly by deallocating storage, normally cannot take a WHERE and in many databases resets identity counters; whether it can be rolled back depends on the database (it can inside a transaction in PostgreSQL and SQL Server, but not in MySQL). DROP removes the table itself, including its structure, indexes and permissions.

Use DELETE for selective removal, TRUNCATE to empty a table and DROP to remove it entirely.

Follow-up questions interviewers ask next

  • Why is TRUNCATE faster than DELETE without a WHERE?
  • What happens to foreign keys when you truncate a parent table?
Q16Medium2–5 years

What is a composite index and does column order matter?

30-second answer: A composite index is ordered by its columns, so it serves filters on a leftmost prefix. Column order matters: equality columns first, then range or sort columns.

A composite index covers several columns in a defined order. The database can use it efficiently for queries that filter on a leftmost prefix of the columns: an index on (country, city) helps WHERE country = 'IN' and WHERE country = 'IN' AND city = 'Pune', but not WHERE city = 'Pune' on its own.

Put equality columns first, then range or sort columns, and think about which filters are most selective. Wider indexes cost more to maintain on every write, so create them for real query patterns, not speculatively.

CREATE INDEX idx_orders_cust_date ON orders (customer_id, created_at);

-- Uses the index well
SELECT * FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Follow-up questions interviewers ask next

  • Can an index on (a, b) serve ORDER BY b alone?
  • What is a covering index?
Q17Medium2–5 yearsOften asked

How would you find and fix a slow SQL query?

30-second answer: Measure with the execution plan first. Common fixes are a proper index, rewriting predicates so they can use it, selecting fewer columns, reducing join fan-out and refreshing statistics.

Start by measuring: look at the execution plan, row counts and timing instead of guessing. Typical causes are a missing or unusable index, scanning far more rows than needed, functions on indexed columns in WHERE (which prevent index use), SELECT * pulling unneeded columns, joins that multiply rows and stale statistics.

Fix the cause the plan reveals: add or adjust an index, rewrite the predicate so it is index-friendly, filter earlier, paginate with keyset pagination, or precompute with a materialised view. Then check the plan again and compare timings on realistic data.

-- Slow: the function on the column blocks the index
SELECT * FROM orders WHERE DATE(created_at) = '2026-11-01';

-- Faster: a range the index can use
SELECT * FROM orders
WHERE created_at >= '2026-11-01' AND created_at < '2026-11-02';

Follow-up questions interviewers ask next

  • Why does wrapping an indexed column in a function slow a query?
  • When would you use a materialised view?
Q18HardSenior

How do you read an execution plan with EXPLAIN?

30-second answer: EXPLAIN shows the chosen plan with scan types, join methods and estimates; EXPLAIN ANALYZE adds actual times and rows. Look for unexpected sequential scans, bad estimates and spills.

EXPLAIN shows the plan the optimiser chose: the scan type for each table, the join method, the order of operations and estimated row counts and costs. EXPLAIN ANALYZE (PostgreSQL) actually runs the query and adds real timings and row counts, so you can compare estimates with reality.

Look for sequential scans on large tables where you expected an index, large gaps between estimated and actual rows (often stale statistics), expensive sorts, nested loops over many rows and operations that spill to disk. Read the plan from the innermost, most indented nodes outward.

EXPLAIN ANALYZE
SELECT * FROM orders WHERE customer_id = 42;

Follow-up questions interviewers ask next

  • What does a large gap between estimated and actual rows suggest?
  • When is a sequential scan the right choice?
Q19HardSenior

What does ACID mean, and what are transaction isolation levels?

30-second answer: ACID means atomic, consistent, isolated and durable transactions. Isolation levels trade protection from anomalies such as dirty and non-repeatable reads against concurrency.

ACID describes transaction guarantees: atomicity (all or nothing), consistency (constraints hold before and after), isolation (concurrent transactions do not interfere in unexpected ways) and durability (committed data survives a crash).

Isolation comes in levels. Read committed prevents dirty reads, repeatable read also prevents non-repeatable reads, and serializable behaves as if transactions ran one at a time. Stronger levels prevent more anomalies but reduce concurrency or cause retries, so use the weakest level that protects your invariants.

Follow-up questions interviewers ask next

  • What is a phantom read?
  • How would you prevent two sessions both spending the last unit of stock?
Q20Medium2–5 years

What is the difference between a subquery and a CTE?

30-second answer: A subquery is nested inline; a CTE is a named query defined with WITH that you can reuse and read top-down, and it supports recursion. Performance depends on the database.

A subquery is a query nested inside another, and a common table expression (CTE) is a named query defined with WITH before the main query. They can often express the same logic; a CTE usually reads better, can be referenced several times and supports recursion.

Performance depends on the database: many optimisers inline CTEs and treat them like subqueries, while some versions materialise them. Choose for clarity first, then check the execution plan if the query is slow.

WITH recent AS (
  SELECT customer_id, SUM(total) AS spend
  FROM orders
  WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
  GROUP BY customer_id
)
SELECT c.name, r.spend
FROM recent r
JOIN customers c ON c.id = r.customer_id
WHERE r.spend > 1000;

Follow-up questions interviewers ask next

  • When does a recursive CTE help?
  • Does a CTE always materialise its result?

Go deeper: INNER JOIN Mechanics & Multi-Table Joins · LEFT JOIN (Left Outer Join) & Preserving Unmatched Rows · Grouping Data with GROUP BY (Single & Multiple Columns) · Filtering Groups with HAVING (WHERE vs HAVING) · SQL Execution Order vs Logical Writing Order · Handling NULL Values (IS NULL, IS NOT NULL, Three-Valued Logic) · Introduction to Common Table Expressions (WITH Clause) · Ranking Functions: ROW_NUMBER(), RANK(), DENSE_RANK() · Window Functions vs GROUP BY Aggregations (Preserving Row Granularity) · How Indexes Work & The Read vs Write Trade-off · Covering Indexes (INCLUDE Clause) & Index-Only Scans · Solving Classic FAANG / Senior Data Analyst SQL Interview Problems

How to prepare for a SQL interview

  1. Learn the logical order of a query. Knowing that FROM and WHERE run before SELECT explains most syntax errors and most "why can't I use that alias" questions.
  2. Practise the ten patterns. Second highest value, top N per group, duplicates, running totals, month-over-month change, customers with no orders, consecutive days, pivoting with CASE, funnels and retention.
  3. Always handle NULLs and ties. Say out loud what should happen when two rows tie or a value is missing. It is the quickest way to look careful.
  4. Know one execution plan. Take a slow query, read EXPLAIN, add an index and show the plan change. This turns the performance questions into a story you lived.
  5. Learn the dialect you will be tested in. Date functions, string functions and LIMIT versus TOP differ between PostgreSQL, MySQL and SQL Server.

For a structured path, the SQL learning track covers 160 topics from foundations to production SQL, and the Python questions are a natural next step for data roles: Python interview questions.