Interviews · SQL

20 SQL interview questions with answers

The SQL questions that come up most in technical interviews, each with an answer you can explain out loud and a worked example where it helps.

Updated: October 18, 202620 questions with examples that have been run
In this guide

How to use this guide

A SQL interview usually tests three things: whether you understand what each clause does, whether you avoid the classic mistakes (NULL, duplicates after a JOIN, filters in the wrong place) and whether you can reason about the result. These twenty questions are grouped by topic; each answer is short on purpose, so you can explain it in your own words.

The examples were run on the fictional StoreSQL database with SQLite, and the results shown come from that run. Practise the queries in the Editor SQL before the interview: being able to write them counts for more than reciting them.

Basics

1. What is the difference between a primary key and a foreign key?

A primary key uniquely identifies each row in a table: it does not allow repeated or null values. A foreign key is a column that points to the primary key of another table and makes sure the relationship is valid: an order cannot refer to a customer who does not exist. The primary key defines identity; the foreign key defines the relationship.

2. What is the difference between DELETE, TRUNCATE and DROP?

DELETE deletes the rows you specify with WHERE and can be rolled back inside a transaction. TRUNCATE empties the whole table in one go; it is faster, but it takes no filter and its transactional behaviour depends on the engine. DROP removes the whole table, structure included. SQLite has no TRUNCATE; there you use DELETE without WHERE.

3. What is NULL and how are null values compared?

NULL means «unknown or missing value», not zero or an empty string. Any comparison with NULL with = or <> gives unknown, and the row does not pass the filter. To detect it, use IS NULL or IS NOT NULL.

SQLite example
SELECT name
FROM customers
WHERE email IS NULL
ORDER BY name;

Verified result (3 rows):

name
David Clark
Miles Lee
Peter Hill

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

COUNT(*) counts rows. COUNT(column_name) counts the rows where that column is not null. COUNT(DISTINCT column_name) counts the distinct non-null values. In the example there are 12 customers, 9 with an email address and 6 distinct cities.

SQLite example
SELECT COUNT(*) AS rows,
       COUNT(email) AS with_email,
       COUNT(DISTINCT city) AS cities
FROM customers;

Verified result (1 row):

rowswith_emailcities
1296

JOIN and relationships

5. What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only the rows that have a match in both tables. LEFT JOIN returns every row from the left table and, where there is no match, fills the right-hand columns with missing values. In StoreSQL there are 12 customers, but only 10 have orders: the INNER JOIN gives 10 distinct customers and the LEFT JOIN, 12.

SQLite example
SELECT COUNT(DISTINCT c.id) AS with_inner_join
FROM customers AS c
JOIN orders AS p ON p.customer_id = c.id;

Verified result (1 row):

with_inner_join
10

6. How do you find the rows in one table that have no match in another?

With a LEFT JOIN and filtering the rows where the right-hand table's key is null, or with NOT EXISTS. Both forms give the same result; NOT EXISTS avoids multiplying rows and is not affected by nulls in the list.

SQLite example
SELECT c.name
FROM customers AS c
WHERE NOT EXISTS (
  SELECT 1 FROM orders AS p WHERE p.customer_id = c.id
)
ORDER BY c.name;

Verified result (2 rows):

name
Miles Lee
Peter Hill

7. Why can a JOIN duplicate rows?

Because every matching pair produces a row. If one table has several rows for each key of the other, that key's row is repeated. A customer with three orders appears three times. That is not a data error, but it becomes an interpretation error if you then add up a customer-level value. Count the result before and after joining, and aggregate to the unit you need.

8. What is a SELF JOIN and when is it used?

It means joining a table to itself using two different aliases. It is used for hierarchies, such as employees and their managers, or to compare rows within the same table. Each alias plays a different role. To keep the people who have no manager, you need LEFT JOIN.

SQLite example
SELECT e.name AS employee, r.name AS owner
FROM employees AS e
LEFT JOIN employees AS r ON r.id = e.manager_id
ORDER BY e.id;

Verified result (10 rows):

employeeowner
Claire SmithNULL
Alex ReedClaire Smith
Beth MorganAlex Reed
Charles PageClaire Smith
Diana LaneCharles Page
Ernest ColeCharles Page
Faith RiversCharles Page
Graham NewtonClaire Smith
Helen CooperGraham Newton
Isaac DavisAlex Reed

Aggregation and filters

9. What is the difference between WHERE and HAVING?

WHERE filters rows before grouping and cannot use aggregate functions. HAVING filters groups after grouping and can use them. If the filter can be applied before grouping, put it in WHERE: it is clearer and processes fewer rows.

SQLite example
SELECT customer_id, COUNT(*) AS orders
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING COUNT(*) >= 2
ORDER BY orders DESC, customer_id;

Verified result (5 rows):

customer_idorders
12
22
32
52
82

10. How do you find duplicate values in a column?

Group by the column and keep the groups with more than one row using HAVING COUNT(*) > 1. To see the full rows, join the result back to the original table or use a window function.

SQLite example
SELECT city, COUNT(*) AS customers
FROM customers
GROUP BY city
HAVING COUNT(*) > 1
ORDER BY customers DESC, city;

Verified result (4 rows):

citycustomers
London4
Bristol2
Leeds2
Manchester2

11. How do you get the second highest value in a column?

Sort the distinct values from highest to lowest, skip the first and take the next. The DISTINCT stops a tie at the maximum from counting as the second value. You can also use DENSE_RANK() and filter by position 2.

SQLite example
SELECT DISTINCT price
FROM products
ORDER BY price DESC
LIMIT 1 OFFSET 1;

Verified result (1 row):

price
249

12. What is the difference between UNION and UNION ALL?

UNION stacks two results and removes duplicate rows. UNION ALL keeps them all and is faster, because it does not deduplicate. Use UNION ALL if you know there is no overlap or if you need to count every occurrence.

Subqueries, CTEs and window functions

13. What is the difference between a subquery, a CTE and a view?

A subquery lives inside another query. A CTE (WITH) gives a step a name and exists only for that statement, which makes it easier to read. A view stores a query in the database and can be reused in many statements. None of the three stores data, except a materialised view.

14. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

ROW_NUMBER gives every row a different number, even when they are tied. RANK gives tied rows the same position and then skips numbers. DENSE_RANK gives tied rows the same position without skipping. In the example, the two Audio products have different prices and are ordered without a tie; with ties you would see the difference.

SQLite example
SELECT category, name, price,
       ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS row,
       RANK() OVER (PARTITION BY category ORDER BY price DESC) AS position
FROM products
WHERE category IN ('Audio', 'Displays')
ORDER BY category, row;

Verified result (4 rows):

categorynamepricerowposition
AudioHeadphones69.911
AudioSpeaker5422
DisplaysMonitor 2724911
DisplaysMonitor 2417922

15. When to use EXISTS instead of IN?

Both check membership. EXISTS stops as soon as it finds the first match and is not affected by nulls. NOT IN with a subquery that contains a null returns no rows; so, for absence, NOT EXISTS is safer.

16. How do you calculate a running total?

With a window function: SUM(column_name) OVER (ORDER BY ...). The ordering defines how the total moves forward, and a unique tiebreaker stops ties from changing the result.

SQLite example
SELECT id, date, total,
       SUM(total) OVER (ORDER BY date, id) AS cumulative
FROM orders
WHERE id <= 105
ORDER BY date, id;

Verified result (5 rows):

iddatetotalcumulative
1012025-05-02128.4128.4
1022025-05-0449.5177.9
1032025-05-1024.9202.8
1042025-05-11179381.8
1052025-05-1569.9451.7

Design, performance and transactions

17. What is an index, and when does it not help?

An index is a helper structure that lets the engine find rows without scanning the whole table. It speeds up filters, joins and sorting on the indexed columns, but it takes up space and slows down writes. It does not help on very small tables, on columns with little variety, or when a function applied to the column prevents its use.

18. What is normalisation?

It means organising data into tables to avoid repetition and contradictions: each fact is stored in one place and tables are related through keys. It reduces update errors, although sometimes data is deliberately denormalised to speed up read queries.

19. What are transactions and what does ACID mean?

A transaction groups several operations that must all happen together or not at all. ACID sums up its guarantees: atomicity (all or nothing), consistency (the rules are respected), isolation (concurrent transactions do not interfere with each other) and durability (what is committed persists). They are controlled with BEGIN, COMMIT and ROLLBACK.

20. How do you analyse a slow query?

Measure first: run EXPLAIN (or EXPLAIN QUERY PLAN in SQLite) to see whether it scans the whole table. Check that filters and joins use indexed columns, that you are not applying functions to the filtered column, and that you are not fetching more columns or rows than you need. Change one thing at a time and measure again.

SQLite example
EXPLAIN QUERY PLAN
SELECT * FROM orders WHERE customer_id = 3;

Verified result (1 row):

detail
SCAN orders

How to prepare

Good preparation combines practice and review: work through the JOIN and aggregate exercises, go over the syntax with the SQL cheat sheet and look things up in the glossary when an answer is not clear to you. To understand the most common mistakes, read why NULL does not return rows and why a JOIN duplicates rows.