N sql cheat sheet: the 5 things interview questions are built from, with a query for each - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/sql-cheat-sheet/
☷ sql cheat sheet: the 5 things interview questions are built from, with a query for each - nicnonac guides _□×

← back to guides

sql cheat sheet: the 5 things interview questions are built from, with a query for each

Stacks · 10 min read · posted Nov 30, 2026, 2:30 am

Most SQL interview questions are built from the same five things. Once you can tell which one a question is asking for, the query gets a lot easier to write.

This is the cheat sheet from the reel. It covers the five things in it. For each one you get the words that give it away in a question, a query on a tiny table with its result, the mistake that usually breaks it, and problems to practise on, easiest first.

Every query here was run in SQLite on the rows shown, and the results are what came back. They only use standard SQL, so Postgres and MySQL 8 take them as written. Each section has its own small table, even where a table name repeats. The practice problems are all public on LeetCode.

the quick lookup

Read the question and look for these words before you write anything.

the question says reach for
data from two tables, "with their", "who has no" join
"per", "for each", "how many", total, average group by
rank, "top n in each group", running total, "compared with the previous row" window function
"why is this query slow", "how would you speed it up" index
two steps, where the first result feeds the second cte

what each one does to your rows

tool rows in, rows out
join pairs up rows from two tables. the result can have more or fewer rows than either
group by many rows in, one row out per group
window function the same rows out, each with a new column worked out across its group
index changes no rows. it changes how many the database has to read
cte names a result so the next query can read it like a table

1. joins

Spot it. The answer needs columns from two tables. "Each order with its customer's name", "employees and their manager", "customers who never ordered".

The idea. A join puts rows from two tables side by side wherever a condition holds, almost always "this id equals that id". An inner join keeps only the pairs that match. A left join keeps every row of the left table and fills in NULL where nothing matched.

The query.

orders:

user_id item
1 book
4 cap
1 mug
3 pen

users:

id name
1 Ana
2 Ben
3 Cy
SELECT u.name, o.item
FROM orders AS o
INNER JOIN users AS u
  ON u.id = o.user_id
ORDER BY o.item;
name item
Ana book
Ana mug
Cy pen

This is the one in the reel. The cap belongs to user 4, who isn't in users, so that row is dropped. Ben has no orders, so he's dropped too. An inner join only keeps rows that match on both sides.

Second shape: who has nothing. Start from the table you want to keep all of, left join the other one, and keep the rows where the join found nothing.

SELECT u.name
FROM users AS u
LEFT JOIN orders AS o
  ON o.user_id = u.id
WHERE o.user_id IS NULL;
name
Ben

What breaks it. A missing or wrong join condition. With no condition every row pairs with every row, so these 4 orders and 3 users come back as 12 rows. If a result has far more rows than you expected, check the ON first. The other one is filtering a left join in the WHERE. Adding WHERE o.item = 'mug' to a left join throws away the NULL rows and you're back to an inner join with one row. Put that condition in the ON and all three users stay.

Practise.

2. group by

Spot it. "Per", "for each", "how many", "total", "average". The answer has one row per category.

The idea. GROUP BY sorts the rows into piles that share a value, then squashes each pile into one row. Everything in the SELECT has to be either the column you grouped by or an aggregate over the pile: COUNT, SUM, AVG, MIN or MAX.

The query.

orders:

city qty
Rome 3
Oslo 1
Rome 2
Paris 4
Oslo 2
Rome 1
SELECT city, SUM(qty) AS total
FROM orders
GROUP BY city
ORDER BY city;
city total
Oslo 3
Paris 4
Rome 6

Six rows in, three rows out, one per city.

Second shape: filter the groups. HAVING is WHERE for groups.

SELECT city, SUM(qty) AS total
FROM orders
GROUP BY city
HAVING SUM(qty) > 3
ORDER BY city;
city total
Paris 4
Rome 6

What breaks it. Putting a total in the WHERE. WHERE runs before the grouping and looks at single rows, so WHERE SUM(qty) > 3 is an error. HAVING runs after the grouping and looks at groups. The other one is selecting a column that is neither grouped nor aggregated. Postgres refuses it. SQLite and some MySQL setups run it and hand you the value from one arbitrary row of the pile, which is worse.

Practise.

3. window functions

Spot it. "Rank", "top n in each group", "running total", "compared with the previous row". You want a number worked out across a group, and you still want every row.

The idea. A window function looks across a set of rows, like GROUP BY does, but it doesn't squash them. Every row stays and gets a new column. PARTITION BY says which rows count as one group. The ORDER BY inside the OVER says what order to number them in.

The query.

staff:

name dept pay
Ana eng 120
Ben ops 90
Cy eng 150
Di ops 70
Eve eng 100
SELECT name, dept, pay,
  RANK() OVER (
    PARTITION BY dept
    ORDER BY pay DESC
  ) AS rnk
FROM staff
ORDER BY dept, rnk;
name dept pay rnk
Cy eng 150 1
Ana eng 120 2
Eve eng 100 3
Ben ops 90 1
Di ops 70 2

Five rows in, five rows out, and the rank starts again at 1 for ops. That's the difference from GROUP BY, which would have given you two rows.

Second shape: top n in each group. Rank inside a CTE (section 5), then filter on the rank outside it.

WITH ranked AS (
  SELECT name, dept, pay,
    RANK() OVER (
      PARTITION BY dept
      ORDER BY pay DESC
    ) AS rnk
  FROM staff
)
SELECT name, dept, pay
FROM ranked
WHERE rnk = 1
ORDER BY dept;
name dept pay
Cy eng 150
Ben ops 90

The three numbering functions. They only differ when there's a tie. For pay of 150, 150 and 100:

function gives
ROW_NUMBER() 1, 2, 3
RANK() 1, 1, 3
DENSE_RANK() 1, 1, 2

Two more worth knowing: LAG(pay) OVER (ORDER BY pay) reads the previous row's value, and SUM(pay) OVER (ORDER BY pay) is a running total.

What breaks it. Filtering on the rank in the same SELECT. WHERE rnk = 1 fails there, because WHERE runs before the window is worked out. Wrap it, as above. The other one is picking the wrong numbering function when there can be ties. "The second highest salary" wants DENSE_RANK: with RANK, two people tied for first leave no rank 2 at all.

Practise.

4. indexes

Spot it. "This query is slow, why", "how would you speed this up", "what would you index". It's usually a conversation, not a query to write.

The idea. Without an index, finding one username means reading every row and checking it. An index is a separate sorted copy of one column, with a pointer from each value back to its row. Because it's sorted, the database can throw away half of what's left with each check, the way binary search does.

The query.

SELECT * FROM users
WHERE username = 'tia';

CREATE UNIQUE INDEX idx_user
  ON users (username);

SELECT * FROM users
WHERE username = 'tia';

In the reel the table has 10 users. The first SELECT reads all 10 rows. After the index, the same SELECT finds tia in 3 checks of the sorted usernames and follows the pointer to row 8.

On 10 rows nobody would notice. On 10 million rows the scan reads all 10 million, and a search of a sorted list needs about 24 checks. Real databases keep the index as a B-tree, a wide sorted tree, so it's even fewer reads from disk than that.

Ask the database what it's doing.

EXPLAIN QUERY PLAN
SELECT * FROM users
WHERE username = 'tia';

SQLite answers SCAN users before the index and SEARCH users USING INDEX idx_user (username=?) after it. Postgres and MySQL have their own EXPLAIN with the same two ideas under other names: a sequential or full scan, and an index scan.

What an index costs. Every insert, update and delete has to update the index too, and it takes disk space. So you index the columns you search, join and sort on, not every column.

What breaks it. Wrapping the column in a function. WHERE lower(username) = 'tia' goes back to a full scan, because the index is sorted by the raw value. A pattern that starts with a wildcard, LIKE '%ia', does the same: sorted order is no help when you don't know the first letter. The other one is a two-column index used from the wrong end. An index on (last_name, first_name) is searched by last name, or by both. A search by first name alone can't use it.

Practise. These get asked out loud, so answer them out loud.

  • A query filters on WHERE email = ? and takes two seconds on a million rows. What do you check first? (The query plan. If it says scan, add an index on email.)
  • Why not put an index on every column? (Every write gets slower, and it costs space.)
  • You have an index on (last_name, first_name). Which searches can use it: last name only, first name only, both? (Last name only, and both.)
  • A column is indexed but the query still scans. Why might that be? (A function around the column, a leading wildcard, or the query wants most of the table anyway.)

5. ctes

Spot it. The answer takes two steps: work something out, then filter or join on it. "Customers who spent more than 100 in total", "departments whose average is above the company average".

The idea. WITH name AS (...) runs a query and gives the result a name. The query after it reads from that name like a table. It does the same job as a subquery, but it reads top to bottom, in the order you'd explain it. CTE stands for common table expression.

The query.

orders:

customer amount
Ana 40
Ben 120
Ana 90
Cy 30
Ben 15
Cy 20
WITH totals AS (
  SELECT customer,
         SUM(amount) AS spent
  FROM orders
  GROUP BY customer
)
SELECT customer, spent
FROM totals
WHERE spent > 100
ORDER BY customer;
customer spent
Ana 130
Ben 135

Step one builds totals: Ana 130, Ben 135, Cy 50. Step two reads it and keeps the two over 100.

You could write this one with HAVING too. The CTE earns its place when the second step needs more than a filter.

Second shape: join back to the step. Orders that are more than half of what that customer spent in total.

WITH totals AS (
  SELECT customer,
         SUM(amount) AS spent
  FROM orders
  GROUP BY customer
)
SELECT o.customer, o.amount, t.spent
FROM orders AS o
JOIN totals AS t
  ON t.customer = o.customer
WHERE o.amount * 2 > t.spent
ORDER BY o.customer;
customer amount spent
Ana 90 130
Ben 120 135
Cy 30 50

What breaks it. Treating a CTE like a saved table. It only lives for the one statement it's attached to, and the next query can't see it. The other one is the comma. Several CTEs share a single WITH and are separated by commas: WITH a AS (...), b AS (...) SELECT .... Writing WITH twice is a syntax error.

Practise.

the order sql runs in

You write a query starting with SELECT, but the database works through it in this order:

  1. FROM and JOIN
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. window functions, then the rest of the SELECT
  6. ORDER BY
  7. LIMIT

Most "why doesn't this work" moments come from that order. WHERE can't see a total, because the grouping hasn't happened yet. WHERE can't see a rank, because windows come later still.

how to practise with this

One section at a time. Do the easy problem with the query open, then the mediums with it closed.

Before you write anything, say what one row of the answer is: one per customer, one per order, one per department. That sentence usually tells you whether you need a join, a group or a window. Say it out loud in the interview too, before you start typing.

honest limitations

Five things isn't all of SQL. Subqueries, UNION, CASE, NULL handling and date functions all turn up, and self joins are a favourite. These five are what the harder questions get built from.

Everything here was run in SQLite. The queries are standard SQL, but each database has its own details. Date functions differ the most, and MySQL only got window functions and CTEs in version 8.

The index section is the short version. Real query planners look at statistics about the table, and sometimes a full scan is the right call, for example when the query wants most of the rows anyway.

If you're preparing for the coding rounds too, the coding interview cheat sheet and the data structures cheat sheet cover those, and the system design cheat sheet covers where the database sits in a bigger system.

← all guides

Done nicnonac.com 56.6k