Lesson 27 of 29Beyond relational, and interviews
SQL Interview Questions
The SQL questions screens actually ask, solved and run on the course data: second-highest salary, top N per group, duplicates, hierarchies, streaks, retention and more.
SQL screens are short and unforgiving. You get 30 to 45 minutes in CoderPad, HackerRank or a shared doc, a schema you have never seen, and two or three questions that look easy until you think about ties, NULLs and duplicates. Interviewers are not checking whether you remember syntax. They are checking whether you ask the right questions first, pick a pattern that fits, and test it against the edge cases that break naive answers. This lesson runs the classic questions on the course data, explains the traps each one hides, and ends with the concept questions and model answers that come up in backend rounds.
How a SQL round runs
Most rounds follow the same rhythm, and a calm routine is worth more than memorised tricks.
Ask before you type. 'If two people tie for second, do both count?' 'Does a cancelled order count as ordering?' 'Postgres or MySQL?' Each answer changes the query.
If the platform lets you run code, run small pieces as you go. If it does not, say what you expect each CTE to return. Silence is the thing that hurts most.
Second-highest salary
The most asked SQL question of all. The trap is not the second-highest value; it is what happens with ties and when there is no second value.
Press Run (⌘ Enter) to see what happens.DISTINCT handles ties: if two people earn the top salary, the second-highest is still the next distinct value. Wrapping the query in an outer SELECT (...) turns "no rows" into a NULL, which is what most questions ask for ("return null if there is none"). The MAX(...) WHERE salary < MAX version is the one to reach for in an engine without LIMIT, and it returns NULL naturally. For "the Nth highest" in general, DENSE_RANK() ... = N is the window version.
What does this print?
-- Sales has two people: 190000 and 95000 SELECT DISTINCT salary FROM employees WHERE department = 'Sales' ORDER BY salary DESC LIMIT 1 OFFSET 2; -- How many rows does this return?
Top N per group
"Top two earners per department" is the same pattern as the top-N section of Window Functions: rank inside a CTE, filter outside, because WHERE runs before windows exist. The interview twist is the tie.
Press Run (⌘ Enter) to see what happens.What does this print?
-- After the UPDATE, Engineering salaries are -- 310000, 210000, 210000, 180000, 175000, 135000, 130000 -- How many Engineering rows have rn <= 2? -- And how many have dr <= 2?
Earning more than their manager
A self join: the same table plays employee and manager.
Press Run (⌘ Enter) to see what happens.The first run returns nothing, and that is a lesson in itself: an empty result does not prove a query is right. Change the data so a row should match and run it again. In an interview, you can do this out loud: "if Ana earned 215k she should appear, and she does because her manager is Sofia at 205k." Note the inner join drops people with no manager (Priya, Noah), which is correct here. If the question were "employees with no manager", you would use WHERE manager_id IS NULL.
Walking the management chain
"List everyone in Priya's organisation with their depth" needs a recursive CTE, which Recursive CTEs and hierarchies covers in full. The interview version is short: an anchor row, a recursive step that joins children to the rows found so far, and a column that tracks depth or path.
The anchor selects the starting row: WHERE id = 1. Depth 0.
Press Run (⌘ Enter) to see what happens.The second query walks up instead of down by flipping the join. Mention cycle protection if you have time: a bad row where someone manages their own manager loops forever, so cap the depth (WHERE o.depth < 20) or, in Postgres 14+, use the CYCLE clause.
Customers who never ordered
Press Run (⌘ Enter) to see what happens.NOT EXISTS is the safe default. The LEFT JOIN ... WHERE o.id IS NULL anti-join is equivalent, and it shows a clarifying question at work: Alan's only order was cancelled, so whether he "never ordered" depends on the business. Putting the status condition in the ON clause, not in WHERE, is what keeps the anti-join correct. Avoid NOT IN (SELECT customer_id ...): if that column can ever be NULL, it returns no rows at all, as NULL and three-valued logic showed.
Finding and deleting duplicates
A staging table of newsletter signups has repeated emails, some with different case and stray spaces. Find them, delete all but the earliest, and stop it happening again.
Press Run (⌘ Enter) to see what happens.The details interviewers look for: define what "duplicate" means (here, case and whitespace do not count), keep a deterministic survivor (lowest id), and fix the cause with a unique constraint, not a nightly cleanup job. NOT IN is safe here because MIN(id) is never NULL. In Postgres you would usually write the delete with ROW_NUMBER() OVER (PARTITION BY lower(trim(email)) ORDER BY id) and delete where it is above 1, which also lets you keep "the newest" or "the most complete" row instead. On a big table, run it in batches inside a transaction you can check before committing.
Running totals and month-over-month growth
Press Run (⌘ Enter) to see what happens.Three things earn credit. 100.0 avoids integer division. NULLIF(prev, 0) turns a zero month into NULL instead of a division error. And the explicit ROWS frame avoids the default-frame trap from Window Functions. Also say what the query misses: a month with no orders would not appear at all, and LAG would silently compare the next month with the one before the gap. A real report left-joins to a calendar of months first.
Gaps and islands: login streaks
"Longest run of consecutive login days per user" is gaps and islands. Subtract a per-user row number from each distinct day: consecutive days share the same result, so each group is one streak.
Press Run (⌘ Enter) to see what happens.User 2 now logs in on 1, 2, 3 and 4 June, a streak of 4. The DISTINCT matters: the two logins on 3 June would otherwise get two row numbers and split the streak. In Postgres, day - ROW_NUMBER() OVER (...)::int gives the anchor date directly.
Retention from the events table
"What share of users came back within 7 days of their first visit, by cohort?" Build it in three steps: each user's first day (the cohort), each user's active days, then count users with any activity in the window.
Press Run (⌘ Enter) to see what happens.Collapsing to one row per user before counting (the MAX(...) in cohorts) is the key move. Counting raw events instead would let a user with ten return visits count ten times. Clarify the definition before writing anything: "returned" on day 7 exactly, or any time in days 1 to 7? Does any event count, or only logins? Is the window in the user's time zone?
What does this print?
-- Using the result above, across ALL cohorts: -- what percentage of users returned within 7 days? -- (round to one decimal place)
Median and pivots without special functions
SQLite has no median, and interviewers sometimes ban percentile_cont to see whether you can build it. Number the rows, count them, and average the middle one or two.
Press Run (⌘ Enter) to see what happens.With 10 products, integer division makes the two positions 5 and 6, so the median is the average of 4900 and 7900: 6400. With an odd count both positions are the same row. The pivot is conditional aggregation: one aggregate per output column, each counting only the rows that match.
Concept questions and short answers
Backend rounds mix queries with questions you answer in a sentence or two. These are the ones that come up most, with the lesson that covers each in depth.
- WHERE vs HAVING. WHERE filters rows before grouping; HAVING filters groups after. (Aggregation, GROUP BY and HAVING.)
- UNION vs UNION ALL. UNION removes duplicates, which costs a sort or hash; UNION ALL keeps everything and is faster. Use UNION ALL unless you need deduplication.
- DELETE vs TRUNCATE vs DROP. DELETE removes chosen rows, fires triggers and can be filtered. TRUNCATE empties the whole table fast without scanning it. DROP removes the table itself. In Postgres, TRUNCATE is transactional and can be rolled back; in MySQL it commits implicitly.
- Clustered vs non-clustered index. A clustered index stores the table rows in index order (InnoDB's primary key, SQL Server's clustered index). Postgres tables are heaps, and every index is secondary. (How indexes work.)
- What an index costs. Disk, memory, and slower writes, since every insert and update maintains each index. Unused indexes are pure cost.
- Isolation defaults. Postgres uses Read Committed, MySQL InnoDB uses Repeatable Read. (Isolation levels.)
- Optimistic vs pessimistic locking. Pessimistic takes a lock first (
SELECT ... FOR UPDATE); optimistic checks a version column at write time and retries on conflict. Optimistic wins when conflicts are rare. (Locking and deadlocks.) - OFFSET vs keyset pagination. OFFSET reads and throws away every skipped row, so page 1,000 is slow and rows shift as data changes. Keyset (
WHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT 20) uses an index and stays fast. (Query performance patterns.)
Match each interview question to the pattern that solves it.
Every question in this lesson used something from an earlier unit. The project next does the same with a feature you build yourself, product reviews, from the first table to a safe write.
- scalar subquery
- A subquery used as a single value. If it finds no row it yields NULL, which is how 'return null if none' questions are answered.
- self join
- Joining a table to itself under two aliases, such as employees as e and as m, to compare a row with a related row.
- anti-join
- Keeping rows that have no match in another table, written with NOT EXISTS or LEFT JOIN ... WHERE right.id IS NULL.
- conditional aggregation
- Using an aggregate with CASE or FILTER per output column, for example to pivot statuses into columns.
- cohort
- A group of users defined by when they first appeared, used to compare retention over time.
- keyset pagination
- Paging by remembering the last sort key seen and seeking past it with an index, instead of skipping rows with OFFSET.