SQL interview questions with answers and coding practice
By InterviewKit · Updated · 15 practice questions
Start with these original practice questions, then explain each answer aloud. The examples use PostgreSQL-style SQL; adjust date functions and syntax for your database.
1–3 years: query foundations
1. How do WHERE and HAVING differ?
WHERE removes individual input rows before grouping. HAVING removes groups after aggregation. For example, use WHERE to keep paid orders and HAVING COUNT(*) > 5 to keep customers with more than five paid orders.
2. When would you choose a LEFT JOIN?
Use it when every row from the left table must remain, even without a matching row on the right. Unmatched right-side columns become NULL. A right-table condition in WHERE can remove those unmatched rows; put that condition in ON when they must remain.
3. How do you find duplicate email addresses?
Group by email and keep groups whose count exceeds one. Decide first whether NULL values and differences in letter case should count as duplicates.
SELECT email, COUNT(*) AS occurrences
FROM customers
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;4–7 years: coding and multiple-table joins
4. How do you join customers, orders, order items and products safely?
Identify each table’s grain first: one row per customer, order, order line and product. Join through their keys. An order with three items becomes three rows, so summing the order’s total after that join would count it three times. Aggregate line values or pre-aggregate before joining.
5. How do you return the highest two distinct salaries per department?
Use DENSE_RANK by department and descending salary, then keep ranks one and two. This includes all ties. ROW_NUMBER would return only two rows when ordered with a unique tie-breaker.
WITH ranked AS (
SELECT employee_id, department_id, salary,
DENSE_RANK() OVER (
PARTITION BY department_id ORDER BY salary DESC
) AS salary_rank
FROM employees
WHERE salary IS NOT NULL
)
SELECT * FROM ranked WHERE salary_rank <= 2;6. How does a window function differ from GROUP BY?
GROUP BY usually reduces rows into groups. A window calculation keeps the detail rows and calculates across a related set. For a running total, specify an explicit frame and a stable order so tied dates do not make the result surprising.
7+ years: reliability and performance
7. How would you investigate a slow query?
Confirm the expected result and measure a baseline. Read the execution plan and compare row estimates with actual rows. Check expensive scans, joins, sorts and spills. Then assess statistics, indexes, filters and data volume. Re-measure after each change instead of assuming that an index always helps.
8. How do you make an incremental load safe to retry?
Choose a stable business key and a consistent source boundary. Stage and validate the batch, then apply inserts and updates transactionally where supported. Advance the watermark only after success. Decide how to handle deletes, late changes and duplicate source rows.
9. What should you explain before proposing an index?
Describe the query’s filters, join keys, ordering, selectivity and table size. Explain read benefits alongside write and storage costs. Compare execution plans and representative timings before and after the change.
SQL mock interview: six coding questions with answers
Try these original exercises in a fresh practice database. Explain your assumptions, write the query, and compare its output with the answer. The downloadable tables belong to these six tasks; earlier conceptual examples use their own schemas. The coding examples use a SQL subset supported by PostgreSQL and SQLite; other systems may need syntax changes.
For an optional 30-minute practice round, explain the table grain first, then attempt the six tasks before opening their answers. There is no pass mark or hiring prediction.
Download the sample SQL tables
The sample script creates four tables and their rows. Start with an empty practice database. Prices are illustrative units, not actual customer transactions. Order 106 is a guest order, so its customer key is NULL.
View the four sample tables
| customer_id | customer_name | city |
|---|---|---|
| 1 | Anaya | Delhi |
| 2 | Bharat | Mumbai |
| 3 | Charu | Delhi |
| 4 | Dev | Pune |
| 5 | Esha | Delhi |
| order_id | customer_id | status | order_date |
|---|---|---|---|
| 101 | 1 | paid | 2026-10-01 |
| 102 | 1 | paid | 2026-10-03 |
| 103 | 2 | paid | 2026-10-03 |
| 104 | 3 | cancelled | 2026-10-04 |
| 105 | 5 | pending | 2026-10-05 |
| 106 | NULL | paid | 2026-10-06 |
| 107 | 2 | paid | 2026-10-03 |
| product_id | category |
|---|---|
| 11 | Books |
| 12 | Courses |
| 13 | Accessories |
| item_id | order_id | product_id | quantity | unit_price |
|---|---|---|---|---|
| 1 | 101 | 11 | 2 | 50 |
| 2 | 101 | 12 | 1 | 100 |
| 3 | 102 | 11 | 1 | 50 |
| 4 | 103 | 12 | 2 | 100 |
| 5 | 104 | 11 | 10 | 50 |
| 6 | 105 | 13 | 1 | 30 |
| 7 | 106 | 11 | 1 | 50 |
| 8 | 107 | 13 | 1 | 30 |
Count paid orders for every customer, including customers with none.
Interview follow-up: What changes if you move the status condition from ON to WHERE?
Show SQL answer and expected result
SELECT c.customer_id, c.customer_name,
COUNT(o.order_id) AS paid_orders
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.status = 'paid'
GROUP BY c.customer_id, c.customer_name
ORDER BY c.customer_id;| customer_id | customer_name | paid_orders |
|---|---|---|
| 1 | Anaya | 2 |
| 2 | Bharat | 2 |
| 3 | Charu | 0 |
| 4 | Dev | 0 |
| 5 | Esha | 0 |
The LEFT JOIN retains all customers. COUNT(o.order_id) counts matching orders, while COUNT(*) would also count the unmatched placeholder row. Filtering paid status in ON retains customers who have only pending or cancelled orders.
Find customers who have never placed a paid order.
Interview follow-up: Why would NOT IN (SELECT customer_id FROM orders WHERE status = 'paid') fail for this dataset?
Show SQL answer and expected result
SELECT c.customer_id, c.customer_name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.customer_id
AND o.status = 'paid'
)
ORDER BY c.customer_id;| customer_id | customer_name |
|---|---|
| 3 | Charu |
| 4 | Dev |
| 5 | Esha |
NOT EXISTS tests for the absence of matching paid orders. Order 106 is a guest order with a NULL customer key. That NULL makes the suggested NOT IN expression unknown for otherwise unmatched keys, so it would return no customers here.
Join four tables to return paid line revenue by customer and product category.
Interview follow-up: Why is the guest order excluded, and where would you apply a refund rule?
Show SQL answer and expected result
SELECT c.customer_id, c.customer_name, p.category,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
JOIN order_items AS oi ON oi.order_id = o.order_id
JOIN products AS p ON p.product_id = oi.product_id
WHERE o.status = 'paid'
GROUP BY c.customer_id, c.customer_name, p.category
ORDER BY c.customer_id, p.category;| customer_id | customer_name | category | revenue |
|---|---|---|---|
| 1 | Anaya | Books | 150 |
| 1 | Anaya | Courses | 100 |
| 2 | Bharat | Accessories | 30 |
| 2 | Bharat | Courses | 200 |
Join through the customer, order and product keys. Multiply quantity by the unit price captured on each line. The inner customer join intentionally excludes guest orders. This exercise assumes non-null quantities and prices and excludes tax, refunds and discounts.
Return customers with at least two paid orders and paid line revenue of at least 240.
Interview follow-up: Why would COUNT(*) overcount Anaya’s orders after joining the line table?
Show SQL answer and expected result
SELECT c.customer_id, c.customer_name,
COUNT(DISTINCT o.order_id) AS paid_orders,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status = 'paid'
GROUP BY c.customer_id, c.customer_name
HAVING COUNT(DISTINCT o.order_id) >= 2
AND SUM(oi.quantity * oi.unit_price) >= 240
ORDER BY c.customer_id;| customer_id | customer_name | paid_orders | revenue |
|---|---|---|---|
| 1 | Anaya | 2 | 250 |
WHERE selects paid rows before aggregation. HAVING selects groups after aggregation. COUNT(DISTINCT o.order_id) avoids counting order 101 twice because it has two lines. Orders without lines contribute nothing to this line-revenue exercise; define how to handle such data-quality cases separately.
Return one latest paid order for each registered customer, resolving tied dates.
Interview follow-up: What changes if the business wants all orders tied on the latest date?
Show SQL answer and expected result
WITH ranked AS (
SELECT customer_id, order_id, order_date,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date DESC, order_id DESC
) AS row_num
FROM orders
WHERE status = 'paid' AND customer_id IS NOT NULL
)
SELECT customer_id, order_id, order_date
FROM ranked
WHERE row_num = 1
ORDER BY customer_id;| customer_id | order_id | order_date |
|---|---|---|
| 1 | 102 | 2026-10-03 |
| 2 | 107 | 2026-10-03 |
The unique order ID provides a deterministic tie-breaker for orders 103 and 107. Dates are stored as fixed-width YYYY-MM-DD text in this small portable dataset, so their text order is also chronological. A production system should use its appropriate date or timestamp type.
Return every customer’s paid line revenue, showing zero when no paid line exists.
Interview follow-up: How would you extend this when payments and shipments each contain several rows per order?
Show SQL answer and expected result
WITH paid_revenue AS (
SELECT o.customer_id,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status = 'paid'
GROUP BY o.customer_id
)
SELECT c.customer_id, c.customer_name,
COALESCE(r.revenue, 0) AS revenue
FROM customers AS c
LEFT JOIN paid_revenue AS r ON r.customer_id = c.customer_id
ORDER BY c.customer_id;| customer_id | customer_name | revenue |
|---|---|---|
| 1 | Anaya | 250 |
| 2 | Bharat | 230 |
| 3 | Charu | 0 |
| 4 | Dev | 0 |
| 5 | Esha | 0 |
The CTE produces one row per customer before joining to the customer table. COALESCE turns the missing match into zero because that is the stated reporting rule. For multiple one-to-many child tables, aggregate each to the required grain before joining; otherwise row multiplication can inflate totals. Higher-experience answers should also discuss constraints, representative execution plans and validation totals.
Related practice guides
How to use this guide
Attempt each question before reading its answer. Explain your assumptions, show a small example and test an edge case. Use the experience bands as a guide to depth, rather than a promise about what an employer will ask.
These are independently written practice questions, not verified questions from particular employers. Free guide answers do not change the contents of the paid PDFs.
Compare available interview PDFsReady for a focused SQL question bank?
Choose a PDF edition for deeper, topic-by-topic practice. Compare its sample questions, experience level, answer coverage and current price before buying.
View SQL PDF optionsOne-time purchase. SQL PDFs include model answers; DAX and Power BI Service PDFs contain questions only.
Further reading
Check the official documentation when you need exact behaviour or current platform requirements.
Continue your preparation
All free interview guides · Power BI preparation · SQL PDFs · DAX PDFs