🎓 A1Learner
🔍

Home / Blog / Databases / SQL

Top 50 SQL Interview Questions with Answers

Databases · SQL · 28 min read

Fifty SQL interview questions with answers and runnable queries on two small tables: joins, grouping, subqueries, window functions, indexes, and design.

The two tables every answer uses

I first met these questions in 2019, in a glass meeting room in Reading, when a hiring manager slid a printed sheet across the table and asked me to write the second-highest salary query on a whiteboard with no computer in sight. I wrote LIMIT with OFFSET. She smiled, pointed at the tie at the top, and asked what happened next. That afternoon I learned the difference between counting rows and ranking values, and this sheet is the version of that afternoon I wish I had read first.

This sheet holds fifty questions, grouped by topic. Each answer is short, and each query runs on the two tables below. Nothing here needs a large dataset. Eight people and four departments are enough to catch every mistake in this sheet, because the tables carry two tied salaries, one missing salary, and one department with no people at all.

The employees table holds eight people. Ana earns 72,000 and works in department 1. Ben earns 95,000 in the same department. Cleo earns 88,000 in department 2, Dan earns 95,000 there too, and Hana earns 54,000 alongside them. Eli earns 61,000 in department 1. Fay earns 88,000 in department 3, and Gus, also in department 3, has no salary on record. Two salaries repeat, and one salary is missing. That blank will matter later, when the questions turn to NULLs.

The departments table holds four rows. Department 1 is Engineering, department 2 is Sales, department 3 is Support, and department 4 is Legal. Legal has no people in it. That empty department is deliberate. Several questions below only make sense because one side of a join can come up empty.

The queries were run on SQLite 3.45.1, and the outputs shown are the real outputs. One habit will serve you well in an interview. Test each query on a table small enough to verify by hand before you trust it on real data. The SQL course here teaches SELECT, filtering, joins, grouping, subqueries, window functions, CTEs, and indexes in full. Transactions and normalization are not in the course yet, and this sheet picks up where those lessons stop.

1. What does SQL stand for, and what is it used for?

SQL stands for Structured Query Language. It is the language used to ask a relational database for data, and to change what the database holds.

A relational database stores data in tables. A table holds rows in a list, and each row is one record. SQL is how you read rows, add rows, change rows, and remove rows. Every question in this sheet is one of those four jobs, dressed up as an interview question.

2. What is the difference between a database and a table?

A database is the whole collection. A table is one list inside it. The employees table holds people. The departments table holds departments. Both tables live in one database.

Think of the database as a filing cabinet and each table as one drawer. A query names the drawer it reads from, and a join reads from two drawers at once. The distinction matters in an interview because a vague answer here usually means the next answers will be vague too.

3. Why name columns instead of SELECT *?

SELECT * returns every column, in whatever order the table defines them. Naming columns returns only the columns you asked for, in the order you asked for them. The second version is clearer to read, cheaper to move across a network, and safe when someone later adds a column to the table.

The query below returns eight rows and two columns. It is the shape of most answers in this sheet: a few named columns, one table, and a condition that says which rows count.

SELECT name, salary FROM employees ORDER BY name;

Output:
name | salary
Ana | 72000
Ben | 95000
Cleo | 88000
Dan | 95000
Eli | 61000
Fay | 88000
Gus | 
Hana | 54000

4. What does DISTINCT do?

DISTINCT removes duplicate values from a result. Without it, a column with repeated values shows each repeat. With it, each value appears once.

Three departments have people in them, so the query below returns three rows: 1, 2, and 3. Department 4 never appears, because no employee row carries it. DISTINCT answers a question about values, not about rows, and that is why it sits in the SELECT list rather than in a WHERE clause.

SELECT DISTINCT dept_id FROM employees ORDER BY dept_id;

Output:
dept_id
1
2
3

5. How do you sort results, and where do NULLs go?

ORDER BY sorts the result. ASC sorts from low to high, and DESC sorts from high to low. ASC is the default, so a bare ORDER BY salary sorts from the smallest salary upward.

In SQLite, a missing value counts as smaller than any real number. Sorting from high to low therefore puts Gus and his blank salary at the bottom. The query below breaks ties by name, so the order is stable from one run to the next. Without that second sort key, Ben and Dan could swap places between runs, and Cleo and Fay could too.

SELECT name, salary FROM employees ORDER BY salary DESC, name;

Output:
name | salary
Ben | 95000
Dan | 95000
Cleo | 88000
Fay | 88000
Ana | 72000
Eli | 61000
Hana | 54000
Gus | 

6. How do WHERE and HAVING differ?

WHERE filters rows before any grouping happens. HAVING filters groups after grouping happens. That order is the whole difference, and it decides which one you can use.

A condition on a single row, such as a salary above 80,000, belongs in WHERE. A condition on a group, such as an average salary above 80,000, belongs in HAVING, because the average does not exist until the rows are grouped. WHERE cannot see it yet. The Having lesson in the SQL course works through this order, and the pattern returns in question 19 below.

7. How do you find rows with a missing value?

Use IS NULL. A missing value is not equal to anything, including another missing value, so the equals sign can never find it. The test salary = NULL matches zero rows on every database, because comparing anything with NULL gives UNKNOWN rather than true.

The query below returns one row. Gus is the only person with no salary recorded. The opposite test, IS NOT NULL, returns the other seven. The SQL course's NULL Values lesson works through the same rule.

SELECT name FROM employees WHERE salary IS NULL;

Output:
name
Gus

8. What do AND, OR, and NOT do in a WHERE clause?

AND keeps only rows that pass every condition. OR keeps rows that pass at least one condition. NOT flips a condition, keeping the rows it would have rejected.

The query below asks for people in department 1 who earn more than 80,000. Only Ben passes both tests. Ana earns 72,000, so she fails the salary test. Eli earns 61,000, so he fails it too. AND narrows a result. OR widens it. NOT inverts it. Parentheses decide the order when they are mixed, so write them rather than trusting memory.

SELECT name FROM employees WHERE salary > 80000 AND dept_id = 1;

Output:
name
Ben

9. What is a JOIN, and what does INNER JOIN return?

A join connects two tables on a shared value. An inner join keeps only the combinations where both sides agree. A row that finds no partner on the other side simply does not appear.

The query below pairs each employee with the name of their department. All eight employees have a department, so the result has eight rows. Legal never appears, because no employee row points at it. The Inner Join lesson in the SQL course pairs the same two ideas.

SELECT employees.name, departments.dept_name FROM employees INNER JOIN departments ON employees.dept_id = departments.dept_id ORDER BY employees.name;

Output:
name | dept_name
Ana | Engineering
Ben | Engineering
Cleo | Sales
Dan | Sales
Eli | Engineering
Fay | Support
Gus | Support
Hana | Sales

10. What does LEFT JOIN return that INNER JOIN does not?

A left join starts from the left table and keeps all of it. Every left row survives, matched or not. A left row with no partner gets NULL in the right table's columns.

The query below starts from departments, so it is the left table. Engineering, Sales, and Support each appear with their people. Legal appears too, with NULL where the name and salary would go, because it has no people. The result has nine rows: eight matched pairs plus Legal on its own. The Left Join lesson in the SQL course covers it, and the joins article in this blog walks the same idea row by row.

SELECT departments.dept_name, employees.name FROM departments LEFT JOIN employees ON departments.dept_id = employees.dept_id ORDER BY departments.dept_name, employees.name;

Output:
dept_name | name
Engineering | Ana
Engineering | Ben
Engineering | Eli
Legal | 
Sales | Cleo
Sales | Dan
Sales | Hana
Support | Fay
Support | Gus

11. When would you use RIGHT JOIN?

A right join works the other way round from a left join. It holds on to every row from the right table, and puts NULL in the left columns when a row has no partner. The query below returns the same nine rows as question 10, because the tables are simply swapped.

In practice, most writers rarely use it. Turning the tables round and using a left join instead gives the same answer, and most readers find that version easier to follow, because they scan from the main list outward. You will still meet right join in other people's queries, so it is worth knowing. The Right and Full Join lesson in the SQL course covers both.

SELECT departments.dept_name, employees.name FROM employees RIGHT JOIN departments ON employees.dept_id = departments.dept_id ORDER BY departments.dept_name, employees.name;

Output:
dept_name | name
Engineering | Ana
Engineering | Ben
Engineering | Eli
Legal | 
Sales | Cleo
Sales | Dan
Sales | Hana
Support | Fay
Support | Gus

12. What does FULL JOIN return?

A full join returns the whole of both tables. Rows that match sit together, and rows without a partner show up with NULL filling the empty side. Here it returns the same nine rows as the two joins above, because every employee has a department and only Legal lacks people.

SQLite has supported FULL JOIN since version 3.39, and the Right and Full Join lesson in the SQL course teaches it the same way. MySQL has no full join, so writers there build the same result with a UNION of two outer joins. Full join is the right tool when two lists need reconciling, for instance comparing departments against employees to spot both empty departments and unassigned people in one pass.

SELECT departments.dept_name, employees.name FROM departments FULL JOIN employees ON departments.dept_id = employees.dept_id ORDER BY departments.dept_name, employees.name;

Output:
dept_name | name
Engineering | Ana
Engineering | Ben
Engineering | Eli
Legal | 
Sales | Cleo
Sales | Dan
Sales | Hana
Support | Fay
Support | Gus

13. What is a self join?

A self join joins a table to itself. Two aliases give the two copies different names, so the query can compare rows from the same table against each other.

The query below finds everyone who shares a department with Ana. Ana is in department 1, so the answer is Ben and Eli. The condition e2.name <> 'Ana' keeps Ana herself out of the result. The Self Join lesson in the SQL course works the same example.

SELECT e2.name FROM employees e1 JOIN employees e2 ON e1.dept_id = e2.dept_id WHERE e1.name = 'Ana' AND e2.name <> 'Ana' ORDER BY e2.name;

Output:
name
Ben
Eli

14. What is a CROSS JOIN, and why is it dangerous?

A cross join returns every combination of rows from two tables, with no matching condition at all. Eight people times four departments gives thirty-two rows.

It is dangerous because it is usually an accident. A join written without an ON clause, or with the wrong one, quietly multiplies rows, and a count taken after it looks far too high. If a result is suddenly much bigger than the table it came from, a missing join condition is the first thing to check.

SELECT COUNT(*) AS combinations FROM employees CROSS JOIN departments;

Output:
combinations
32

15. How do you find rows with no match in the other table?

Left join, then keep only the rows where a key from the other table is NULL. The NULL marks the rows that found no partner.

The query below returns Legal, the only department with no people. The same pattern finds customers with no orders, or products never sold. NOT EXISTS gives the same answer and reads well, but the left join version is the one most interviewers expect to see first.

SELECT departments.dept_name FROM departments LEFT JOIN employees ON departments.dept_id = employees.dept_id WHERE employees.id IS NULL;

Output:
dept_name
Legal

16. UNION or UNION ALL: which one keeps duplicates?

UNION stacks two results and removes duplicate rows. UNION ALL stacks them and keeps every row, duplicates included. The two queries must return the same number of columns, with compatible types.

Both queries below ask for department 1, which three employees share. UNION returns one row, because it removes the duplicates. UNION ALL returns six rows, three from each side, because it keeps every row. UNION ALL is faster when duplicates do not matter, because the database skips the work of removing them. The Union lesson in the SQL course stacks results the same way.

SELECT dept_id FROM employees WHERE dept_id = 1 UNION SELECT dept_id FROM employees WHERE dept_id = 1;

Output:
dept_id
1

SELECT dept_id FROM employees WHERE dept_id = 1 UNION ALL SELECT dept_id FROM employees WHERE dept_id = 1;

Output:
dept_id
1
1
1
1
1
1

17. What does COUNT(*) count, and how is it different from COUNT(salary)?

COUNT(*) counts rows. COUNT(salary) counts rows where salary is not NULL. The difference is exactly the rows with a missing value.

The query below returns 8 and 7. Eight people exist. Seven have a salary recorded. Gus is the gap. COUNT(DISTINCT salary) would return 5, because two salaries repeat and one is missing. The Count lesson in the SQL course draws the same line.

SELECT COUNT(*) AS people, COUNT(salary) AS with_salary FROM employees;

Output:
people | with_salary
8 | 7

18. What does GROUP BY do?

GROUP BY collects rows with the same value together, so an aggregate function can summarise each collection separately. Without it, an aggregate summarises the whole table as one group.

The query below returns three rows, one per department that has people. Engineering averages 76,000, Sales averages 79,000, and Support averages 88,000. Support averages only Fay's salary, because AVG ignores the missing value. Legal never appears, because a group needs at least one row. The Group By lesson in the SQL course groups the same way.

SELECT dept_id, AVG(salary) AS avg_salary FROM employees GROUP BY dept_id ORDER BY dept_id;

Output:
dept_id | avg_salary
1 | 76000.0
2 | 79000.0
3 | 88000.0

19. Why does HAVING exist when WHERE already filters?

WHERE cannot test an aggregate, because aggregates are computed after WHERE runs. HAVING tests the grouped result, so it can ask about an average, a count, or a sum.

The query below keeps only the departments whose average salary is above 80,000. Support passes at 88,000. Engineering fails at 76,000, and Sales fails at 79,000. The pattern is always the same: GROUP BY first, HAVING second, and no aggregate in WHERE. The Having lesson in the SQL course keeps only the groups that pass.

SELECT dept_id, AVG(salary) AS avg_salary FROM employees GROUP BY dept_id HAVING AVG(salary) > 80000;

Output:
dept_id | avg_salary
3 | 88000.0

20. What is the difference between MIN/MAX and ORDER BY with LIMIT 1?

MIN and MAX return a value. ORDER BY with LIMIT 1 returns a row. That difference decides which one answers the question you were actually asked.

MAX(salary) returns 95,000, a number with no name attached. Ben and Dan both earn it, and the number alone cannot say which one you mean. ORDER BY with LIMIT 1 returns one of them, but which one is not promised, because the tie is broken by the database, not by the query. When the question is about a person, name the tie-breaker. When the question is about a number, MIN and MAX are enough. The Min and Max lesson in the SQL course covers both.

SELECT MAX(salary) AS top_salary FROM employees;

Output:
top_salary
95000

21. How do you find the highest salary in each department?

Group by department, then take the maximum in each group. The grouping does the splitting, and MAX does the picking.

Three rows come back. Engineering tops out at 95,000, Sales tops out at 95,000, and Support tops out at 88,000. Legal is absent again, for the same reason as before: no rows, no group. A WHERE clause could narrow the rows first, for instance to people hired after a date, and the maximum would then be the maximum among the survivors.

SELECT dept_id, MAX(salary) AS top_salary FROM employees GROUP BY dept_id ORDER BY dept_id;

Output:
dept_id | top_salary
1 | 95000
2 | 95000
3 | 88000

22. How do you find departments with more than two employees?

Count the rows in each group, then keep the groups whose count passes the test. The count belongs in HAVING, because it is a property of the group, not of a single row.

Engineering has three people and Sales has three people, so both pass. Support has two people, so it fails. The result names two departments. The same shape answers most size questions: groups with more than ten orders, customers with more than five purchases, products with no sales at all.

SELECT dept_id, COUNT(*) AS people FROM employees GROUP BY dept_id HAVING COUNT(*) > 2 ORDER BY dept_id;

Output:
dept_id | people
1 | 3
2 | 3

23. What happens when you SELECT a column that is not in GROUP BY?

Most databases reject the query. A column that is neither grouped nor aggregated has no single value inside a group, so the database refuses to guess. SQLite is the exception. It allows the query and picks a value from one row of the group.

SQLite goes further than merely allowing it. When the query uses MAX or MIN, the other columns come from the row that holds that extreme value. The query below therefore returns the top earner of each department by name: Ben, Dan, and Fay. That is a SQLite habit, not a SQL rule, and relying on it makes the query fail on other databases. The safe rule is to group by every column that is not inside an aggregate.

SELECT dept_id, name, MAX(salary) AS top_salary FROM employees GROUP BY dept_id ORDER BY dept_id;

Output:
dept_id | name | top_salary
1 | Ben | 95000
2 | Dan | 95000
3 | Fay | 88000

24. How do you find the second highest salary?

Sort the salaries from high to low, give each distinct pay figure a rank, and keep rank 2. DENSE_RANK counts distinct pay figures, so people on the same pay share a rank and the next figure takes the next number, with no gap left behind.

Cleo and Fay come back, both on 88,000. Ask for rank 3 instead and Ana appears alone on 72,000. Ask for rank 10 and nothing comes back, which is the honest answer for an eight-person table. The LIMIT shortcut gives the wrong person here. It skips one row rather than one rank, so the second person at the top counts as rank two. That trap has its own full walkthrough in the blog article on finding the Nth highest salary.

SELECT name, salary FROM (SELECT name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM employees) WHERE r = 2 ORDER BY name;

Output:
name | salary
Cleo | 88000
Fay | 88000

25. What is a subquery?

A subquery is a query nested in a second query. The nested query runs first and hands its result to the outer query, which uses it like a value or a list.

The query below finds the people who earn more than the average salary. The inner query computes the average, which is 79,000. The outer query then keeps the four people above it: Ben, Cleo, Dan, and Fay. The Subqueries lesson in the SQL course runs the same shape. Subqueries also appear as lists with IN, which question 30 covers.

SELECT name, salary FROM employees WHERE salary > (SELECT AVG(salary) FROM employees) ORDER BY name;

Output:
name | salary
Ben | 95000
Cleo | 88000
Dan | 95000
Fay | 88000

26. What is the difference between a correlated and a non-correlated subquery?

A non-correlated subquery runs once, on its own, and hands one result to the outer query. A correlated subquery refers to the outer query, so it runs once per outer row, with a different value each time.

The query below finds people who earn more than their own department's average. The inner query reads the department of the current outer row, so Engineering is compared against 76,000, Sales against 79,000, and Support against 88,000. Ben, Cleo, and Dan pass. Fay earns exactly her department's average, so she does not. Correlated subqueries are not in the SQL course, so this pattern is worth practising on its own.

SELECT name, salary FROM employees e1 WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e2.dept_id = e1.dept_id) ORDER BY name;

Output:
name | salary
Ben | 95000
Cleo | 88000
Dan | 95000

27. What is a CTE, and when is it better than a subquery?

A CTE, or common table expression, is a named temporary result defined once with WITH and used like a table in the main query. It does the same work as a subquery, but it has a name, so a long query stays readable.

The query below names the department averages once, then compares each person against their own average. It returns the same three people as question 26: Ben, Cleo, and Dan. A CTE earns its keep when the same subquery would otherwise appear twice, or when the query has grown past the point where nesting stays readable. CTEs are now in the SQL course too, in their own lessons, and this sheet covers them here as well.

WITH dept_avg AS (SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id) SELECT e.name, e.salary FROM employees e JOIN dept_avg d ON e.dept_id = d.dept_id WHERE e.salary > d.avg_sal ORDER BY e.name;

Output:
name | salary
Ben | 95000
Cleo | 88000
Dan | 95000

28. How do you find duplicate values?

Group by the value, count the rows in each group, and keep the groups with more than one row. The pattern is the same as question 22, with the salary column in place of the department.

Two salaries repeat here. 95,000 appears twice, and 88,000 appears twice. The other salaries appear once. The missing salary forms its own group with one row, so it fails the more-than-one test and never appears. This query finds duplicate values. Removing duplicate rows is a different job, and it needs a way to tell the copies apart, such as a row id.

SELECT salary, COUNT(*) AS times FROM employees GROUP BY salary HAVING COUNT(*) > 1 ORDER BY salary DESC;

Output:
salary | times
95000 | 2
88000 | 2

29. What does EXISTS do?

EXISTS tests whether a subquery returns any row at all. It returns true on the first row found and false when nothing comes back, and it never returns the rows themselves.

The query below asks which departments have at least one person earning more than 90,000. Engineering passes because of Ben, and Sales passes because of Dan. Support fails, because Fay earns 88,000, and Legal fails, because it has nobody at all. EXISTS stops at the first match, so it is often the fastest way to ask a yes-or-no question about a related table. EXISTS is not in the SQL course, so practise it here rather than assuming it behaves like IN.

SELECT dept_name FROM departments d WHERE EXISTS (SELECT 1 FROM employees e WHERE e.dept_id = d.dept_id AND e.salary > 90000) ORDER BY dept_name;

Output:
dept_name
Engineering
Sales

30. What is the difference between IN and EXISTS?

IN checks whether a value sits in a list. EXISTS checks whether a subquery returns any row. For a small fixed list, IN reads plainly. For a related table, EXISTS usually reads better and stops at the first match.

The two also differ on missing values, and the difference is a classic trap. The query below looks for people whose salary is not in the list 95,000 and NULL. It returns nothing at all. Comparing any salary with NULL gives UNKNOWN, so NOT IN rejects every row, including the people whose salaries are nowhere near the list. Never put a value that might be missing inside a NOT IN list. Use NOT EXISTS instead, or filter the missing values out first.

SELECT name FROM employees WHERE salary NOT IN (95000, NULL) ORDER BY name;

Output:
name

31. How do you find the Nth highest salary without LIMIT?

Count how many distinct salaries sit above each person's salary. The person at rank N has exactly N minus 1 distinct salaries above them. For N equals 2, that count is 1.

The query below returns Cleo and Fay, both on 88,000, because only 95,000 sits above them. It works on any database, including ones without window functions, and it treats ties correctly, because it counts distinct values rather than rows. The window-function version in question 24 is shorter, and the blog article on finding the Nth highest salary compares all three approaches side by side.

SELECT name, salary FROM employees e1 WHERE (SELECT COUNT(DISTINCT salary) FROM employees e2 WHERE e2.salary > e1.salary) = 1 ORDER BY name;

Output:
name | salary
Cleo | 88000
Fay | 88000

32. What is a window function?

A window function computes a value across a set of rows that are related to the current row, without collapsing those rows. The result keeps every row and adds a computed column beside it.

The query below adds the overall average salary, 79,000, as a column on the first three rows. The average is computed over the whole table, and every row keeps its own name and salary. That is the difference from GROUP BY, which would collapse the table into one row. The OVER clause defines the window: which rows the function looks at. Window functions are now in the SQL course too, in their own lessons. Questions 33 to 38 all use them, and this sheet covers the ground the course leaves open.

SELECT name, salary, AVG(salary) OVER () AS avg_salary FROM employees ORDER BY name LIMIT 3;

Output:
name | salary | avg_salary
Ana | 72000 | 79000.0
Ben | 95000 | 79000.0
Cleo | 88000 | 79000.0

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

All three hand out ranks, and all three treat ties differently. ROW_NUMBER never shares a rank. It hands out 1, 2, 3 in order, and tied rows get different numbers in an order the database chooses. RANK shares a rank among tied rows and then leaves a gap. DENSE_RANK shares a rank and leaves no gap.

The query below ranks all eight people by salary. Ben and Dan share the top salary. ROW_NUMBER gives them 1 and 2. RANK gives them both 1, then jumps to 3 for Cleo and Fay. DENSE_RANK gives them both 1, then 2 for Cleo and Fay. The full ranking is worth reading row by row, because the three columns disagree only where ties exist, and ties are exactly where interviews test you.

SELECT name, salary, ROW_NUMBER() OVER (ORDER BY salary DESC, name) AS rn, RANK() OVER (ORDER BY salary DESC) AS rnk, DENSE_RANK() OVER (ORDER BY salary DESC) AS drnk FROM employees ORDER BY salary DESC, name;

Output:
name | salary | rn | rnk | drnk
Ben | 95000 | 1 | 1 | 1
Dan | 95000 | 2 | 1 | 1
Cleo | 88000 | 3 | 3 | 2
Fay | 88000 | 4 | 3 | 2
Ana | 72000 | 5 | 5 | 3
Eli | 61000 | 6 | 6 | 4
Hana | 54000 | 7 | 7 | 5
Gus |  | 8 | 8 | 6

34. How do you find the top earner in each department?

Rank the rows inside each department, then keep rank 1. PARTITION BY restarts the ranking for each department, so every department gets its own number 1.

The query below returns three people: Ben for Engineering, Dan for Sales, and Fay for Support. Legal has nobody, so it never appears. The same shape finds the top three per group by keeping ranks 1 to 3, and the newest row per group by ordering on a date instead of a salary. It is the single most useful window-function pattern in interviews.

SELECT name, salary, dept_id FROM (SELECT name, salary, dept_id, ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC, name) AS rn FROM employees) WHERE rn = 1 ORDER BY dept_id;

Output:
name | salary | dept_id
Ben | 95000 | 1
Dan | 95000 | 2
Fay | 88000 | 3

35. How do you compute a running total?

Add a running sum over an ordered window. SUM with an OVER clause and an ORDER BY inside it adds each row to the total of the rows before it, so the last row holds the grand total.

The query below walks the people in id order. The total reaches 72,000 after Ana, 167,000 after Ben, 255,000 after Cleo, 350,000 after Dan, 411,000 after Eli, and 499,000 after Fay. Gus adds nothing, because his salary is missing and SUM skips missing values. Hana brings the total to 553,000, which matches the sum of all seven recorded salaries. A running total over a date column gives a cumulative sales curve, and the same shape works for a running count.

SELECT name, salary, SUM(salary) OVER (ORDER BY id) AS running_total FROM employees ORDER BY id;

Output:
name | salary | running_total
Ana | 72000 | 72000
Ben | 95000 | 167000
Cleo | 88000 | 255000
Dan | 95000 | 350000
Eli | 61000 | 411000
Fay | 88000 | 499000
Gus |  | 499000
Hana | 54000 | 553000

36. How do you compare each salary with the department average?

Compute the department average as a window, then subtract it from each salary. PARTITION BY keeps the average inside the department, so each person is measured against their own team rather than the whole company.

Ben sits 19,000 above the Engineering average of 76,000. Ana sits 4,000 below it, and Eli sits 15,000 below it. In Sales, Dan sits 16,000 above the average of 79,000, Cleo sits 9,000 above it, and Hana sits 25,000 below it. Fay sits exactly on the Support average of 88,000, so her difference is zero. Gus has no salary, so his difference is blank too. The query does in one pass what a join to a grouped subquery would do in two.

SELECT name, salary, salary - AVG(salary) OVER (PARTITION BY dept_id) AS diff_from_dept_avg FROM employees ORDER BY dept_id, salary DESC;

Output:
name | salary | diff_from_dept_avg
Ben | 95000 | 19000.0
Ana | 72000 | -4000.0
Eli | 61000 | -15000.0
Dan | 95000 | 16000.0
Cleo | 88000 | 9000.0
Hana | 54000 | -25000.0
Fay | 88000 | 0.0
Gus |  | 

37. What is the difference between a window function and GROUP BY?

GROUP BY collapses rows. A window function keeps them. That single difference decides which one fits the question.

GROUP BY with an average returns one row per department, and the individual names are gone. A window function with the same average returns every person, each carrying their department's average beside their own salary. Use GROUP BY when the answer is one row per group, such as a report of averages. Use a window function when the answer needs the detail rows as well, such as flagging the people above their department's average.

38. What does PARTITION BY do?

PARTITION BY splits the rows into groups and restarts the window function inside each group. It is the window-function version of GROUP BY, except the rows are never collapsed.

The query below shows the average salary beside every person, computed inside their own department. Engineering rows carry 76,000, Sales rows carry 79,000, and Support rows carry 88,000. The people stay visible, which is the point. Without PARTITION BY, the average would be the whole-company figure of 79,000 on every row, and the department detail would be lost.

SELECT name, dept_id, AVG(salary) OVER (PARTITION BY dept_id) AS dept_avg FROM employees ORDER BY dept_id, name;

Output:
name | dept_id | dept_avg
Ana | 1 | 76000.0
Ben | 1 | 76000.0
Eli | 1 | 76000.0
Cleo | 2 | 79000.0
Dan | 2 | 79000.0
Hana | 2 | 79000.0
Fay | 3 | 88000.0
Gus | 3 | 88000.0

39. What is an index?

An index is an extra lookup structure that sits next to a table. It lists values from one or more columns in order, and each entry notes where its full row lives, so the database can jump to rows instead of reading the whole table.

The database maintains that list without being asked. Adding, changing, or removing a row updates every index on the table at the same time. Keeping that list current costs work, and the next question covers what that work buys and what it charges. The Indexes lesson in the SQL course builds the same structure, and the blog article on how indexes work explains the lookup step by step.

CREATE INDEX idx_employees_dept ON employees(dept_id);

SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'employees';

Output:
name
idx_employees_dept

40. When does an index help, and when does it not?

An index pays off when a query narrows on the indexed column, and only a small share of rows match. A lookup on one department id is the classic case. It helps little when most rows match anyway, because the database must still fetch them all, and the index only adds a step.

It also pays off little on a column where nearly every row holds the same value, such as a flag with two settings, because the index cannot narrow much. It does not help at all when the query wraps the column in a function or starts a pattern with a wildcard, since the sorted order no longer applies. An index changes speed, never results, and every index costs storage and slower writes.

41. What is the difference between a clustered and a non-clustered index?

A clustered index decides the physical order of the rows in the table. A table can have only one, because rows can only sit in one order. A non-clustered index is a separate sorted list with pointers back to the rows, and a table can have several of those.

SQLite stores an ordinary table in rowid order, which behaves like a clustered order on the row id. The index created in question 39 is a non-clustered index: a sorted list of department ids with pointers to the employee rows. The distinction matters most in interviews about SQL Server, where the clustered index is a design decision rather than a default.

42. How do you find a slow query?

Ask the database how it plans to run the query. In SQLite, EXPLAIN QUERY PLAN prints the plan: SCAN means the engine reads every row, and SEARCH USING INDEX means it uses an index to jump to the matching rows.

The check below runs after the index from question 39 was created, and it reports SEARCH USING INDEX. The same check before the index reported SCAN employees, meaning the engine read all eight rows. Eight rows are too few to feel the difference, but the plan is the same shape at eight rows and at eight million. When a query is slow, read the plan before changing the query.

EXPLAIN QUERY PLAN SELECT name FROM employees WHERE dept_id = 2;

Output:
id | parent | notused | detail
3 | 0 | 0 | SEARCH employees USING INDEX idx_employees_dept (dept_id=?)

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

DELETE removes rows. With a WHERE clause it removes only the matching rows, and without one it removes them all. TRUNCATE removes all rows at once, quickly, without logging each row. DROP removes the table itself, rows and structure together.

SQLite has no TRUNCATE, so DELETE without a WHERE clause is the equivalent there. The demo below copies the table first, deletes the rows with a missing salary from the copy, and counts what is left: seven. DELETE and DROP change data, so run them on a copy first when unsure. A backup is cheaper than a rebuild.

CREATE TABLE tmp_emp AS SELECT * FROM employees;

DELETE FROM tmp_emp WHERE salary IS NULL;

SELECT COUNT(*) AS remaining FROM tmp_emp;

Output:
remaining
7

44. What is a primary key?

A primary key is the column, or set of columns, that identifies each row. Its values are unique, it never holds NULL, and a table has exactly one of them. It is how the database tells two rows apart when every other column matches.

The demo below creates a small table with id as its primary key, adds Ana with id 1, then tries to add Ben with id 1 as well. The database refuses the second row, because the key must stay unique. The Primary Keys lesson in the SQL course sets the same rule.

CREATE TABLE demo_pk (id INTEGER PRIMARY KEY, name TEXT);

INSERT INTO demo_pk VALUES (1, 'Ana');

INSERT INTO demo_pk VALUES (1, 'Ben');

Output:
IntegrityError: UNIQUE constraint failed: demo_pk.id

45. What is a foreign key?

A foreign key is a column whose values must match a key in another table, or be NULL. It is how the database enforces that a row points at something real, rather than trusting the writer to get it right.

The demo below creates a notes table whose emp_id points at employees.id, adds a note for Ana, then tries a note for employee 99, who does not exist. The database refuses it. SQLite keeps foreign keys off by default, so the PRAGMA line turns them on first. The Foreign Keys lesson in the SQL course enforces the same rule.

PRAGMA foreign_keys = ON;

CREATE TABLE demo_notes (note_id INTEGER PRIMARY KEY, emp_id INTEGER REFERENCES employees(id), note TEXT);

INSERT INTO demo_notes VALUES (1, 1, 'Welcome');

INSERT INTO demo_notes VALUES (2, 99, 'Ghost');

Output:
IntegrityError: FOREIGN KEY constraint failed

46. What is normalization, and what is first normal form?

Normalization is the practice of organising tables so each fact lives in one place. First normal form, the first step, says three things: one value per cell, no repeating groups, and every row identified by a key.

A column holding two names in one cell, such as Ana, Ben, breaks the rule, because the database cannot filter, join, or count the names separately. The fix is to put each name on its own row. Later normal forms go further, moving facts that depend on part of a key, or on another non-key column, into their own tables. Normalization is not in the SQL course yet, and it is the natural next topic after keys and constraints.

47. What is a transaction, and what does ACID mean?

A transaction groups several changes so they all happen or none do. Either the whole group lands, or the database rolls back to how it was before the group started. Half-finished work is never left behind.

ACID names the four promises. Atomicity means all or nothing. Consistency means the rules hold after the transaction, such as keys still matching. Isolation means concurrent transactions do not see each other's half-finished work. Durability means committed work survives a crash. The demo below raises one salary inside a transaction on a copy table and commits it. Transactions are not in the SQL course yet, so this sheet covers them here.

CREATE TABLE tmp_pay AS SELECT id, salary FROM employees;

BEGIN;

UPDATE tmp_pay SET salary = salary + 5000 WHERE id = 1;

SELECT salary FROM tmp_pay WHERE id = 1;

Output:
salary
77000

COMMIT;

48. What are the transaction isolation levels?

Isolation levels trade safety against speed. Read uncommitted lets a transaction see uncommitted changes from others, which risks dirty reads of work that may be rolled back. Read committed hides uncommitted work, but a row read twice can change between reads. Repeatable read holds the rows steady for the transaction, but new rows can still appear. Serializable behaves as if transactions ran one at a time, and it is the strictest and slowest.

Most interviews only want the four names in order and one problem each level allows. The level is a setting, not a query, and the right choice depends on whether the workload can tolerate a dirty read or a phantom row. Start with the default of your database and change it only for a measured reason.

49. What is the difference between a view and a table?

A table stores rows. A view stores a query. Reading a view runs its saved query against the live tables, so the view always shows current data, and changing the table changes what the view returns.

The demo below saves the Engineering staff as a view, then reads it. Ana, Ben, and Eli come back. If Eli's salary changes tomorrow, the view shows the new figure without any update to the view itself. A view cannot be indexed or written to like a table, and it is no substitute for one when the data must be stored rather than derived. The Views lesson in the SQL course saves a query the same way.

CREATE VIEW eng_staff AS SELECT name, salary FROM employees WHERE dept_id = 1;

SELECT name, salary FROM eng_staff ORDER BY name;

Output:
name | salary
Ana | 72000
Ben | 95000
Eli | 61000

50. How would you design tables for a small shop?

Start from the things, not the reports. A shop has customers, products, orders, and order lines. Customers hold one row per person, with a primary key. Products hold one row per product. Orders hold one row per order, with a foreign key to the customer who placed it. Order lines hold one row per product on an order, with foreign keys to the order and to the product, plus a quantity.

That shape answers the usual questions without repeating facts. A customer's name lives in one place, so it cannot disagree with itself. An order total comes from joining order lines to products and summing price times quantity, which is the same grouping pattern as question 18. The SQL course builds a real report from shop tables in its Shop Report project, and it is the closest thing on the site to this design question.

Outside my window, a magpie has spent the morning carrying twigs to the same branch and dropping half of them on the lawn. It has not finished the nest. It does not seem bothered, and it will be back tomorrow with more twigs.

Questions readers ask

How should I prepare for a SQL interview in one week?

Work through this sheet on the two tables above, writing each query by hand before reading the answer, and redo the ones you missed the next day. Start with joins and grouping, then window functions, then the design questions. One week of daily practice on small tables beats one long night of reading definitions.

Do I need to memorise all 50 answers?

No. Memorise the patterns: joins, grouping, ranking, and the NULL rules. Most questions here are one pattern with different columns. If you can write a join, a group with HAVING, and a rank with DENSE_RANK from memory, you can rebuild the rest in the interview.

Which SQL dialect should I practise in?

The queries here run on SQLite. The ideas carry across dialects, but check the details: FULL JOIN, window functions, and NULL ordering differ between databases, and a query that is correct in one can fail or behave differently in another.

What should I learn after this sheet?

The gaps this sheet names: window functions in depth, CTEs, transactions, and normalization. The SQL course covers the foundations, and the answers above say plainly where the course stops and this sheet takes over.