PrepStack › Databases › SQL Queries

SQL Queries interview cheat sheet

Joins, grouping, subqueries, CTEs, window functions and the classic puzzles

SQL rounds test two things: do you understand how a query is evaluated (logical order, NULL logic, join semantics), and can you write the classic queries on a whiteboard (Nth highest salary, top-N per group, duplicates, gaps and islands). Every runnable snippet here uses SQLite and shows its real output; the text calls out where PostgreSQL and MySQL differ. Read the 15-minute revision first, then switch to Quiz mode and write each query by hand before checking.

15-minute revision

  1. Sublanguages: DDL (CREATE ALTER DROP TRUNCATE), DML (INSERT UPDATE DELETE MERGE, often SELECT too, or DQL), DCL (GRANT REVOKE), TCL (BEGIN COMMIT ROLLBACK SAVEPOINT).
  2. Logical order: FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. That is why a SELECT alias is not visible in WHERE but is visible in ORDER BY.
  3. WHERE filters rows before grouping and cannot use aggregates. HAVING filters groups after grouping and can.
  4. Any comparison with NULL is UNKNOWN, and WHERE keeps only TRUE rows. Use IS NULL, IS NOT NULL, COALESCE, IS DISTINCT FROM.
  5. COUNT(*) counts rows; COUNT(col) skips NULLs; COUNT(DISTINCT col) counts unique non-NULL values. SUM/AVG/MIN/MAX ignore NULLs.
  6. INNER JOIN keeps matches only; LEFT JOIN keeps every left row (NULLs when no match); FULL JOIN keeps both sides; CROSS JOIN is the Cartesian product.
  7. A condition on the right table in WHERE turns a LEFT JOIN into an inner join. Put it in the ON clause instead.
  8. Semi-join = EXISTS/IN; anti-join = NOT EXISTS or LEFT JOIN ... WHERE r.id IS NULL. NOT IN returns nothing if the subquery has a NULL.
  9. UNION removes duplicates (sort/hash cost); UNION ALL keeps them and is faster. INTERSECT = in both; EXCEPT (MINUS in Oracle) = in first, not in second.
  10. A correlated subquery references the outer row and logically runs per row; a non-correlated one runs once.
  11. A CTE (WITH) names a subquery for readability; WITH RECURSIVE = anchor UNION ALL recursive part, used for trees and series.
  12. Window functions compute over related rows without collapsing them: fn() OVER (PARTITION BY ... ORDER BY ... frame). They run after HAVING, so filter them in an outer query.
  13. ROW_NUMBER 1,2,3,4 · RANK 1,2,2,4 · DENSE_RANK 1,2,2,3. Use DENSE_RANK for 'Nth highest distinct salary'.
  14. With ORDER BY and no frame, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so ties share a running total. Use ROWS for a strict row-by-row sum.
  15. DELETE removes chosen rows (logged, fires triggers); TRUNCATE empties the table fast (DDL, resets identity); DROP removes the table itself.
  16. A view is a stored query (no data). A materialized view stores the result and must be refreshed (REFRESH MATERIALIZED VIEW in PostgreSQL; MySQL and SQLite have none).

Query foundations

SQL sublanguages: DDL, DML, DCL, TCL

SQL commands fall into families: define structure, change data, control access and control transactions.

  • DDL (Data Definition) changes the schema: CREATE, ALTER, DROP, TRUNCATE, RENAME, COMMENT.
  • DML (Data Manipulation) changes rows: INSERT, UPDATE, DELETE, MERGE/upsert. Many books put SELECT here; others call it DQL (Data Query).
  • DCL (Data Control) handles permissions: GRANT and REVOKE.
  • TCL (Transaction Control) groups statements into atomic units: BEGIN/START TRANSACTION, COMMIT, ROLLBACK, SAVEPOINT, ROLLBACK TO.
  • In PostgreSQL and SQLite, DDL is transactional (you can roll back a CREATE TABLE). In MySQL/Oracle, most DDL causes an implicit commit.

Interview questions

  • What are DDL, DML, DCL and TCL?
  • Can you roll back a DDL statement?
  • What is a savepoint?

SELECT logical execution order

SQL is written SELECT-first but evaluated FROM-first; this order explains most 'why can't I use that alias' errors.

  • Logical order: FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT (incl. window functions) → DISTINCT → ORDER BY → LIMIT/OFFSET.
  • Each step sees only what earlier steps produced. So WHERE cannot use a SELECT alias or an aggregate, but ORDER BY can use both.
  • Window functions are computed in the SELECT step, after HAVING. So you cannot filter on them in WHERE; wrap the query in a subquery or CTE.
  • This is a logical model. The optimizer may reorder physically (push filters down, use an index to avoid a sort) as long as the result is the same.
  • Dialect leniency: SQLite and MySQL accept a SELECT alias in HAVING (and SQLite even in WHERE); PostgreSQL rejects both but allows aliases in GROUP BY and ORDER BY.

Interview questions

  • What is the logical order of execution of a SELECT?
  • Why can't I use a column alias in WHERE?
  • How do you filter on a window function result?

WHERE vs HAVING

WHERE filters individual rows before grouping; HAVING filters whole groups after aggregation.

  • WHERE runs before GROUP BY, so it cannot reference aggregates like SUM(x).
  • HAVING runs after GROUP BY, so it filters on aggregates: HAVING COUNT(*) > 1.
  • Put non-aggregate conditions in WHERE: fewer rows reach the grouping step, which is cheaper.
  • HAVING without GROUP BY treats the whole table as one group (returns one row or zero rows).
  • A row filter in HAVING (e.g. HAVING dept = 'IT') works only if the column is grouped, and it is slower than WHERE.

Interview questions

  • Difference between WHERE and HAVING?
  • Can you use HAVING without GROUP BY?
  • Which is faster?

NULL semantics, COALESCE & three-valued logic

NULL means 'unknown'; comparisons with it yield UNKNOWN, and WHERE keeps only TRUE rows.

  • SQL uses three-valued logic: TRUE, FALSE, UNKNOWN. NULL = NULL is UNKNOWN, not TRUE.
  • WHERE and ON keep only TRUE rows; CHECK constraints reject only FALSE (UNKNOWN passes).
  • Test with IS NULL / IS NOT NULL. Null-safe equality: IS NOT DISTINCT FROM (PostgreSQL, SQLite 3.39+), <=> (MySQL), IS (SQLite).
  • COALESCE(a, b, c) returns the first non-NULL argument (standard). IFNULL/ISNULL/NVL are 2-argument dialect versions. NULLIF(a, b) returns NULL when a = b, handy to avoid division by zero.
  • Arithmetic and string concatenation with NULL give NULL: 1 + NULL, 'a' || NULL. (MySQL CONCAT also gives NULL; CONCAT_WS skips NULLs.)
  • Aggregates ignore NULLs, except COUNT(*). GROUP BY, DISTINCT and set operators treat all NULLs as one group.
  • Sort position differs: PostgreSQL puts NULLs last in ascending order; MySQL and SQLite put them first. Use NULLS FIRST/LAST (PostgreSQL, SQLite 3.30+) or ORDER BY col IS NULL, col in MySQL.

Interview questions

  • Why does WHERE col = NULL return no rows?
  • Difference between COALESCE and ISNULL/IFNULL/NVL?
  • COUNT(*) vs COUNT(col) vs COUNT(1)?
  • How do NULLs behave in GROUP BY and DISTINCT?

DISTINCT, ORDER BY, LIMIT/OFFSET & pagination

DISTINCT removes duplicate result rows, ORDER BY is the only guarantee of order, LIMIT/OFFSET slices the result.

  • DISTINCT applies to the whole selected row, not one column. SELECT DISTINCT a, b dedupes on the pair.
  • Without ORDER BY the row order is undefined, even if it looks stable today.
  • ORDER BY sorts by several keys, each with ASC/DESC; it can use aliases and expressions.
  • Row limiting differs by dialect: LIMIT n OFFSET m (PostgreSQL, MySQL, SQLite), FETCH FIRST n ROWS ONLY (standard, PostgreSQL, Oracle 12c+), TOP n (SQL Server).
  • OFFSET pagination gets slower for deep pages (the engine still reads and throws away the skipped rows) and can skip/duplicate rows when data changes.
  • Keyset (seek) pagination: remember the last key and ask for WHERE id > :last ORDER BY id LIMIT n. It uses the index and stays fast.

Interview questions

  • Does DISTINCT apply to one column or all?
  • Is the order of rows guaranteed without ORDER BY?
  • Why is OFFSET pagination slow and what's the alternative?

Joins & set operations

JOIN types: inner, outer, self, cross

A join pairs rows from two tables by a condition; the type decides what happens to rows without a match.

  • INNER JOIN: only rows that match on both sides.
  • LEFT (OUTER) JOIN: every left row; right columns are NULL when there is no match. RIGHT JOIN is the mirror image.
  • FULL (OUTER) JOIN: every row from both sides. MySQL has no FULL JOIN; emulate with LEFT JOIN ... UNION ... RIGHT JOIN. SQLite supports RIGHT/FULL since 3.39.
  • CROSS JOIN: Cartesian product, m × n rows. Useful to build combinations (sizes × colours, users × dates).
  • SELF JOIN: a table joined to itself with two aliases, e.g. employee ↔ manager in one table.
  • If the join key is not unique on one side, rows multiply (fan-out). Summing after such a join double-counts.
  • NATURAL JOIN and USING (col) join on same-named columns. NATURAL is risky because adding a column can change the join.

Interview questions

  • Difference between INNER JOIN and LEFT JOIN?
  • What happens if you put a condition on the right table in WHERE after a LEFT JOIN?
  • How do you do a FULL OUTER JOIN in MySQL?
  • What is a self join? Give a use case.

Semi-joins, anti-joins & the NOT IN NULL trap

EXISTS/IN keep rows that have a match; NOT EXISTS keeps rows that don't, and NOT IN breaks when NULLs appear.

  • A semi-join returns left rows that have at least one match, without duplicating them. Write it with EXISTS or IN.
  • An anti-join returns left rows with no match. Write it with NOT EXISTS or LEFT JOIN ... WHERE right.key IS NULL.
  • x NOT IN (subquery) is x <> v1 AND x <> v2 AND .... If any v is NULL, every comparison chain becomes UNKNOWN, so no rows come back.
  • NOT EXISTS only asks 'is there a row?' so NULLs do not affect it. It is the safe default for anti-joins.
  • EXISTS can stop at the first match. Modern planners (PostgreSQL, MySQL 8) turn both IN and EXISTS into the same semi-join plan, so pick for clarity, not speed.
  • A plain INNER JOIN used as a filter duplicates left rows when the right side has many matches; EXISTS does not.

Interview questions

  • Why can NOT IN return zero rows?
  • EXISTS vs IN: which is faster?
  • What is a semi-join and an anti-join?

UNION, UNION ALL, INTERSECT, EXCEPT

Set operators stack query results vertically; joins combine them horizontally.

  • Both queries need the same number of columns with compatible types. Column names come from the first query.
  • UNION removes duplicates (needs a sort or hash). UNION ALL keeps everything and is cheaper. Default to UNION ALL when duplicates are impossible or wanted.
  • INTERSECT returns rows in both results; EXCEPT returns rows in the first but not the second (MINUS in Oracle). MySQL added both in 8.0.31.
  • Set operators compare rows with NULLs treated as equal (unlike =), so they are null-safe for 'what changed between two tables'.
  • One ORDER BY/LIMIT at the end applies to the combined result. To sort or limit a part, wrap it in a subquery.
  • Precedence: INTERSECT binds tighter than UNION/EXCEPT in the SQL standard and PostgreSQL. SQLite evaluates them left to right, so use parentheses or subqueries for portable code.

Interview questions

  • Difference between UNION and UNION ALL?
  • Difference between a JOIN and a UNION?
  • How do you find rows that are in table A but not in table B?

Aggregation, subqueries & CTEs

GROUP BY, aggregates & CASE

GROUP BY collapses rows into one per key; CASE inside aggregates gives conditional counts and pivots.

  • Every selected column must be either in GROUP BY or inside an aggregate. PostgreSQL allows other columns of a table if you group by its primary key (functional dependency).
  • MySQL with ONLY_FULL_GROUP_BY (default since 5.7) enforces the rule. SQLite allows 'bare' columns and picks a value from some row in the group; with a lone MAX()/MIN() it takes the row holding the max/min.
  • Core aggregates: COUNT, SUM, AVG, MIN, MAX. String aggregation: STRING_AGG (PostgreSQL, SQL Server, SQLite 3.44+), GROUP_CONCAT (MySQL, SQLite).
  • CASE WHEN cond THEN x ... ELSE y END is the SQL if/else. Without ELSE, the result is NULL. It works in SELECT, WHERE, ORDER BY, GROUP BY and inside aggregates.
  • Conditional aggregation: SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END). PostgreSQL and SQLite also support COUNT(*) FILTER (WHERE status = 'paid').
  • ROLLUP, CUBE and GROUPING SETS produce subtotals (PostgreSQL, SQL Server; MySQL has WITH ROLLUP; SQLite has none).

Interview questions

  • Why do I get 'column must appear in the GROUP BY clause or be used in an aggregate'?
  • How do you count rows matching different conditions in one query?
  • How do you pivot rows to columns without a PIVOT keyword?

Subqueries: scalar, correlated, derived tables

A subquery is a query inside another; a correlated one depends on the current outer row.

  • Scalar subquery: returns one value, usable anywhere an expression is (SELECT, WHERE). Returns NULL if it finds no row; errors if it finds more than one (SQLite silently takes the first).
  • Table subquery / derived table: in FROM (...) AS t. Must have an alias in PostgreSQL (before 16) and MySQL.
  • Non-correlated: does not reference the outer query; logically evaluated once.
  • Correlated: references outer columns (WHERE e2.dept = e.dept), so logically it runs once per outer row. Optimizers often rewrite it into a join.
  • Comparison operators with sets: IN, EXISTS, = ANY, > ALL. > ALL (empty set) is TRUE (ANY/ALL are not supported in SQLite).
  • PostgreSQL and MySQL 8 support LATERAL (SQL Server: CROSS APPLY) for a derived table that can reference earlier FROM items, e.g. 'top 3 orders per customer'.

Interview questions

  • Difference between a correlated and a non-correlated subquery?
  • Subquery vs JOIN: which should you use?
  • What is a LATERAL join?

CTEs & recursive CTEs

WITH names a subquery for readability; WITH RECURSIVE repeatedly feeds its own output back to walk trees and build series.

  • A CTE (WITH name AS (...)) is a named, statement-scoped subquery. Later CTEs and the main query can reference it, even several times.
  • Benefits: readability, step-by-step logic, and reuse within one statement. It is not stored anywhere after the statement ends.
  • Materialization: PostgreSQL 12+ inlines a non-recursive CTE that is referenced once (so filters push in); force behaviour with AS MATERIALIZED / NOT MATERIALIZED. Before 12 every CTE was an optimization fence. SQLite also accepts these hints.
  • Recursive CTE = anchor member UNION ALL recursive member that references the CTE. It runs until the recursive part returns no rows.
  • Syntax: PostgreSQL and MySQL 8 need WITH RECURSIVE; SQL Server omits RECURSIVE; SQLite accepts both.
  • Always include a stop condition (WHERE depth < 10) or cycle protection; PostgreSQL 14+ also has a CYCLE clause. UNION (not ALL) in a recursive CTE drops repeated rows, which can stop simple cycles.

Interview questions

  • What is a CTE and why use it over a subquery?
  • How does a recursive CTE execute?
  • How do you find all subordinates of a manager, at any depth?
  • CTE vs temp table vs view?

Window functions

Window functions: ROW_NUMBER, RANK, DENSE_RANK, NTILE

A window function computes a value across related rows while keeping every row in the output.

  • Syntax: fn(...) OVER (PARTITION BY a ORDER BY b frame). PARTITION BY splits rows into groups; ORDER BY orders rows inside each group.
  • Unlike GROUP BY, rows are not collapsed: you get the detail row and the group value side by side.
  • ROW_NUMBER() gives unique 1,2,3… (ties broken arbitrarily). RANK() gives ties the same rank and leaves gaps (1,2,2,4). DENSE_RANK() gives ties the same rank without gaps (1,2,2,3).
  • NTILE(n) splits ordered rows into n nearly equal buckets (quartiles, deciles). PERCENT_RANK() and CUME_DIST() give relative positions.
  • Any aggregate can be a window: SUM(x) OVER (PARTITION BY dept) gives the department total on every row.
  • Support: PostgreSQL (since 8.4), MySQL 8.0+, SQLite 3.25+, SQL Server. MySQL 5.7 has none.
  • A named window avoids repetition: ... OVER w ... WINDOW w AS (PARTITION BY dept ORDER BY salary DESC).

Interview questions

  • Difference between ROW_NUMBER, RANK and DENSE_RANK?
  • Difference between GROUP BY and a window function?
  • Why can't I use ROW_NUMBER() in WHERE?

LAG/LEAD, running totals & window frames

Offset functions look at neighbouring rows; the frame clause decides which rows an aggregate window sees.

  • LAG(col, n, default) reads n rows back, LEAD reads n rows ahead within the partition. Use them for day-over-day change, previous status, session gaps.
  • FIRST_VALUE, LAST_VALUE, NTH_VALUE read a specific row of the frame.
  • Frame syntax: {ROWS | RANGE | GROUPS} BETWEEN start AND end, with bounds UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING, UNBOUNDED FOLLOWING.
  • ROWS counts physical rows. RANGE uses the ORDER BY value, so peer rows (ties) are included together. GROUPS counts peer groups (PostgreSQL 11+, SQLite).
  • Default frame with ORDER BY: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Without ORDER BY: the whole partition.
  • Because of that default, LAST_VALUE(x) OVER (ORDER BY y) returns the current row's value (end of frame = current row). Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
  • Moving average over the last 3 rows: AVG(x) OVER (ORDER BY d ROWS BETWEEN 2 PRECEDING AND CURRENT ROW). RANGE with an interval (RANGE BETWEEN INTERVAL '6 days' PRECEDING ...) works in PostgreSQL and MySQL.

Interview questions

  • How do you compute a running (cumulative) total?
  • Difference between ROWS and RANGE frames?
  • Why does LAST_VALUE return the current row's value?
  • How do you compare each row to the previous row?

Schema objects & data changes

DELETE vs TRUNCATE vs DROP

DELETE removes chosen rows, TRUNCATE empties a table quickly, DROP removes the table definition and data.

  • DELETE FROM t WHERE ... is DML: row by row, can filter, logs each row, fires row triggers, can be rolled back.
  • TRUNCATE TABLE t is DDL: deallocates data pages, no WHERE, minimal logging, much faster on big tables, resets identity/auto-increment in most engines, does not fire DELETE triggers.
  • DROP TABLE t removes data and structure: indexes, constraints, triggers and grants go too. Dependent views break or block the drop (CASCADE in PostgreSQL).
  • Rollback: PostgreSQL can roll back TRUNCATE and DROP inside a transaction. MySQL commits implicitly, so they cannot be undone.
  • TRUNCATE is blocked when other tables reference it by foreign key (PostgreSQL: unless CASCADE; MySQL InnoDB: always).
  • SQLite has no TRUNCATE: DELETE FROM t without WHERE uses a fast 'truncate optimization' internally.

Interview questions

  • Difference between DELETE, TRUNCATE and DROP?
  • Can TRUNCATE be rolled back?
  • Why is TRUNCATE faster than DELETE?

Constraints & keys

Constraints are rules the database enforces on every write, so bad data cannot get in no matter which app writes it.

  • NOT NULL: value required. DEFAULT: value when none is given.
  • PRIMARY KEY: unique + not null, one per table, identifies the row. Usually backed by a unique index (clustered in InnoDB and SQL Server by default).
  • UNIQUE: no duplicate values, but NULLs are allowed (usually many). A table can have many unique constraints; they are candidate keys.
  • FOREIGN KEY ... REFERENCES parent(id): value must exist in the parent. Actions ON DELETE/UPDATE CASCADE | SET NULL | SET DEFAULT | RESTRICT | NO ACTION.
  • CHECK (expr): row must not make the expression FALSE (UNKNOWN passes). MySQL enforces CHECK only from 8.0.16; older versions parsed and ignored it.
  • SQLite enforces foreign keys only after PRAGMA foreign_keys = ON (per connection).
  • Keys vocabulary: super key (any unique column set), candidate key (minimal super key), primary key (chosen candidate), alternate key (other candidates), composite key (several columns), surrogate vs natural key.

Interview questions

  • Difference between PRIMARY KEY and UNIQUE?
  • What do ON DELETE CASCADE and SET NULL do?
  • Candidate key vs primary key vs super key?
  • Surrogate key vs natural key?

Views & materialized views

A view is a saved query re-run on each read; a materialized view stores the result and must be refreshed.

  • A view (CREATE VIEW v AS SELECT ...) stores only the query. Reading it runs the query, so data is always current. The planner merges it into the outer query.
  • Uses: hide join complexity, expose a stable interface over changing tables, and security (grant access to the view, not the base table; e.g. hide salary columns).
  • Simple views (one table, no aggregates/DISTINCT/GROUP BY) are updatable in PostgreSQL and MySQL. WITH CHECK OPTION blocks writes that would vanish from the view. SQLite views are read-only unless you add INSTEAD OF triggers.
  • A materialized view stores the result rows physically and can have its own indexes. Reads are fast, but data is stale until refreshed.
  • PostgreSQL: CREATE MATERIALIZED VIEW mv AS ... and REFRESH MATERIALIZED VIEW [CONCURRENTLY] mv. CONCURRENTLY keeps the view readable during refresh but needs a unique index on it.
  • Oracle supports fast incremental refresh with materialized view logs; SQL Server has indexed views (kept in sync automatically). MySQL and SQLite have no materialized views: use a summary table refreshed by a job or triggers.

Interview questions

  • Difference between a view and a materialized view?
  • Can you insert into a view?
  • How do you refresh a materialized view without blocking readers?

Stored procedures, functions & triggers

Procedures and functions put logic inside the database; triggers run it automatically on data changes.

  • A stored procedure is a named program stored in the database, called with CALL proc(...) (EXEC in SQL Server). It can run many statements and, in PostgreSQL 11+, COMMIT/ROLLBACK inside.
  • A function returns a value (or a table) and is usable inside a SELECT. In PostgreSQL, functions cannot control transactions; that is the main reason procedures were added.
  • A trigger fires BEFORE, AFTER or INSTEAD OF an INSERT/UPDATE/DELETE, per row or per statement. Uses: audit logs, derived columns, enforcing complex rules.
  • In triggers, NEW is the incoming row and OLD is the previous row (SQL Server uses inserted/deleted tables).
  • Pros: fewer round trips, logic close to data, one place for rules. Cons: harder to version, test and debug; vendor lock-in; hidden side effects (triggers).
  • SQLite has triggers but no stored procedures; MySQL and PostgreSQL have both.

Interview questions

  • Difference between a stored procedure and a function?
  • What is a trigger and when would you use one?
  • Should business logic live in stored procedures?

Classic interview queries

Nth highest salary, department max & duplicates

The most asked SQL puzzles: rank with DENSE_RANK, find the max per group, and find or delete duplicate rows.

  • Nth highest (distinct): DENSE_RANK() OVER (ORDER BY salary DESC) = N. Portable alternative: SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET N-1.
  • Wrap in a scalar subquery to return NULL when there is no Nth salary (the LeetCode requirement).
  • Without window/LIMIT: correlated count, 'salary where exactly N-1 distinct salaries are higher'.
  • Second highest classic: SELECT MAX(salary) FROM emp WHERE salary < (SELECT MAX(salary) FROM emp).
  • Max per department with names: join the table to (dept, MAX(salary)) or use RANK() OVER (PARTITION BY dept ORDER BY salary DESC) = 1 (keeps ties).
  • Find duplicates: GROUP BY the duplicate columns HAVING COUNT(*) > 1. Delete duplicates: keep MIN(id) per group, or delete where ROW_NUMBER() > 1.

Interview questions

  • Write a query for the Nth highest salary.
  • Find the employee(s) with the highest salary in each department.
  • How do you find duplicate records?
  • How do you delete duplicates but keep one?

Top-N per group, employee vs manager, cumulative sums

Rank inside partitions for top-N, self-join for manager comparisons, and window SUM for running totals.

  • Top-N per group: ROW_NUMBER() (exactly N) or DENSE_RANK() (N distinct values, ties included) partitioned by the group, filtered in an outer query.
  • Without windows: correlated count, 'fewer than N rows in my group are bigger than me' ((SELECT COUNT(DISTINCT x) ... WHERE x > me) < N). PostgreSQL alternative: LATERAL (... ORDER BY ... LIMIT N).
  • Employees earning more than their manager: self join emp e JOIN emp m ON e.manager_id = m.id WHERE e.salary > m.salary.
  • Cumulative sum: SUM(x) OVER (PARTITION BY ... ORDER BY ... ROWS UNBOUNDED PRECEDING). Old style: self join on b.date <= a.date and GROUP BY, which is O(n²).
  • Percent of total: x * 100.0 / SUM(x) OVER (). Year-over-year: LAG(x) OVER (ORDER BY year).

Interview questions

  • How do you get the top 3 earners in each department?
  • Find employees who earn more than their managers.
  • Top-N per group: what if the table is huge?

Consecutive days: gaps and islands

Subtract a row number from a sequence; rows in the same unbroken run get the same constant, which becomes the group key.

  • Islands = runs of consecutive values (login streaks, consecutive seats, uninterrupted uptime). Gaps = the missing ranges between them.
  • Trick: for consecutive dates, date - ROW_NUMBER() days is constant within a run and changes after a break. Group by that constant.
  • Then MIN(day), MAX(day) and COUNT(*) per group give each streak's start, end and length.
  • Deduplicate first (SELECT DISTINCT user, day) or a double login on the same day breaks the arithmetic (or use DENSE_RANK).
  • Gaps: LEAD(day) OVER (ORDER BY day) and keep rows where the next value is more than one step away.
  • 'N consecutive' questions (LeetCode 180 'Consecutive Numbers', 601 'Human Traffic'): either islands with HAVING COUNT(*) >= N, or compare LAG/LEAD values.

Interview questions

  • How do you find users who logged in on 3 or more consecutive days?
  • Why does subtracting ROW_NUMBER from the date work?
  • How do you find missing numbers in a sequence?
  • Find numbers that appear at least 3 times consecutively.