Skip to main content

SQL guide

SQL interview questions with worked answers

Fifteen SQL interview questions asked for analyst and engineer roles, each with a worked answer, the query, and what the interviewer is really checking.

By Simas Bandzevicius · Updated November 24, 2026 · 12 min read

These are the questions that come up again and again in SQL interviews for data analyst, analytics engineer and backend roles. Each answer includes the query and, more importantly, what the interviewer is checking. All examples run on the LearnWithSQL sandbox databases, so you can paste them into the playground and experiment.

1. What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping; HAVING filters groups after aggregates are computed.

SELECT department_id, COUNT(*) AS headcount
FROM employees
WHERE salary > 3000          -- row filter
GROUP BY department_id
HAVING COUNT(*) > 5;         -- group filter

What they check: that you know the order clauses run in. See SQL order of execution.

2. Find the second-highest salary

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

A more general version uses DENSE_RANK, which also works for the third or tenth highest:

SELECT DISTINCT salary
FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) t
WHERE rnk = 2;

What they check: handling ties and the case where no second value exists (both queries return NULL or no row instead of failing).

3. Highest-paid employee in each department

WITH ranked AS (
  SELECT department_id, first_name, salary,
         RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
  FROM employees
)
SELECT department_id, first_name, salary
FROM ranked
WHERE rnk = 1;

What they check: window functions, and whether you ask how ties should be handled. RANK keeps every tied employee; ROW_NUMBER keeps exactly one.

4. Explain INNER vs LEFT JOIN

An inner join keeps only rows that match on both sides. A left join keeps every row from the left table and fills the right side with NULLs when there is no match. What they check: whether you know that a WHERE condition on the right table turns a left join back into an inner join.

5. Find customers who have never ordered

SELECT c.first_name, c.last_name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

What they check: that you avoid NOT IN, which returns no rows when the subquery contains a NULL.

6. Find duplicate rows

SELECT first_name, last_name, COUNT(*) AS copies
FROM customers
GROUP BY first_name, last_name
HAVING COUNT(*) > 1;

What they check: grouping by the columns that define "the same", then filtering groups.

7. Delete duplicates, keeping one

DELETE FROM customers
WHERE id IN (
  SELECT id FROM (
    SELECT id, ROW_NUMBER() OVER (PARTITION BY first_name, last_name ORDER BY id) AS rn
    FROM customers
  ) t
  WHERE rn > 1
);

The LearnWithSQL sandbox is read-only, so try the inner SELECT there. What they check: that you keep a deterministic survivor (the lowest id) rather than deleting both copies.

8. COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column)

COUNT(*) counts rows. COUNT(column) counts non-NULL values. COUNT(DISTINCT column) counts unique non-NULL values. On the orders table, COUNT(*) is the number of orders and COUNT(DISTINCT customer_id) is the number of customers who ordered.

9. Running total

SELECT order_date, id,
       COUNT(*) OVER (ORDER BY order_date, id) AS orders_so_far
FROM orders
ORDER BY order_date, id;

What they check: that you include a unique tie-breaker; otherwise rows sharing a date get the same running value.

10. Month-over-month change

WITH monthly AS (
  SELECT DATE_TRUNC('month', order_date) AS month, COUNT(*) AS orders
  FROM orders
  GROUP BY 1
)
SELECT month, orders,
       orders - LAG(orders) OVER (ORDER BY month) AS change
FROM monthly;

11. What does NULL = NULL return?

NULL, which a filter treats as false. Use IS NULL, or IS NOT DISTINCT FROM to compare two nullable columns. What they check: three-valued logic.

12. UNION vs UNION ALL

UNION removes duplicate rows, which requires a sort or hash and is slower. UNION ALL keeps everything. Use UNION ALL unless you specifically need duplicates removed.

13. When would you use a CTE instead of a subquery?

When the logic has several steps, when the same intermediate result is used more than once, or when readability matters for review. In PostgreSQL 12 and later a CTE used once is optimized like a subquery, so there is no performance penalty.

14. Revenue by product category

SELECT c.name AS category, SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN products p   ON p.id = oi.product_id
JOIN categories c ON c.id = p.category_id
GROUP BY c.name
ORDER BY revenue DESC;

What they check: starting from the table that holds the measure (order lines) so the joins add labels without duplicating revenue.

15. How would you speed up a slow query?

Look at the plan with EXPLAIN ANALYZE, check that filters and join keys use indexes, filter rows as early as possible, avoid functions on indexed columns in WHERE, aggregate before joining one-to-many tables, and select only the columns you need. What they check: a method, not a list of tricks.

How to practise

Reading answers is not the same as writing them. Pick five of these, close this page, and write each query from memory in the SQL playground. Then change one requirement (third-highest instead of second, per country instead of per department) and write it again.