SQL interview questions with answers and practice tasks

Interviews for data analyst, finance, engineering and IT roles test SQL in two ways: you explain a concept, or you write a query on the spot. Below are the questions that come up again and again, grouped by level, each with a short answer, plus interview-style tasks you can solve right in your browser.

These are common topics, not questions from any particular company. The answers are kept short on purpose: in an interview, two or three clear sentences and a small example land better than a lecture. Examples use our practice database for an office supplies store, with customers, orders and employees.

New: SQL 50, 50 interview practice questions

Basic, intermediate and advanced, set in an online shop, finance, marketing and HR: cancellation rate, gaps in invoice numbers, top 3 per category, median, retention and more. With topic filters, a stopwatch and the typical follow-up question for every answer.

Go to SQL 50

Basics: questions for any role that uses SQL

1. What's a primary key, and what's a foreign key?

A primary key identifies each row uniquely and can't be empty, like customer_id in the customers table. A foreign key is a column that points at another table's primary key: orders.customer_id refers to customers.customer_id. That lets the database refuse an order for a customer who doesn't exist. More in primary and foreign keys.

2. In what order does the database process a query?

Not in the order you write it. Logically it goes FROM and JOIN, then WHERE, GROUP BY, HAVING, then SELECT, DISTINCT, ORDER BY and finally LIMIT. A lot of rules follow from this: WHERE can't see totals yet, which is why HAVING exists, and ORDER BY can use the aliases from SELECT because it comes later. See SQL order of execution.

3. What's the difference between DELETE, TRUNCATE and DROP?

DELETE removes rows: with WHERE only some, without WHERE all of them. TRUNCATE empties the whole table in one go and leaves the table in place. DROP TABLE removes the table itself, structure and all. The detail interviewers like: in MySQL, TRUNCATE causes an implicit commit and can't be rolled back, while PostgreSQL and SQL Server let you roll it back inside a transaction. SQLite has no TRUNCATE at all; there, DELETE FROM table_name without WHERE clears the table with a fast shortcut. See DELETE.

4. What's the difference between UNION and UNION ALL?

Both stack the results of two queries on top of each other. UNION removes duplicate rows, UNION ALL keeps everything and is faster because it skips that step. If duplicates can't occur, or you want them, use UNION ALL. Both queries need the same number of columns with compatible types. See UNION.

5. How do you return only the first ten rows?

In MySQL, PostgreSQL and SQLite with LIMIT 10 at the end, in SQL Server with SELECT TOP (10) .... The part that matters more: without ORDER BY there's no telling which ten rows you get. "The ten biggest customers" always means ORDER BY plus LIMIT. See ORDER BY.

Warm-up: the three newest orders

Many interviews open with a small task like this one: sort and limit. It is free and takes a minute.

Task The dashboard should show the three most recent orders. Show order_id, order_date and status for those three orders, newest first.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

Joins: the biggest group of questions

6. What's the difference between INNER JOIN and LEFT JOIN?

An INNER JOIN keeps only rows that have a match on both sides. A LEFT JOIN keeps every row from the left table and fills in NULL where nothing matches on the right. Customers and their orders: INNER JOIN shows only customers who have ordered, LEFT JOIN shows all customers. See SQL JOIN and LEFT JOIN.

7. How do you find records with no match?

LEFT JOIN, then check for NULL: FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id WHERE o.order_id IS NULL returns customers who never ordered. WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id) does the same job. Always test a column on the right that's never empty in real rows, ideally its key. See EXISTS.

8. With a LEFT JOIN, does a condition go in ON or in WHERE?

A favorite trap. A condition on the right-hand table inside ON only decides which rows count as a match, and every left row survives. The same condition in WHERE runs after the join and throws out the rows with NULL, so your LEFT JOIN quietly behaves like an INNER JOIN.

9. Why does a join suddenly return more rows, with totals that are too high?

Because one side has several matches. A customer with three orders shows up three times after the join, so summing a column from the customers table counts it three times. The fix is to aggregate the "many" side first (GROUP BY in a subquery or CTE) and join afterwards. A good line in an interview: "First I check whether the relationship is one-to-one or one-to-many."

10. What's a self join?

Joining a table to itself under two different aliases. The classic case is employees and their managers stored in the same table, with manager_id pointing at employee_id. See self join.

11. What are FULL OUTER JOIN and CROSS JOIN?

A FULL OUTER JOIN keeps unmatched rows from both sides. MySQL doesn't support it, so you combine a LEFT and a RIGHT JOIN with UNION; SQLite has had it since version 3.39.0. A CROSS JOIN pairs every row with every other row: 12 customers times 12 products gives 144 rows. Rarely what you want, but handy for building every combination of, say, month and store.

Try it: customers who never got a delivery

This task combines questions 7 and 8, and it's exactly how it tends to show up in live coding.

Task An interview classic with a twist: sales wants to contact customers who have never received a delivery. Show customer_id and name for every customer without a single order whose status is 'delivered'. Customers who only have open or cancelled orders count. Use LEFT JOIN.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

GROUP BY, HAVING and aggregate functions

12. What's the difference between WHERE and HAVING?

WHERE filters individual rows before grouping. HAVING filters groups after grouping, so it can use aggregate functions: HAVING COUNT(*) > 2. Anything that's about single rows belongs in WHERE, even if it would also work in HAVING, because then the database groups fewer rows. See HAVING.

13. What do COUNT(*), COUNT(column) and COUNT(DISTINCT column) count?

COUNT(*) counts rows. COUNT(phone) only counts rows where phone isn't NULL. COUNT(DISTINCT city) counts different values, also ignoring NULL. On the practice database's customers, COUNT(*) gives 12 and COUNT(phone) gives 9, because three customers have no number on file. See COUNT.

14. Why must every column in SELECT be in GROUP BY or inside an aggregate?

Because each group turns into exactly one result row. If name is in SELECT but only city is in GROUP BY, there are several names per city and no single right answer. Most databases reject the query, and so does MySQL as long as its default ONLY_FULL_GROUP_BY mode is on. SQLite doesn't enforce the rule and picks a value from some row in the group. Don't rely on that. See GROUP BY.

15. What's the difference between DISTINCT and GROUP BY?

Without an aggregate, SELECT DISTINCT city FROM customers and SELECT city FROM customers GROUP BY city return the same thing. DISTINCT means "each row once", GROUP BY means "collapse rows so I can calculate per group". As soon as you want to count or add up, you need GROUP BY. See DISTINCT.

Try it: customers with more than 1,000 in revenue

A typical live task: join, filter rows, group, then filter the groups, all in one query.

Task A classic interview task: which customers brought in more than 1,000 in revenue? Show customer_id and revenue (the sum of quantity times unit_price from the order items) for every customer whose revenue is above 1000. Cancelled orders don't count. Use GROUP BY and HAVING.

orders 19 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
102022026-06-16cancelled8
order_items 39 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9
102053449

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

NULL: where most of the traps are

16. Why does WHERE salary = NULL find nothing?

NULL means "unknown", not zero and not blank. Comparing anything with an unknown value gives unknown, which is neither true nor false, and WHERE only keeps rows where the condition is true. The right way is WHERE salary IS NULL. For the same reason, WHERE salary <> 62400 won't return the rows with no salary. See SQL NULL.

17. How do SUM, AVG and COUNT handle NULL?

SUM, AVG, MIN, MAX and COUNT(column) skip NULL values; only COUNT(*) counts every row. With AVG this matters: the average is taken over the rows that have a value, not over all rows. If a missing value should count as 0, write AVG(COALESCE(salary, 0)). Which one is right depends on the question, and saying so is exactly what interviewers want to hear. See aggregate functions.

18. Why does NOT IN suddenly return nothing?

If the list or subquery after NOT IN contains a NULL, x NOT IN (1, 2, NULL) is never true, only unknown at best, so the result is empty. NOT EXISTS doesn't have this problem, which makes it the safer choice when the column can contain NULL.

Try it: NULL in a condition

This level 1 exercise is free and shows how easily rows with NULL slip through the cracks.

Task HR is reviewing pay. Show first_name, last_name and salary for everyone earning less than 42000, plus everyone who doesn't have a salary entered yet.

employees 10 rows, 7 columns
employee_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147

Window functions, CTEs and subqueries

19. What's a window function, and how is it different from GROUP BY?

GROUP BY collapses rows: many go in, one comes out. A window function calculates across a set of rows but keeps every row: SUM(salary) OVER (PARTITION BY department) puts the department's salary total next to each employee. You can spot one by the OVER keyword. MySQL has supported window functions since 8.0, SQLite since 3.25.0. See window functions.

20. What's the difference between ROW_NUMBER, RANK and DENSE_RANK?

All three number rows in a given order. On a tie, ROW_NUMBER still hands out different numbers (1, 2, 3), RANK gives the same number and then leaves a gap (1, 1, 3), and DENSE_RANK gives the same number with no gap (1, 1, 2). Pick the one that matches what a tie should mean.

21. How do you find the second-highest salary?

DENSE_RANK() OVER (ORDER BY salary DESC) in a subquery, then WHERE rnk = 2 outside it. Without a window function: SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees). The weakest answer is ORDER BY salary DESC LIMIT 1 OFFSET 1, because with tied salaries it returns the second row instead of the second amount. Point that out yourself and you'll stand out.

Try it: the second-highest salary

Task The question from nearly every SQL interview: who earns the second-highest salary? Show first_name, last_name and salary for everyone on the second-highest salary amount. Careful: a second managing director joined in April, so two people share the top salary. You want the second-highest amount, not the second row. Use a window function.

employees 11 rows, 7 columns
employee_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147
12JamesPorterManagement936002026-04-01NULL

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

22. What's a CTE, and when do you use one instead of a subquery?

A CTE is a named intermediate query placed before the main query with WITH: WITH revenue AS (SELECT ...) SELECT ... FROM revenue. It makes long queries readable, since you read the steps from top to bottom, and you can refer to it more than once in the same query. For a single short step, a subquery is often just as good. See CTEs and subqueries.

23. How do you calculate a running total or the change from last month?

Both with window functions over rows sorted by month: SUM(revenue) OVER (ORDER BY month) adds up to the current row, and LAG(revenue) OVER (ORDER BY month) fetches the previous row's value, so revenue - LAG(revenue) OVER (ORDER BY month) is the change. See running totals and LAG and LEAD.

24. How do you find duplicates?

First agree on what counts as a duplicate, meaning which columns have to match. Then GROUP BY name, city HAVING COUNT(*) > 1 lists the duplicated combinations. To see every affected row with its ID, use COUNT(*) OVER (PARTITION BY name, city). For a cleanup, ROW_NUMBER() OVER (PARTITION BY name, city ORDER BY customer_id) marks everything from the second copy onward. See find duplicates.

Try it: duplicate customers after an import

Task After a data import, some customers appear twice in the table under a new customer_id. Before anyone cleans up, accounting wants to see every affected row: show customer_id, name and city for each row whose combination of name and city occurs more than once. The same name in a different city is a different person.

customers 15 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
21Emily CarterChicagoUSA2026-05-04ConsumerNULL
22Northline Printing CoTorontoCanada2026-05-04Business416-555-0133
23Daniel KimPortlandUSA2026-05-04ConsumerNULL

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Performance and indexes

25. What's an index, and what does it cost?

An index is a sorted extra structure on one or more columns, much like the index at the back of a book. With it, the database can find matching rows without reading the whole table. The price: every index takes storage and has to be updated on every INSERT, UPDATE and DELETE. So you index columns you often search, join or sort on, not every column. PostgreSQL creates an index automatically for primary keys and UNIQUE constraints.

26. Why isn't my query using the index?

Common reasons: the column is wrapped in a function, as in WHERE substr(order_date, 1, 4) = '2026', where a range like WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01' works better. A LIKE pattern starts with a wildcard ('%LLC'), so the index's sort order is no help. Or the query needs a large share of the table anyway, and the database decides reading it all is cheaper.

27. A query is slow. Where do you start?

Look at the execution plan instead of guessing. In MySQL and PostgreSQL that's EXPLAIN; EXPLAIN ANALYZE actually runs the query and adds real timings. In SQLite, EXPLAIN QUERY PLAN shows whether a table is read in full (SCAN) or searched selectively (SEARCH). In SQL Server Management Studio, switch on Include Actual Execution Plan from the Query menu before running, or use SET STATISTICS XML ON. Then check: is an index missing, is a big table joined without a useful condition, is SELECT * pulling columns nobody needs?

Changing data and transactions

28. What's a transaction, and what does ACID mean?

A transaction groups several changes that only count together: a transfer debits one account and credits another, or neither happens. ACID stands for atomicity (all or nothing), consistency (rules such as foreign keys still hold), isolation (concurrent transactions don't trip over each other) and durability (once committed, the change survives a crash). See transactions.

29. How do you make an UPDATE or DELETE safe?

Run the same condition as a SELECT first and check which rows, and how many, it hits. Then run the change inside a transaction, check the number of affected rows, and only then COMMIT, otherwise ROLLBACK. An UPDATE without WHERE changes every row in the table. See UPDATE.

30. What's the difference between INSERT INTO ... VALUES and INSERT INTO ... SELECT?

VALUES inserts rows with fixed values. SELECT inserts the result of a query, for example copying a year's orders into an archive table. Either way, name the target columns explicitly so the statement doesn't break when someone adds a column to the table later. See INSERT.

How to handle the live-coding part

You'll often get a table schema and a question, then write the query on a laptop, in a browser tool or on a whiteboard. They're watching how you work, not just the result:

  • Clarify before you type: what happens on a tie? Do cancelled orders count? What about missing values?
  • Think out loud. Say which tables you need and how they connect, then build the query step by step.
  • Sanity-check the result: is the row count about right? Does anyone show up twice because a join multiplied rows?
  • Raise edge cases yourself: NULLs, duplicates, empty groups. That's what separates people who use SQL every day from people who memorized it.
  • If you can't remember a function's exact name, say so and describe what it should do. Most teams look up syntax all the time.

Practice under real conditions

For the live-coding part there is SQL 50: 50 interview-style questions with a stopwatch, sorted by difficulty and topic. If an online test on HackerRank comes before the interview, HackerRank SQL practice explains what it covers and which questions match. If you'd like to gauge your level first, the SQL test is a good start. Everything on this page is covered in the SQL course, from SELECT to window functions, with exercises checked on the server against hidden data. At the end of the course, the final test covers the whole syllabus, including the topics on this page.

FAQ

Which SQL dialect will the interview use?

Usually whatever the company runs, often SQL Server, PostgreSQL or MySQL. The fundamentals are the same everywhere. It's fine to ask which database they use, and to mention differences like LIMIT versus TOP when a task touches on them.

How much SQL do data analyst interviews expect?

For sure: SELECT with WHERE, joins, GROUP BY with HAVING, CASE, and handling NULL. Often window functions and CTEs too. Indexes and transactions tend to go deeper for engineering and database admin roles.

Can I ask questions during a live SQL test?

Yes, and you should. Asking about ties, NULLs and duplicates shows you're thinking about the data. Many tasks are left a little open on purpose to see whether you do.

Do the tasks on this page need to be solved a particular way?

We check the result, not the text of your query, and we check it against hidden data as well. A keyword only has to appear where the task asks for it explicitly: LEFT JOIN, GROUP BY with HAVING, or a window function.

Ready for the practical part?

Work on the topics that still feel shaky in the SQL course. Every lesson has exercises right in your browser, nothing to install.

Take the SQL test Go to the SQL course

Write to us

Choose language

Select your preferred language