INTERVIEWKIT PRACTICE GUIDE

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.

TRY IT YOURSELF

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
customers — one row per customer
customer_idcustomer_namecity
1AnayaDelhi
2BharatMumbai
3CharuDelhi
4DevPune
5EshaDelhi
orders — one row per order
order_idcustomer_idstatusorder_date
1011paid2026-10-01
1021paid2026-10-03
1032paid2026-10-03
1043cancelled2026-10-04
1055pending2026-10-05
106NULLpaid2026-10-06
1072paid2026-10-03
products — one row per product
product_idcategory
11Books
12Courses
13Accessories
order_items — one row per order line
item_idorder_idproduct_idquantityunit_price
110111250
2101121100
310211150
4103122100
5104111050
610513130
710611150
810713130
1–3 years · Coding 1

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;
Expected paid-order counts
customer_idcustomer_namepaid_orders
1Anaya2
2Bharat2
3Charu0
4Dev0
5Esha0

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.

1–3 years · Coding 2

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;
Expected customers without paid orders
customer_idcustomer_name
3Charu
4Dev
5Esha

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.

4–7 years · Coding 3

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;
Expected four-table join result
customer_idcustomer_namecategoryrevenue
1AnayaBooks150
1AnayaCourses100
2BharatAccessories30
2BharatCourses200

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.

4–7 years · Coding 4

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;
Expected qualifying customer
customer_idcustomer_namepaid_ordersrevenue
1Anaya2250

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.

4–7 years · Coding 5

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;
Expected latest paid orders
customer_idorder_idorder_date
11022026-10-03
21072026-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.

7+ years · Coding 6

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;
Expected revenue for every customer
customer_idcustomer_namerevenue
1Anaya250
2Bharat230
3Charu0
4Dev0
5Esha0

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.

Continue with ranking, running totals and LAG examples.

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 PDFs
KEEP YOUR REVISION ORGANISED

Ready 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 options

One-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