Skip to the content.

SQL Interview Questions and Answers: Easy to Hard, With Schemas (2027)

A free, hands-on set of SQL interview questions with answers, from basic SELECT and JOIN questions to window functions, recursive CTEs and “gaps and islands” problems. Every query runs against a small sample schema included in this repo, and an automated test checks every answer, so you can practice SQL for data analyst, data engineer, data scientist and backend developer interviews with real, verified results.

Last reviewed: December 2026. Queries are tested on SQLite. Most are standard SQL that also runs on PostgreSQL (current major version: 19) and MySQL 8+; date functions differ by database, and each answer that uses one notes the PostgreSQL and MySQL equivalent.

Table of contents

How to use this repo

  1. Load the sample data into SQLite (preinstalled on macOS and most Linux distributions):

    sqlite3 shop.db < data/schema.sql
    sqlite3 shop.db
    

    Or paste data/schema.sql into an online playground such as DB Fiddle or a local PostgreSQL.

  2. Read a question, write your own query, then compare with the answer and the expected output.
  3. Run the tests to see every answer execute: python3 tests/run_tests.py (needs only Python 3).

Levels: Easy = filtering, joins, grouping. Medium = subqueries, window functions, conditional aggregation. Hard = recursive CTEs, gaps and islands, multi-step analytics.

The sample schema

departments(id, name)
employees(id, name, dept_id -> departments.id, manager_id -> employees.id, salary, hire_date)
customers(id, name, city, signup_date)
products(id, name, category, price)
orders(id, customer_id -> customers.id, order_date, status)      -- status: pending | shipped | cancelled
order_items(order_id -> orders.id, product_id -> products.id, quantity, unit_price)
logins(user_id, login_date)                                        -- may contain duplicates

Quick facts about the data (useful when checking answers): 10 employees in 3 departments, plus one employee (Jo) with no department and one department (HR) with no employees; 5 customers, one of whom (Echo) never ordered; 8 orders from January to March 2025, one cancelled and one pending; 3 users in logins, with one duplicate row.

SQL interview roadmap

Stage Topics Time Practice
1. Basics SELECT, WHERE, ORDER BY, LIMIT, DISTINCT, NULL handling 2-4 days Q1-Q5, SQLBolt
2. Aggregation and joins GROUP BY, HAVING, INNER/LEFT/FULL joins, self joins 1 week Q6-Q15, SQLZoo
3. Subqueries and CTEs Correlated subqueries, EXISTS, WITH 3-5 days Q11, Q20, Q24
4. Window functions ROW_NUMBER, RANK, DENSE_RANK, LAG/LEAD, running totals, frames 1 week Q12-Q13, Q17-Q19, Q23, Q26
5. Advanced patterns Recursive CTEs, gaps and islands, retention, median, top-N per group 1 week Q27-Q35
6. Performance and design Indexes, EXPLAIN, normalization, transactions 3-5 days Concept questions below, Use The Index, Luke

For most analyst and data science interviews, stages 1-5 matter most. Backend and data engineering interviews add stage 6.

Concept questions (theory)

1. What is the logical order in which a SELECT query is evaluated?

FROM (and joins) -> WHERE -> GROUP BY -> HAVING -> SELECT (including window functions) -> DISTINCT -> ORDER BY -> LIMIT/OFFSET. That is why you cannot use a SELECT alias in WHERE in standard SQL, and why window functions cannot appear in WHERE (wrap them in a subquery or CTE). The database may physically execute things in a different order, but the result must match this logical order.

2. What is the difference between WHERE and HAVING?

WHERE filters rows before grouping; HAVING filters groups after aggregation. Put conditions on raw columns in WHERE (faster, fewer rows to group) and conditions on aggregates (COUNT(*) > 5) in HAVING.

3. Explain the types of JOIN.

Join Returns
INNER JOIN Only rows with a match on both sides
LEFT (OUTER) JOIN All left rows; NULLs where the right side has no match
RIGHT (OUTER) JOIN Mirror of LEFT JOIN
FULL (OUTER) JOIN All rows from both sides, matched where possible
CROSS JOIN Every combination (Cartesian product)
Self join A table joined to itself, e.g. employee to manager

SQLite supports RIGHT and FULL joins from version 3.39; MySQL has no FULL OUTER JOIN (emulate with LEFT JOIN ... UNION ... RIGHT JOIN).

4. Why does NOT IN sometimes return no rows?

If the subquery returns any NULL, x NOT IN (1, 2, NULL) evaluates to UNKNOWN for every x, so nothing passes. Use NOT EXISTS or filter NULLs out of the subquery. This is one of the most common SQL interview traps.

5. What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?

COUNT(*) counts rows; COUNT(col) counts rows where col is not NULL; COUNT(DISTINCT col) counts unique non-NULL values. Example in our data: COUNT(*) on employees is 10, COUNT(dept_id) is 9.

6. UNION vs UNION ALL?

UNION removes duplicates (extra sort or hash step); UNION ALL keeps every row and is faster. Use UNION ALL unless you need deduplication.

7. DELETE vs TRUNCATE vs DROP?

DELETE removes chosen rows, can have WHERE, is logged per row, and fires triggers. TRUNCATE removes all rows quickly and usually resets storage (in PostgreSQL it is transactional; in MySQL it causes an implicit commit). DROP removes the table itself.

8. What are primary keys, foreign keys and unique constraints?

A primary key uniquely identifies each row and cannot be NULL (one per table). A unique constraint also enforces uniqueness but allows NULLs (how many depends on the database) and a table can have many. A foreign key enforces that a value exists in another table’s key, protecting referential integrity.

9. What is normalization? When would you denormalize?

Normalization organizes data to reduce redundancy: 1NF (atomic values, no repeating groups), 2NF (no partial dependency on part of a composite key), 3NF (no transitive dependencies on non-key columns). Denormalize deliberately for read performance (analytics tables, caches, precomputed counters), accepting the cost of keeping copies in sync.

10. What is an index and how does it speed up queries?

An index is an extra data structure (usually a B-tree) that keeps column values sorted with pointers to rows, so lookups, range scans and ORDER BY on those columns avoid a full table scan. Costs: extra storage and slower writes. Composite indexes follow the leftmost-prefix rule: an index on (customer_id, order_date) helps WHERE customer_id = ? and WHERE customer_id = ? AND order_date > ?, but not WHERE order_date > ? alone.

11. What is a “sargable” predicate?

One the database can satisfy using an index. WHERE order_date >= '2025-02-01' AND order_date < '2025-03-01' is sargable; WHERE strftime('%m', order_date) = '02' or WHERE YEAR(order_date) = 2025 wraps the column in a function and usually prevents index use (unless you create an expression index).

12. Clustered vs non-clustered index?

A clustered index determines the physical order of the table data (InnoDB tables are clustered by primary key; SQL Server lets you choose one clustered index). A non-clustered (secondary) index is a separate structure pointing back to rows. PostgreSQL tables are heaps; CLUSTER reorders once but is not maintained.

13. What does EXPLAIN do?

It shows the query plan: scan types (sequential vs index), join algorithms (nested loop, hash, merge), estimated rows and costs. EXPLAIN ANALYZE in PostgreSQL also runs the query and shows actual times. In SQLite use EXPLAIN QUERY PLAN.

14. What are ACID properties?

Atomicity (all or nothing), Consistency (constraints hold before and after), Isolation (concurrent transactions don’t see each other’s partial work, to a chosen degree), Durability (committed data survives crashes, typically via a write-ahead log).

15. Explain transaction isolation levels.

Level Prevents Still allows
Read uncommitted Nothing much Dirty reads
Read committed Dirty reads Non-repeatable reads, phantoms
Repeatable read Dirty and non-repeatable reads Phantoms in the standard definition (PostgreSQL and MySQL InnoDB behave more strictly in practice)
Serializable All of the above anomalies Nothing; transactions may fail and need retry

PostgreSQL’s default is read committed; MySQL InnoDB’s default is repeatable read.

16. Window functions vs GROUP BY?

GROUP BY collapses rows into one per group. Window functions compute over a set of related rows but keep every row, so you can show each employee’s salary next to their department average.

17. ROW_NUMBER vs RANK vs DENSE_RANK?

For salaries 200, 150, 150, 120: ROW_NUMBER gives 1, 2, 3, 4 (ties broken arbitrarily unless ORDER BY is unique); RANK gives 1, 2, 2, 4 (gaps); DENSE_RANK gives 1, 2, 2, 3 (no gaps).

18. CTE vs subquery vs temporary table?

A CTE (WITH) names a subquery for readability and can be recursive. A derived table (subquery in FROM) is equivalent for most purposes. A temporary table is materialized and can be indexed and reused across statements. Modern PostgreSQL inlines non-recursive CTEs unless you write MATERIALIZED.

19. View vs materialized view?

A view is a stored query run each time. A materialized view stores the result and must be refreshed; great for expensive aggregations that can be a little stale.

20. OLTP vs OLAP, and what is a star schema?

OLTP systems handle many small transactional reads/writes (normalized schemas, row stores). OLAP systems answer big analytical queries (column stores, denormalized). A star schema has a central fact table (e.g. sales) with foreign keys to dimension tables (date, product, customer).

21. How do NULLs behave in comparisons and aggregates?

NULL = NULL is UNKNOWN, not TRUE; use IS NULL / IS NOT NULL (or IS DISTINCT FROM in PostgreSQL). Aggregates such as SUM and AVG ignore NULLs; AVG therefore divides by the non-NULL count. COALESCE(x, default) replaces NULLs.

22. What is the N+1 query problem?

Application code runs one query to fetch N parent rows, then one query per row to fetch children: N+1 round trips. Fix with a join or a single WHERE id IN (...) query (ORMs call this eager loading).

Easy query questions (Q1-Q10)

Q1. List employees earning more than 100,000, highest paid first.

-- Q1
SELECT name, salary
FROM employees
WHERE salary > 100000
ORDER BY salary DESC, name;

Expected output:

name salary
Ava 200000
Ben 150000
Cara 150000
Dan 120000
Gia 115000
Eve 110000

Note the tie-breaker name: without it, the order of Ben and Cara is not guaranteed.

Q2. Count employees in every department, including departments with nobody.

-- Q2
SELECT d.name AS department, COUNT(e.id) AS headcount
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.id
GROUP BY d.id, d.name
ORDER BY headcount DESC, department;
department headcount
Engineering 4
Sales 3
Marketing 2
HR 0

COUNT(e.id) (not COUNT(*)) is what makes HR show 0 instead of 1.

Q3. List the distinct cities customers are in.

-- Q3
SELECT DISTINCT city
FROM customers
ORDER BY city;
city
Los Angeles
New York
San Francisco

Q4. Which departments have an average salary above 100,000?

-- Q4
SELECT d.name AS department, AVG(e.salary) AS avg_salary
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
HAVING AVG(e.salary) > 100000
ORDER BY avg_salary DESC;
department avg_salary
Engineering 155000.0
Sales 105000.0

Q5. Find employees who are not assigned to any department.

-- Q5
SELECT name
FROM employees
WHERE dept_id IS NULL;
name
Jo

WHERE dept_id = NULL would return nothing: comparisons with NULL are never true.

Q6. Find customers who have never placed an order.

-- Q6
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
name
Echo

Alternative: LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL.

Q7. Total value of each shipped order.

-- Q7
SELECT o.id AS order_id, SUM(oi.quantity * oi.unit_price) AS order_total
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'shipped'
GROUP BY o.id
ORDER BY o.id;
order_id order_total
1 1250
2 300
4 640
5 625
6 2400
8 325

Q8. Label each employee’s salary band: “high” (150,000+), “mid” (100,000-149,999) or “low”.

-- Q8
SELECT name,
       CASE
         WHEN salary >= 150000 THEN 'high'
         WHEN salary >= 100000 THEN 'mid'
         ELSE 'low'
       END AS band
FROM employees
ORDER BY id;
name band
Ava high
Ben high
Cara high
Dan mid
Eve mid
Finn low
Gia mid
Hal low
Ivy low
Jo low

CASE checks branches in order, so the second condition does not need AND salary < 150000.

Q9. Show every employee with their department name, using “Unassigned” when missing.

-- Q9
SELECT e.name, COALESCE(d.name, 'Unassigned') AS department
FROM employees e
LEFT JOIN departments d ON d.id = e.dept_id
WHERE e.id IN (1, 9, 10)
ORDER BY e.id;
name department
Ava Engineering
Ivy Marketing
Jo Unassigned

(Filtered to three rows to keep the output short.)

Q10. List orders placed in February 2025.

-- Q10
SELECT id, order_date
FROM orders
WHERE order_date >= '2025-02-01' AND order_date < '2025-03-01'
ORDER BY order_date;
id order_date
4 2025-02-05
5 2025-02-14

A half-open range (>= start, < next start) is index-friendly and avoids end-of-month and timestamp bugs that BETWEEN '2025-02-01' AND '2025-02-28' has with datetime columns.

Medium query questions (Q11-Q26)

Q11. Find the second-highest distinct salary.

-- Q11
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
second_highest
150000

Returns NULL (not an empty result) if there is no second salary, which is what LeetCode 176 asks for.

Q12. Find the 3rd-highest distinct salary using a window function.

-- Q12
WITH ranked AS (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
)
SELECT DISTINCT salary
FROM ranked
WHERE rnk = 3;
salary
120000

DENSE_RANK gives 200000 rank 1, both 150000s rank 2, and 120000 rank 3. With RANK, 120000 would be rank 4 (a gap after the tie), and ROW_NUMBER would give rank 3 to the second 150000; that is why DENSE_RANK is the right choice for “Nth highest distinct value”. Related practice: LeetCode 177 (Nth Highest Salary).

Q13. Highest-paid employee(s) in each department, keeping ties.

-- Q13
WITH ranked AS (
  SELECT e.name, d.name AS department, e.salary,
         RANK() OVER (PARTITION BY e.dept_id ORDER BY e.salary DESC) AS rnk
  FROM employees e
  JOIN departments d ON d.id = e.dept_id
)
SELECT department, name, salary
FROM ranked
WHERE rnk = 1
ORDER BY department, name;
department name salary
Engineering Ava 200000
Marketing Hal 85000
Sales Gia 115000

Use RANK or DENSE_RANK (not ROW_NUMBER) when ties should all be returned.

Q14. Find employees who earn more than their manager.

-- Q14
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;
employee salary manager manager_salary
Gia 115000 Eve 110000

A self join: the same table plays two roles. Same idea as LeetCode 181.

Q15. Find duplicate rows in logins.

-- Q15
SELECT user_id, login_date, COUNT(*) AS copies
FROM logins
GROUP BY user_id, login_date
HAVING COUNT(*) > 1;
user_id login_date copies
1 2025-03-02 2

Q16. Remove duplicates, keeping one copy of each row (show the rows that would remain).

-- Q16
WITH numbered AS (
  SELECT user_id, login_date,
         ROW_NUMBER() OVER (PARTITION BY user_id, login_date ORDER BY user_id) AS rn
  FROM logins
)
SELECT COUNT(*) AS rows_after_dedup
FROM numbered
WHERE rn = 1;
rows_after_dedup
11

To actually delete in PostgreSQL, use the system column ctid (or a real primary key): DELETE FROM logins a USING logins b WHERE a.ctid > b.ctid AND a.user_id = b.user_id AND a.login_date = b.login_date;. In SQLite, use rowid the same way. Tables should normally have a primary key so this never happens.

Q17. Running total of shipped revenue by order date.

-- Q17
WITH daily AS (
  SELECT o.order_date, SUM(oi.quantity * oi.unit_price) AS revenue
  FROM orders o
  JOIN order_items oi ON oi.order_id = o.id
  WHERE o.status = 'shipped'
  GROUP BY o.order_date
)
SELECT order_date, revenue,
       SUM(revenue) OVER (ORDER BY order_date) AS running_total
FROM daily
ORDER BY order_date;
order_date revenue running_total
2025-01-03 1250 1250
2025-01-20 300 1550
2025-02-05 640 2190
2025-02-14 625 2815
2025-03-01 2400 5215
2025-03-18 325 5540

Q18. Month-over-month change in shipped revenue.

-- Q18
WITH monthly AS (
  SELECT substr(o.order_date, 1, 7) AS month,
         SUM(oi.quantity * oi.unit_price) AS revenue
  FROM orders o
  JOIN order_items oi ON oi.order_id = o.id
  WHERE o.status = 'shipped'
  GROUP BY substr(o.order_date, 1, 7)
)
SELECT month, revenue,
       revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month;
month revenue change
2025-01 1550 NULL
2025-02 1265 -285
2025-03 2725 1460

In PostgreSQL use date_trunc('month', order_date) or to_char(order_date, 'YYYY-MM'); in MySQL DATE_FORMAT(order_date, '%Y-%m'). For percentage change, divide by the previous value and guard against zero with NULLIF.

Q19. Revenue by product category and its share of the total (shipped orders).

-- Q19
SELECT p.category,
       SUM(oi.quantity * oi.unit_price) AS revenue,
       ROUND(100.0 * SUM(oi.quantity * oi.unit_price)
             / SUM(SUM(oi.quantity * oi.unit_price)) OVER (), 1) AS pct_of_total
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
WHERE o.status = 'shipped'
GROUP BY p.category
ORDER BY revenue DESC;
category revenue pct_of_total
Electronics 3700 66.8
Furniture 1840 33.2

SUM(SUM(...)) OVER () is a window over the grouped result: it adds up all groups. Multiply by 100.0 (not 100) to avoid integer division.

Q20. Customers who bought from both the Electronics and Furniture categories (shipped orders).

-- Q20
SELECT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id AND o.status = 'shipped'
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE p.category IN ('Electronics', 'Furniture')
GROUP BY c.id, c.name
HAVING COUNT(DISTINCT p.category) = 2
ORDER BY c.name;
name
Acme
Cove

This “relational division” pattern (HAVING COUNT(DISTINCT ...) = number of required values) answers “who did all of X”.

Q21. Each customer’s first order.

-- Q21
WITH firsts AS (
  SELECT customer_id, id AS order_id, order_date,
         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, id) AS rn
  FROM orders
)
SELECT c.name, f.order_id, f.order_date
FROM firsts f
JOIN customers c ON c.id = f.customer_id
WHERE f.rn = 1
ORDER BY f.order_date;
name order_id order_date
Acme 1 2025-01-03
Bolt 3 2025-01-22
Cove 5 2025-02-14
Dune 7 2025-03-03

Q22. Days between consecutive orders for each customer.

-- Q22
SELECT customer_id, id AS order_id, order_date,
       julianday(order_date)
         - julianday(LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date)) AS days_since_prev
FROM orders
WHERE customer_id = 1
ORDER BY order_date;
customer_id order_id order_date days_since_prev
1 1 2025-01-03 NULL
1 2 2025-01-20 17.0
1 6 2025-03-01 40.0

PostgreSQL: subtracting two date values gives an integer number of days directly: order_date - LAG(order_date) OVER (...). MySQL: DATEDIFF(order_date, LAG(order_date) OVER (...)).

Q23. Rank products by shipped revenue.

-- Q23
SELECT p.name,
       SUM(oi.quantity * oi.unit_price) AS revenue,
       RANK() OVER (ORDER BY SUM(oi.quantity * oi.unit_price) DESC) AS rnk
FROM order_items oi
JOIN orders o ON o.id = oi.order_id AND o.status = 'shipped'
JOIN products p ON p.id = oi.product_id
GROUP BY p.id, p.name
ORDER BY rnk, p.name;
name revenue rnk
Laptop 3600 1
Chair 900 2
Desk 900 2
Mouse 100 4
Lamp 40 5

Chair and Desk tie, so RANK gives both 2 and skips 3. You can use an aggregate inside OVER (ORDER BY ...) because window functions are evaluated after GROUP BY.

Q24. Employees who earn more than their department’s average.

-- Q24
SELECT e.name, e.salary
FROM employees e
WHERE e.salary > (
  SELECT AVG(e2.salary) FROM employees e2 WHERE e2.dept_id = e.dept_id
)
ORDER BY e.salary DESC;
name salary
Ava 200000
Gia 115000
Eve 110000
Hal 85000

A correlated subquery runs (logically) once per outer row. The window version is often faster: AVG(salary) OVER (PARTITION BY dept_id) in a CTE, then filter.

Q25. Pivot: number of orders per customer by status.

-- Q25
SELECT c.name,
       SUM(CASE WHEN o.status = 'shipped'   THEN 1 ELSE 0 END) AS shipped,
       SUM(CASE WHEN o.status = 'pending'   THEN 1 ELSE 0 END) AS pending,
       SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;
name shipped pending cancelled
Acme 3 0 0
Bolt 1 0 1
Cove 2 0 0
Dune 0 1 0

PostgreSQL also supports COUNT(*) FILTER (WHERE o.status = 'shipped').

Q26. Three-order moving average of shipped order totals.

-- Q26
WITH totals AS (
  SELECT o.id, o.order_date, SUM(oi.quantity * oi.unit_price) AS total
  FROM orders o
  JOIN order_items oi ON oi.order_id = o.id
  WHERE o.status = 'shipped'
  GROUP BY o.id, o.order_date
)
SELECT id, total,
       ROUND(AVG(total) OVER (ORDER BY order_date, id
                              ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS moving_avg_3
FROM totals
ORDER BY order_date, id;
id total moving_avg_3
1 1250 1250.0
2 300 775.0
4 640 730.0
5 625 521.7
6 2400 1221.7
8 325 1116.7

ROWS BETWEEN counts physical rows; RANGE BETWEEN (with an interval, in PostgreSQL) counts by value, e.g. “last 7 days” even when days are missing.

Hard query questions (Q27-Q35)

Q27. Show the whole reporting chain under Ava with each person’s level (recursive CTE).

-- Q27
WITH RECURSIVE chain AS (
  SELECT id, name, manager_id, 0 AS level
  FROM employees
  WHERE name = 'Ava'
  UNION ALL
  SELECT e.id, e.name, e.manager_id, c.level + 1
  FROM employees e
  JOIN chain c ON e.manager_id = c.id
)
SELECT name, level
FROM chain
ORDER BY level, name;
name level
Ava 0
Ben 1
Cara 1
Eve 1
Hal 1
Dan 2
Finn 2
Gia 2
Ivy 2

The anchor member selects the root; the recursive member joins children to rows found so far, until no new rows appear. Add a depth limit or cycle check for data that might contain loops.

Q28. Find each user’s login streaks (gaps and islands).

-- Q28
WITH days AS (
  SELECT DISTINCT user_id, login_date FROM logins
),
grouped AS (
  SELECT user_id, login_date,
         julianday(login_date)
           - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) AS grp
  FROM days
)
SELECT user_id, MIN(login_date) AS streak_start, MAX(login_date) AS streak_end,
       COUNT(*) AS days
FROM grouped
GROUP BY user_id, grp
ORDER BY user_id, streak_start;
user_id streak_start streak_end days
1 2025-03-01 2025-03-03 3
1 2025-03-05 2025-03-05 1
2 2025-03-01 2025-03-01 1
2 2025-03-03 2025-03-03 1
3 2025-03-02 2025-03-06 5

The trick: for consecutive dates, date - row_number is constant, so it labels each island. Deduplicate first, or duplicates break the arithmetic. In PostgreSQL: login_date - ROW_NUMBER() OVER (...)::int.

Q29. Users who logged in on at least 3 consecutive days.

-- Q29
WITH days AS (
  SELECT DISTINCT user_id, login_date FROM logins
),
grouped AS (
  SELECT user_id,
         julianday(login_date)
           - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) AS grp
  FROM days
)
SELECT DISTINCT user_id
FROM grouped
GROUP BY user_id, grp
HAVING COUNT(*) >= 3
ORDER BY user_id;
user_id
1
3

Alternative without islands: self join or LEAD(login_date, 2) and check that it equals login_date + 2 days.

Q30. Median salary.

-- Q30
WITH ordered AS (
  SELECT salary,
         ROW_NUMBER() OVER (ORDER BY salary) AS rn,
         COUNT(*) OVER () AS n
  FROM employees
)
SELECT AVG(salary) AS median_salary
FROM ordered
WHERE rn IN ((n + 1) / 2, (n + 2) / 2);
median_salary
112500.0

With integer division, (n + 1) / 2 and (n + 2) / 2 are the same row when n is odd and the two middle rows when n is even. PostgreSQL has PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary).

Q31. Next-day retention: share of users who logged in the day after their first login.

-- Q31
WITH firsts AS (
  SELECT user_id, MIN(login_date) AS first_day
  FROM logins
  GROUP BY user_id
)
SELECT ROUND(1.0 * COUNT(DISTINCT l.user_id) / (SELECT COUNT(*) FROM firsts), 2) AS day1_retention
FROM firsts f
JOIN logins l
  ON l.user_id = f.user_id
 AND l.login_date = date(f.first_day, '+1 day');
day1_retention
0.67

Users 1 and 3 came back the next day; user 2 did not. PostgreSQL: f.first_day + 1; MySQL: DATE_ADD(f.first_day, INTERVAL 1 DAY). Similar to LeetCode 550 (Game Play Analysis IV).

Q32. Top 2 products by units sold in each category (shipped orders).

-- Q32
WITH units AS (
  SELECT p.category, p.name, SUM(oi.quantity) AS units
  FROM order_items oi
  JOIN orders o ON o.id = oi.order_id AND o.status = 'shipped'
  JOIN products p ON p.id = oi.product_id
  GROUP BY p.id, p.category, p.name
),
ranked AS (
  SELECT category, name, units,
         ROW_NUMBER() OVER (PARTITION BY category ORDER BY units DESC, name) AS rn
  FROM units
)
SELECT category, name, units
FROM ranked
WHERE rn <= 2
ORDER BY category, rn;
category name units
Electronics Mouse 4
Electronics Laptop 3
Furniture Chair 6
Furniture Desk 3

The general “top N per group” pattern; LeetCode 185 (Department Top Three Salaries) is the classic version.

Q33. Cancellation rate per month.

-- Q33
SELECT substr(order_date, 1, 7) AS month,
       COUNT(*) AS orders,
       ROUND(1.0 * SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) / COUNT(*), 2) AS cancel_rate
FROM orders
GROUP BY substr(order_date, 1, 7)
ORDER BY month;
month orders cancel_rate
2025-01 3 0.33
2025-02 2 0.0
2025-03 3 0.0

AVG(CASE WHEN status = 'cancelled' THEN 1.0 ELSE 0 END) is a shorter equivalent.

Q34. Find dates in the first week of March 2025 with no orders (generate a date series).

-- Q34
WITH RECURSIVE calendar(day) AS (
  SELECT '2025-03-01'
  UNION ALL
  SELECT date(day, '+1 day') FROM calendar WHERE day < '2025-03-07'
)
SELECT c.day
FROM calendar c
LEFT JOIN orders o ON o.order_date = c.day
WHERE o.id IS NULL
ORDER BY c.day;
day
2025-03-02
2025-03-04
2025-03-05
2025-03-06
2025-03-07

PostgreSQL has generate_series('2025-03-01'::date, '2025-03-07', interval '1 day'). Reports that must show zero-activity days always need a calendar table or series like this.

Q35. For each customer, their share of total shipped revenue and their cumulative share (Pareto analysis).

-- Q35
WITH cust AS (
  SELECT c.name, SUM(oi.quantity * oi.unit_price) AS revenue
  FROM customers c
  JOIN orders o ON o.customer_id = c.id AND o.status = 'shipped'
  JOIN order_items oi ON oi.order_id = o.id
  GROUP BY c.id, c.name
)
SELECT name, revenue,
       ROUND(100.0 * revenue / SUM(revenue) OVER (), 1) AS pct,
       ROUND(100.0 * SUM(revenue) OVER (ORDER BY revenue DESC, name)
             / SUM(revenue) OVER (), 1) AS cumulative_pct
FROM cust
ORDER BY revenue DESC, name;
name revenue pct cumulative_pct
Acme 3950 71.3 71.3
Cove 950 17.1 88.4
Bolt 640 11.6 100.0

Dialect differences cheat sheet

Task SQLite PostgreSQL MySQL 8
Limit rows LIMIT 10 LIMIT 10 (or FETCH FIRST 10 ROWS ONLY) LIMIT 10
Current date date('now') CURRENT_DATE CURDATE()
Add a day date(d, '+1 day') d + 1 or d + INTERVAL '1 day' DATE_ADD(d, INTERVAL 1 DAY)
Days between julianday(a) - julianday(b) a - b (dates) DATEDIFF(a, b)
Month bucket strftime('%Y-%m', d) date_trunc('month', d) DATE_FORMAT(d, '%Y-%m')
String concat a \|\| b a \|\| b or concat(a, b) CONCAT(a, b)
Median manual (see Q30) PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) manual
Conditional count SUM(CASE ...) COUNT(*) FILTER (WHERE ...) SUM(cond)
Upsert INSERT ... ON CONFLICT DO UPDATE INSERT ... ON CONFLICT DO UPDATE INSERT ... ON DUPLICATE KEY UPDATE
Series recursive CTE generate_series recursive CTE

References: PostgreSQL window functions tutorial, SQLite window functions, SQLite date and time functions, MySQL 8.4 window functions.

Common mistakes interviewers look for

Where to practice more

Site Free/Paid Best for
LeetCode SQL 50 study plan Free (some database problems are Premium) Interview-style problems
SQLBolt Free Absolute beginners, interactive lessons
SQLZoo Free Classic interactive exercises
Select Star SQL Free An interactive book with real data
PostgreSQL Exercises Free Joins, aggregates, recursive queries on PostgreSQL
Mode SQL tutorial Free Analyst-style SQL
DataLemur Free tier; paid premium Data analyst and data science SQL interviews
StrataScratch Free tier; paid premium Questions styled after company interviews
HackerRank SQL Free Quick drills
Use The Index, Luke Free online book Indexing and performance
Modern SQL Free Newer SQL standard features across databases
CMU 15-445 Database Systems Free course materials How databases work inside

Books (paid): Learning SQL (O’Reilly), SQL Antipatterns (Pragmatic Bookshelf), SQL Performance Explained (the paid book form of Use The Index, Luke).

Also see our LeetCode SQL solutions repo.

FAQ

What SQL questions are asked in interviews? For analysts and data scientists: joins, GROUP BY with HAVING, window functions (ranking, LAG/LEAD, running totals), date handling, retention and funnel questions. For backend engineers: the same basics plus indexes, transactions, isolation levels and schema design. For data engineers: all of the above plus performance, partitioning and modeling (star schemas, slowly changing dimensions).

Which SQL dialect should I use in an interview? Whatever the interviewer’s environment runs, often PostgreSQL or MySQL; many platforms let you pick. Standard SQL with CTEs and window functions works almost everywhere. Mention dialect differences when you use something specific.

How do I get better at window functions quickly? Learn four patterns until they’re automatic: ranking (ROW_NUMBER/RANK/DENSE_RANK with PARTITION BY), previous/next row (LAG/LEAD), running totals (SUM() OVER (ORDER BY ...)), and moving windows (ROWS BETWEEN n PRECEDING AND CURRENT ROW). Questions Q12-Q26 drill each one.

Are SQL interviews timed? Usually: 15-30 minutes per question in live rounds, or a set of 2-4 questions in 60-90 minutes on online assessments. Practice talking while you type.

Do I need to memorize syntax for every database? No. Interviewers care about logic. Know one dialect well and know that differences exist (see the cheat sheet).

How do I prepare for a SQL interview in one week? Days 1-2: Q1-Q10 and concept questions 1-8. Days 3-5: Q11-Q26. Day 6: Q27-Q35. Day 7: 10 timed problems from the LeetCode SQL 50 plan and redo anything you missed.

Where to go next

Contributing

New questions are welcome. Each one needs:

  1. A question in plain words.
  2. A query in a sql code block starting with -- Q<number>, using only the tables in data/schema.sql (add rows if you need them and update affected expected results).
  3. The expected output, also added to tests/expected.json.
  4. python3 tests/run_tests.py passing.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.