How to answer a SQL problem in an interview
- Clarify: ties? NULLs? duplicates? which date range? “Highest” distinct or not?
- Say the plan: “I'll rank salaries per department with DENSE_RANK in a CTE, then filter rank 1.”
- Write it in steps with CTEs, readable names, and comments if helpful.
- Test edge cases out loud: empty groups, ties, NULLs, a customer with no orders.
- Mention performance: indexes on join keys, avoiding correlated subqueries on huge tables.
Part 1: 12 classic problems (tested)
1. Second-highest salary
-- Q1. Second-highest salary
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);| second_highest |
|---|
| 180000 |
Works with ties at the top and returns NULL if there's no second value. Alternative: DENSE_RANK() … = 2.
2. N-th highest distinct salary
-- Q2. N-th highest DISTINCT salary (N = 4)
SELECT DISTINCT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) r
WHERE rnk = 4;| salary |
|---|
| 160000 |
Distinct salaries: 300k, 180k, 170k, 160k… so the 4th is 160k. DENSE_RANK makes ties count once.
3. Employees earning more than their manager
-- Q3. Employees who earn more than their manager
SELECT e.name, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.emp_id = e.manager_id
WHERE e.salary > m.salary;| name | salary | manager | manager_salary |
|---|---|---|---|
| Ishaan | 170000 | Neha | 160000 |
4. Top 2 earners per department
-- Q4. Top 2 earners per department
SELECT department, name, salary
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC, name) AS rn
FROM employees
) r
WHERE rn <= 2
ORDER BY department, salary DESC;| department | name | salary |
|---|---|---|
| Data | Rohan | 180000 |
| Data | Amit | 120000 |
| Leadership | Kavya | 300000 |
| Sales | Ishaan | 170000 |
| Sales | Neha | 160000 |
ROW_NUMBER with a tie-breaker (name) returns exactly 2. Use DENSE_RANK if tied people should all be included.
5. Customers who ordered in May but not in April
-- Q5. Customers who ordered in May but not in April
SELECT customer_id FROM orders WHERE order_date >= '2026-05-01' AND order_date < '2026-06-01'
EXCEPT
SELECT customer_id FROM orders WHERE order_date >= '2026-04-01' AND order_date < '2026-05-01';| customer_id |
|---|
| 8 |
Only Vikram (customer 8). Also solvable with NOT EXISTS.
6. Customers who logged in 3+ days in a row
-- Q6. Customers who logged in on 3+ consecutive days
SELECT DISTINCT customer_id
FROM (
SELECT customer_id, login_date,
LEAD(login_date, 2) OVER (PARTITION BY customer_id ORDER BY login_date) AS two_later
FROM logins
) t
WHERE two_later = login_date + 2;| customer_id |
|---|
| 1 |
| 2 |
If the row two logins later is exactly 2 days later, there are 3 consecutive days (dates are unique per customer). See the islands method in lesson 10.
7. Median order value
-- Q7. Median order value
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY total) AS median_order_value
FROM order_totals;| median_order_value |
|---|
| 2498 |
8. Percentage of orders delivered
-- Q8. Percentage of orders delivered
SELECT ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'DELIVERED') / COUNT(*), 1) AS delivered_pct
FROM orders;| delivered_pct |
|---|
| 80.0 |
Use 100.0 (not 100) so the division isn't integer division, which would return 0.
9. Days from signup to first order
-- Q9. Each customer's first order and how many days after signup it came
SELECT c.name, MIN(o.order_date) AS first_order,
MIN(o.order_date) - c.signup_date AS days_to_first_order
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name, c.signup_date
ORDER BY days_to_first_order, c.name
LIMIT 3;| name | first_order | days_to_first_order |
|---|---|---|
| Arjun | 2026-04-15 | 28 |
| Meera | 2026-04-12 | 42 |
| Vikram | 2026-05-22 | 42 |
10. Repeat customers (ordered in both months)
-- Q10. Customers with orders in BOTH months (repeat customers)
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.order_date < '2026-05-01')
AND EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.order_date >= '2026-05-01')
ORDER BY c.name;| name |
|---|
| Arjun |
| Asha |
| Imran |
| Meera |
| Priya |
| Rahul |
11. Delete duplicates, keep one
CREATE TABLE signups (email TEXT, signed_up DATE);
INSERT INTO signups VALUES
('[email protected]', '2026-01-05'), ('[email protected]', '2026-01-20'),
('[email protected]', '2026-02-11'), ('[email protected]', '2026-02-03'),
('[email protected]', '2026-03-01');-- Q11. Delete duplicates, keeping the earliest signup per email
WITH ranked AS (
SELECT ctid AS row_id, -- PostgreSQL's physical row id
ROW_NUMBER() OVER (PARTITION BY email ORDER BY signed_up) AS rn
FROM signups
)
DELETE FROM signups
WHERE ctid IN (SELECT row_id FROM ranked WHERE rn > 1);
SELECT email, signed_up FROM signups ORDER BY email;| signed_up | |
|---|---|
| [email protected] | 2026-01-05 |
| [email protected] | 2026-02-03 |
| [email protected] | 2026-01-20 |
Asha's three signups became one (the earliest). In warehouses without row ids, rebuild instead: CREATE OR REPLACE TABLE t AS SELECT … WHERE rn = 1.
12. Cumulative customers by month
-- Q12. Cumulative number of customers by signup month
WITH monthly AS (
SELECT DATE_TRUNC('month', signup_date)::date AS month, COUNT(*) AS new_customers
FROM customers
GROUP BY 1
)
SELECT month, new_customers,
SUM(new_customers) OVER (ORDER BY month) AS total_customers
FROM monthly
ORDER BY month;| month | new_customers | total_customers |
|---|---|---|
| 2026-01-01 | 2 | 2 |
| 2026-02-01 | 2 | 4 |
| 2026-03-01 | 2 | 6 |
| 2026-04-01 | 2 | 8 |
Part 2: 38 concept questions
🎯 Basics
Try to answer out loud first, then tap to check.
Q1What is the logical order of execution of a query?Fresher+
Q2Primary key vs unique key?Fresher+
Q3DELETE vs TRUNCATE vs DROP?Fresher+
Q4WHERE vs HAVING?Fresher+
Q5COUNT(*) vs COUNT(col) vs COUNT(DISTINCT col)?Fresher+
Q6How does NULL behave in comparisons and aggregates?Fresher+
Q7UNION vs UNION ALL?Fresher+
Q8What is a view?Fresher+
Q9CHAR vs VARCHAR vs TEXT?Fresher+
Q10What is a constraint? Name five.Fresher+
🎯 Joins and aggregation
Try to answer out loud first, then tap to check.
Q1Explain all join types.1–3 yrs+
Q2Why might a LEFT JOIN behave like an INNER JOIN?1–3 yrs+
Q3Table A has 5 rows, B has 4. Max and min rows of A INNER JOIN B?1–3 yrs+
Q4Why did SUM double after a join, and how do you fix it?1–3 yrs+
Q5NOT IN vs NOT EXISTS?1–3 yrs+
Q6What is conditional aggregation?1–3 yrs+
Q7How do you find duplicate records?1–3 yrs+
Q8What do ROLLUP, CUBE and GROUPING SETS do?1–3 yrs+
🎯 Window functions and CTEs
Try to answer out loud first, then tap to check.
Q1What is a window function and how is it different from GROUP BY?1–3 yrs+
Q2ROW_NUMBER vs RANK vs DENSE_RANK?1–3 yrs+
Q3How do you get the latest record per key?1–3 yrs+
Q4How do you compute a running total and a 7-day moving average?1–3 yrs+
Q5LAG vs LEAD?1–3 yrs+
Q6What is a CTE, and when is a recursive CTE needed?1–3 yrs+
Q7Why can't you filter a window function in WHERE?3+ yrs+
Q8What's the default window frame?3+ yrs+
🎯 Changing data, transactions and performance
Try to answer out loud first, then tap to check.
Q1What are ACID properties?1–3 yrs+
Q2How do you upsert?1–3 yrs+
Q3What are isolation levels?1–3 yrs+
Q4What is an index and its cost?1–3 yrs+
Q5What is a sargable query?1–3 yrs+
Q6Clustered vs non-clustered index?3+ yrs+
Q7How do you troubleshoot a slow query?3+ yrs+
🎯 Modeling and data engineering
Try to answer out loud first, then tap to check.
Q1Fact vs dimension tables?1–3 yrs+
Q2Star vs snowflake schema?1–3 yrs+
Q3Explain SCD Type 1, 2 and 3.3+ yrs+
Q4How do you build an idempotent incremental load in SQL?3+ yrs+
Q5What quality checks run after a load?3+ yrs+
SQL cheat sheet
-- Shape of a query (run order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT)
SELECT col, COUNT(*) AS n FROM t WHERE cond GROUP BY col HAVING COUNT(*) > 1 ORDER BY n DESC LIMIT 10;
-- NULLs
WHERE c IS NULL; COALESCE(c, 'x'); NULLIF(a, 0);
-- Joins
FROM a LEFT JOIN b ON b.id = a.id AND b.flag = true -- right-side filters in ON
WHERE NOT EXISTS (SELECT 1 FROM b WHERE b.id = a.id) -- anti join
-- Conditional aggregation
SUM(CASE WHEN status = 'DELIVERED' THEN 1 ELSE 0 END)
-- Windows
ROW_NUMBER() OVER (PARTITION BY k ORDER BY ts DESC) -- latest per key: keep = 1
SUM(x) OVER (ORDER BY d) -- running total
LAG(x) OVER (ORDER BY d) -- previous row
x * 100.0 / SUM(x) OVER () -- share of total
-- CTE / recursive
WITH a AS (...), b AS (SELECT ... FROM a) SELECT ... FROM b;
WITH RECURSIVE r AS (anchor UNION ALL SELECT ... FROM t JOIN r ON ...) SELECT ...;
-- Upsert
MERGE INTO t USING s ON t.id = s.id
WHEN MATCHED AND s.updated_at > t.updated_at THEN UPDATE SET ...
WHEN NOT MATCHED THEN INSERT (...) VALUES (...);
-- Streaks (gaps & islands)
d - ROW_NUMBER() OVER (PARTITION BY u ORDER BY d)::int AS grpKey takeaways
- ✓Most SQL interview problems are a handful of patterns in disguise.
- ✓Always handle ties, NULLs and duplicates explicitly.
- ✓Write in CTE steps and explain your plan out loud.
- ✓Revisit the lesson linked to any answer that surprised you.
Frequently asked questions
How should I practise SQL for interviews?
Solve problems on a real database: load ShopKart (lesson 1), redo every problem on this page without looking, then try variations (top 3 instead of top 1, by month instead of by day). Explain your query out loud as you write it.
What SQL topics are asked for data engineer roles?
Joins (especially anti joins and join traps), GROUP BY/HAVING, window functions (ROW_NUMBER, RANK, LAG, running totals), CTEs, de-duplication, MERGE and incremental loads, indexes and query plans, and data modeling (star schema, SCD).
Which SQL dialect do interviews use?
Usually 'any standard SQL'. Write clean ANSI SQL, and mention dialect differences if relevant (LIMIT vs TOP, QUALIFY in Snowflake/Databricks).
What if I don't remember exact syntax?
Say what you'd do and why. Interviewers care more about the approach (window function to rank, then filter) and correctness (ties, NULLs, duplicates) than a perfect function name.
🧠 Quick check: SQL interview
1. Second-highest salary when two people share the highest?
2. Three consecutive login days: a clean approach?
3. Median in PostgreSQL?
4. Customers in May but not April?
Checking your access…