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
- Sublanguages: DDL (
CREATE ALTER DROP TRUNCATE), DML (INSERT UPDATE DELETE MERGE, oftenSELECTtoo, or DQL), DCL (GRANT REVOKE), TCL (BEGIN COMMIT ROLLBACK SAVEPOINT). - Logical order:
FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. That is why aSELECTalias is not visible inWHEREbut is visible inORDER BY. WHEREfilters rows before grouping and cannot use aggregates.HAVINGfilters groups after grouping and can.- Any comparison with
NULLis UNKNOWN, andWHEREkeeps only TRUE rows. UseIS NULL,IS NOT NULL,COALESCE,IS DISTINCT FROM. COUNT(*)counts rows;COUNT(col)skips NULLs;COUNT(DISTINCT col)counts unique non-NULL values.SUM/AVG/MIN/MAXignore NULLs.INNER JOINkeeps matches only;LEFT JOINkeeps every left row (NULLs when no match);FULL JOINkeeps both sides;CROSS JOINis the Cartesian product.- A condition on the right table in
WHEREturns aLEFT JOINinto an inner join. Put it in theONclause instead. - Semi-join =
EXISTS/IN; anti-join =NOT EXISTSorLEFT JOIN ... WHERE r.id IS NULL.NOT INreturns nothing if the subquery has a NULL. UNIONremoves duplicates (sort/hash cost);UNION ALLkeeps them and is faster.INTERSECT= in both;EXCEPT(MINUSin Oracle) = in first, not in second.- A correlated subquery references the outer row and logically runs per row; a non-correlated one runs once.
- A CTE (
WITH) names a subquery for readability;WITH RECURSIVE= anchorUNION ALLrecursive part, used for trees and series. - Window functions compute over related rows without collapsing them:
fn() OVER (PARTITION BY ... ORDER BY ... frame). They run afterHAVING, so filter them in an outer query. ROW_NUMBER1,2,3,4 ·RANK1,2,2,4 ·DENSE_RANK1,2,2,3. UseDENSE_RANKfor 'Nth highest distinct salary'.- With
ORDER BYand no frame, the default frame isRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so ties share a running total. UseROWSfor a strict row-by-row sum. DELETEremoves chosen rows (logged, fires triggers);TRUNCATEempties the table fast (DDL, resets identity);DROPremoves the table itself.- A view is a stored query (no data). A materialized view stores the result and must be refreshed (
REFRESH MATERIALIZED VIEWin 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 putSELECThere; others call it DQL (Data Query). - DCL (Data Control) handles permissions:
GRANTandREVOKE. - 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
WHEREcannot use aSELECTalias or an aggregate, butORDER BYcan use both. - Window functions are computed in the
SELECTstep, afterHAVING. So you cannot filter on them inWHERE; 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
SELECTalias inHAVING(and SQLite even inWHERE); PostgreSQL rejects both but allows aliases inGROUP BYandORDER 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.
WHEREruns beforeGROUP BY, so it cannot reference aggregates likeSUM(x).HAVINGruns afterGROUP BY, so it filters on aggregates:HAVING COUNT(*) > 1.- Put non-aggregate conditions in
WHERE: fewer rows reach the grouping step, which is cheaper. HAVINGwithoutGROUP BYtreats 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 thanWHERE.
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 = NULLis UNKNOWN, not TRUE. WHEREandONkeep only TRUE rows;CHECKconstraints 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/NVLare 2-argument dialect versions.NULLIF(a, b)returns NULL whena = b, handy to avoid division by zero.- Arithmetic and string concatenation with NULL give NULL:
1 + NULL,'a' || NULL. (MySQLCONCATalso gives NULL;CONCAT_WSskips NULLs.) - Aggregates ignore NULLs, except
COUNT(*).GROUP BY,DISTINCTand 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+) orORDER BY col IS NULL, colin MySQL.
Interview questions
- Why does
WHERE col = NULLreturn 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.
DISTINCTapplies to the whole selected row, not one column.SELECT DISTINCT a, bdedupes on the pair.- Without
ORDER BYthe row order is undefined, even if it looks stable today. ORDER BYsorts by several keys, each withASC/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). OFFSETpagination 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 withLEFT JOIN ... UNION ... RIGHT JOIN. SQLite supportsRIGHT/FULLsince 3.39. - CROSS JOIN: Cartesian product,
m × nrows. 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 JOINandUSING (col)join on same-named columns.NATURALis 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
EXISTSorIN. - An anti-join returns left rows with no match. Write it with
NOT EXISTSorLEFT JOIN ... WHERE right.key IS NULL. x NOT IN (subquery)isx <> v1 AND x <> v2 AND .... If anyvis NULL, every comparison chain becomes UNKNOWN, so no rows come back.NOT EXISTSonly asks 'is there a row?' so NULLs do not affect it. It is the safe default for anti-joins.EXISTScan stop at the first match. Modern planners (PostgreSQL, MySQL 8) turn bothINandEXISTSinto the same semi-join plan, so pick for clarity, not speed.- A plain
INNER JOINused as a filter duplicates left rows when the right side has many matches;EXISTSdoes not.
Interview questions
- Why can
NOT INreturn 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.
UNIONremoves duplicates (needs a sort or hash).UNION ALLkeeps everything and is cheaper. Default toUNION ALLwhen duplicates are impossible or wanted.INTERSECTreturns rows in both results;EXCEPTreturns rows in the first but not the second (MINUSin 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/LIMITat the end applies to the combined result. To sort or limit a part, wrap it in a subquery. - Precedence:
INTERSECTbinds tighter thanUNION/EXCEPTin 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 BYor 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 loneMAX()/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 ENDis the SQL if/else. WithoutELSE, the result is NULL. It works inSELECT,WHERE,ORDER BY,GROUP BYand inside aggregates.- Conditional aggregation:
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END). PostgreSQL and SQLite also supportCOUNT(*) FILTER (WHERE status = 'paid'). ROLLUP,CUBEandGROUPING SETSproduce subtotals (PostgreSQL, SQL Server; MySQL hasWITH 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/ALLare not supported in SQLite). - PostgreSQL and MySQL 8 support
LATERAL(SQL Server:CROSS APPLY) for a derived table that can reference earlierFROMitems, 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 ALLrecursive member that references the CTE. It runs until the recursive part returns no rows. - Syntax: PostgreSQL and MySQL 8 need
WITH RECURSIVE; SQL Server omitsRECURSIVE; SQLite accepts both. - Always include a stop condition (
WHERE depth < 10) or cycle protection; PostgreSQL 14+ also has aCYCLEclause.UNION(notALL) 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 BYsplits rows into groups;ORDER BYorders 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()andCUME_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,LEADreads n rows ahead within the partition. Use them for day-over-day change, previous status, session gaps.FIRST_VALUE,LAST_VALUE,NTH_VALUEread a specific row of the frame.- Frame syntax:
{ROWS | RANGE | GROUPS} BETWEEN start AND end, with boundsUNBOUNDED PRECEDING,n PRECEDING,CURRENT ROW,n FOLLOWING,UNBOUNDED FOLLOWING. ROWScounts physical rows.RANGEuses theORDER BYvalue, so peer rows (ties) are included together.GROUPScounts peer groups (PostgreSQL 11+, SQLite).- Default frame with
ORDER BY:RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. WithoutORDER 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). AddROWS 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).RANGEwith 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 tis DDL: deallocates data pages, noWHERE, minimal logging, much faster on big tables, resets identity/auto-increment in most engines, does not fireDELETEtriggers.DROP TABLE tremoves data and structure: indexes, constraints, triggers and grants go too. Dependent views break or block the drop (CASCADEin PostgreSQL).- Rollback: PostgreSQL can roll back
TRUNCATEandDROPinside a transaction. MySQL commits implicitly, so they cannot be undone. TRUNCATEis blocked when other tables reference it by foreign key (PostgreSQL: unlessCASCADE; MySQL InnoDB: always).- SQLite has no
TRUNCATE:DELETE FROM twithoutWHEREuses 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. ActionsON DELETE/UPDATE CASCADE | SET NULL | SET DEFAULT | RESTRICT | NO ACTION.CHECK (expr): row must not make the expression FALSE (UNKNOWN passes). MySQL enforcesCHECKonly 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 OPTIONblocks writes that would vanish from the view. SQLite views are read-only unless you addINSTEAD OFtriggers. - 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 ...andREFRESH MATERIALIZED VIEW [CONCURRENTLY] mv.CONCURRENTLYkeeps 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(...)(EXECin SQL Server). It can run many statements and, in PostgreSQL 11+,COMMIT/ROLLBACKinside. - 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,AFTERorINSTEAD OFanINSERT/UPDATE/DELETE, per row or per statement. Uses: audit logs, derived columns, enforcing complex rules. - In triggers,
NEWis the incoming row andOLDis the previous row (SQL Server usesinserted/deletedtables). - 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 useRANK() OVER (PARTITION BY dept ORDER BY salary DESC) = 1(keeps ties). - Find duplicates:
GROUP BYthe duplicate columnsHAVING COUNT(*) > 1. Delete duplicates: keepMIN(id)per group, or delete whereROW_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) orDENSE_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 onb.date <= a.dateandGROUP 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)andCOUNT(*)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 useDENSE_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 compareLAG/LEADvalues.
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.