Skip to content
Commitwise
Menu
Databases

SQL interview problems

The SQL questions interviews actually ask, solved step by step. Covers a method for any query problem, second highest salary, employees who earn more than their manager, top N per group with ties, the latest row per group, deleting duplicates, login streaks, month-over-month growth and cohort retention, plus the edge cases that interviewers check.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

SQL interviews reuse a small set of problems with new table names: the second highest value, the best row per group, duplicates, streaks of consecutive days, growth compared with last month, retention by signup month. Once you recognise the pattern, the work is in the details: ties, NULLs, missing days and empty results. That’s also where interviewers spend their questions.

This lesson solves the classics with the tools from the earlier lessons, especially Joins, Aggregation, Subqueries and CTEs and Window functions. Besides the shop tables, it uses a small company:

departments (id, name)
employees   (id, name, department_id, manager_id, salary)   -- manager_id points to employees.id
logins      (user_id, login_at)                              -- one row per sign-in

New to some of these? Open what you need, or skip ahead.

Basics:GROUP BY and aggregates

count, sum, avg, min and max turn many rows into one value; GROUP BY gives one row per group; HAVING filters groups. WHERE runs before grouping, so it can’t use avg(…). See Aggregation.

Basics:Subqueries and WITH

A query in parentheses can be used as a table: FROM (SELECT …) AS t. WITH name AS (…) names such a step so the main query can use it. See Subqueries and CTEs.

Basics:Window functions

A window function computes a value for each row from related rows, without collapsing them: row_number() OVER (PARTITION BY department_id ORDER BY salary DESC) numbers employees inside each department, and lag(revenue) OVER (ORDER BY month) reads the previous row’s value. See Window functions.

Part Not started

A method for any SQL question

Most SQL interview questions are a sentence and a few tables: “Find the employees who earn more than their manager.” Jumping straight into SELECT is how people end up with a query that almost works. A short routine avoids that:

  1. Read the tables. What is one row of each? Which columns are keys, and which can be NULL?
  2. Say the grain of the answer: “one row per employee”, “one row per department and month”. It tells you what to group by and what to join.
  3. Ask about the edge cases before the interviewer does: What if two people have the same salary? What if a department has no employees? What should come back when there’s no answer, no rows or NULL?
  4. Build it in steps. Write each step as a CTE with a name (WITH ranked AS (…)), check it, then use it in the next one.
  5. Test it on a tiny example in your head: three or four rows, including a tie and a NULL.

Here’s the routine on a classic: employees who earn more than their manager. One row is an employee, and manager_id points to another row of the same table. The answer is one row per employee. To compare an employee with their manager, put the table next to itself, a self-join:

SELECT e.name, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;

The edge case: the CEO has no manager (manager_id is NULL). The inner join drops them, which is right here, because they can’t earn more than a manager they don’t have.

The other classic is the second highest salary. With salaries 100, 100 and 90, the answer is 90: the question is about different salary amounts, so duplicates have to go first. And when there’s only one salary, the expected answer is usually a single row with NULL, not an empty result.

  • Grain first: say “one row per X” out loud; most wrong answers come from joins that change the grain (fan-out before sum) or groups at the wrong level.
  • Clarify ties and empties before coding: row_number vs rank vs dense_rank; “no rows” vs a NULL row; include or exclude zero-activity entities (left join from the full list).
  • Build with CTEs, one idea per step, then mention you could inline them. In PostgreSQL 12+ CTEs are inlined unless referenced twice or MATERIALIZED, so readability costs nothing.
  • Classic traps to check aloud: NOT IN with a NULL in the subquery, count(*) after a left join, integer division, conditions on the outer table in WHERE, BETWEEN on timestamps, time zones when grouping by day.
  • Dialect: LIMIT/OFFSET (PostgreSQL, MySQL, SQLite), FETCH FIRST n ROWS ONLY (standard, PostgreSQL, Oracle 12c+), TOP and OFFSET … FETCH (SQL Server); date functions differ everywhere. Say which dialect you’re writing.
  • Nth highest generalises: dense_rank() = n, or DISTINCT … ORDER BY … OFFSET n - 1 LIMIT 1 wrapped in a scalar subquery so an empty answer becomes NULL.

Predict the output

Salaries are 100, 100 and 90. What does this query return as the second highest salary?

SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
-- 1. the biggest salary below the biggest (NULL when there is none)
SELECT max(salary) AS second_highest
FROM employees
WHERE salary < (SELECT max(salary) FROM employees);

-- 2. distinct amounts, skip one; the outer SELECT turns "no row" into NULL
SELECT (
    SELECT DISTINCT salary
    FROM employees
    ORDER BY salary DESC
    LIMIT 1 OFFSET 1
) AS second_highest;

-- 3. dense_rank: ties share a rank and no rank is skipped, so this works for any N
WITH ranked AS (
    SELECT salary, dense_rank() OVER (ORDER BY salary DESC) AS rnk
    FROM employees
)
SELECT max(salary) AS second_highest   -- max() returns one row, NULL if empty
FROM ranked
WHERE rnk = 2;

Practice: three warm-ups

Exerciseeasy

Managers, departments and lonely customers

  1. List managers who have at least three direct reports, with how many they have.
  2. List every department with its number of employees, including departments with none (shown as 0).
  3. List customers (from the shop tables) who have never placed an order.
›

1 is a self-join or a plain GROUP BY manager_id, plus HAVING. 2 needs every department even without matches: which join keeps all rows of one side?

›

For 2, count a column of the employee side, not *: a department with no employees still gets one row from the left join. For 3, look for customers for whom no order exists.

SolutionTry it yourself first
-- 1
SELECT m.id, m.name, count(*) AS reports
FROM employees e
JOIN employees m ON m.id = e.manager_id
GROUP BY m.id, m.name
HAVING count(*) >= 3;

-- 2
SELECT d.name, count(e.id) AS employees
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.id, d.name
ORDER BY employees DESC;

-- 3
SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

In 2, count(*) would show 1 for an empty department, because the left join keeps it as one row with NULLs. In 3, NOT IN (SELECT customer_id FROM orders) works only while customer_id can never be NULL; NOT EXISTS is safe either way.

Deep diveWhat interviewers actually gradeInterview favorite

A live SQL round usually scores four things, in this order.

  1. Correctness on the edge cases: ties, NULLs, duplicates, empty groups, the right answer when nothing matches. Interviewers often have a hidden test table with exactly those rows. Asking “should ties both count?” earns as much as solving it.
  2. The grain: does the result have one row per thing the question asked for? A join to order_items before sum(o.total) multiplies totals; a GROUP BY with an extra column splits groups.
  3. Readability: named CTEs, aliases that mean something, one idea per step. A correct 40-line query nobody can follow scores lower than a clear one with a small bug you catch yourself.
  4. Performance, when asked: which index serves the query ((department_id, salary DESC) for top earners per department), why WHERE date(login_at) = … can’t use an index on login_at but a range can, and that window functions sort, so a PARTITION BY on 100 million rows needs memory or an index in the same order.

Talk while you write: “First I’ll get one row per user and day, then number them.” If you’re stuck, write the brute-force version (a correlated subquery per row) and say how you’d improve it. That’s a far better signal than silence.

  • State the grain, clarify ties, NULLs and empty results, build in CTEs, test on a tiny table with a tie and a NULL.
  • Self-join for row-vs-related-row (employee vs manager). Left join from the full list plus count(child.id) for zero counts. NOT EXISTS over NOT IN.
  • Nth highest: dense_rank() = n or DISTINCT … OFFSET n - 1 in a scalar subquery for NULL on empty.
  • Graded on edge cases, grain, readability, then indexes.
SELECT (SELECT DISTINCT salary FROM employees
        ORDER BY salary DESC LIMIT 1 OFFSET 1) AS second_highest;

SELECT e.name FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;

Check this part

  1. How do you compare each employee with their manager when both are in the employees table?

  2. Departments with their employee count, including empty ones. Which count is right after LEFT JOIN employees e?

  3. Salaries 100, 100, 90. Which gives 90 as the second highest?

  4. Only one employee exists. How do you return a row with NULL instead of no rows?

Before writing SQL, state the grain of the result (one row per what), then ask about ties, NULLs, duplicates and empty results. Build the query in named steps and check it against a tiny example. Second highest salary needs DISTINCT and must return NULL when there is none; self-joins compare a row with a related row of the same table.

Part Not started

Top N per group and duplicates

“The highest-paid employee in each department”, “the three best-selling products per category”, “each customer’s latest order”: these are all top N per group, the most common SQL interview problem. GROUP BY can’t solve it alone, because it returns one value per group (the highest salary) but not the row it came from (whose salary it is).

The pattern has two steps:

  1. Number the rows inside each group with a window function.
  2. Keep the rows with a small enough number.
WITH ranked AS (
    SELECT e.*,
           rank() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
    FROM employees e
)
SELECT department_id, name, salary
FROM ranked
WHERE rnk = 1;

The filter has to be outside, in a second step: window functions run after WHERE, so WHERE rank() OVER (…) = 1 isn’t allowed.

Which numbering function you pick decides what happens with ties, so it’s the first thing to ask about:

salaryrow_number()rank()dense_rank()
100111
100211
90332
80443
  • row_number(): always exactly N rows; among ties, which one comes first is arbitrary unless you add another column to ORDER BY.
  • rank(): ties share a number, and the next number is skipped.
  • dense_rank(): ties share a number, nothing is skipped.

Duplicates are the other classic. Finding them is GROUP BY with HAVING count(*) > 1. Deleting them means keeping one row per group, usually the one with the lowest id, and removing the rest. Afterwards, add a unique index so they can’t come back.

  • Top N per group: ranking function in a CTE, filter outside. Choose row_number (exactly N, add a tie-breaker such as id for determinism), rank (all tied, may exceed N) or dense_rank (N distinct values).
  • Latest per group in PostgreSQL: SELECT DISTINCT ON (customer_id) … ORDER BY customer_id, created_at DESC. Shorter, and with an index on (customer_id, created_at DESC) fast. For few groups with many rows each, a LATERAL (… ORDER BY created_at DESC LIMIT 1) per group can beat both by reading one index entry per group.
  • Without window functions (old MySQL): join to a grouped subquery on both the group key and the max, or NOT EXISTS a better row in the same group.
  • QUALIFY (Snowflake, BigQuery, Databricks, DuckDB, Teradata) filters on window results directly: QUALIFY row_number() OVER (…) = 1. Not in PostgreSQL, MySQL or SQL Server.
  • Dedup: DELETE … USING self-join with a.id > b.id, or DELETE … WHERE id IN (SELECT id FROM (SELECT id, row_number() OVER (PARTITION BY key ORDER BY id) rn …) WHERE rn > 1). Normalise the key the same way the unique index will (lower(email)), then add the index so the bug can’t recur, and use ON CONFLICT in the writer.

Predict the output

One department has salaries 100, 100, 90 and 80. Each query keeps rows where its numbering is at most 2. How many rows does each return, for row_number, rank and dense_rank?

WITH ranked AS (
    SELECT salary,
           row_number() OVER (ORDER BY salary DESC) AS rn,
           rank()       OVER (ORDER BY salary DESC) AS rnk,
           dense_rank() OVER (ORDER BY salary DESC) AS drnk
    FROM employees
    WHERE department_id = 3
)
SELECT count(*) FILTER (WHERE rn <= 2),
       count(*) FILTER (WHERE rnk <= 2),
       count(*) FILTER (WHERE drnk <= 2)
FROM ranked;
-- top 3 products by revenue in each category (ties beyond 3 are cut, tie-breaker id)
WITH revenue AS (
    SELECT p.id, p.name, p.category_id,
           sum(oi.quantity * oi.unit_price) AS revenue
    FROM order_items oi
    JOIN orders o   ON o.id = oi.order_id AND o.status = 'PAID'
    JOIN products p ON p.id = oi.product_id
    GROUP BY p.id, p.name, p.category_id
), ranked AS (
    SELECT *, row_number() OVER (PARTITION BY category_id ORDER BY revenue DESC, id) AS rn
    FROM revenue
)
SELECT category_id, name, revenue
FROM ranked
WHERE rn <= 3
ORDER BY category_id, rn;

-- each customer's latest order (PostgreSQL)
SELECT DISTINCT ON (customer_id) customer_id, id, created_at, total
FROM orders
ORDER BY customer_id, created_at DESC, id DESC;

-- duplicate emails, then delete all but the lowest id
SELECT lower(email), count(*) FROM customers GROUP BY lower(email) HAVING count(*) > 1;

DELETE FROM customers a
USING customers b
WHERE lower(a.email) = lower(b.email)
  AND a.id > b.id;

CREATE UNIQUE INDEX customers_email_key ON customers (lower(email));

The top earner in two departments at once

Spot the bugHighest-paid employee per department

Tap the line with the bug.

SELECT e.department_id, e.name, e.salary
FROM employees e
JOIN (SELECT department_id, max(salary) AS top
      FROM employees
      GROUP BY department_id) m
  ON e.salary = m.top;

Deep diveDeleting duplicates from a 50-million-row tableInterview favorite

The interview version is “write a query that removes duplicates”. The production version adds: the table is live, writes keep coming, and the query must not lock it for an hour or blow up the WAL and replicas.

  1. Measure first: how many duplicate groups and extra rows? SELECT count(*) - count(DISTINCT lower(email)) FROM customers tells you whether it’s 200 rows or 20 million.
  2. Stop new duplicates before cleaning, or you’re bailing water. The unique index can’t be built while duplicates exist, so fix the writer (INSERT … ON CONFLICT, or check-and-insert under a lock), or add a trigger temporarily.
  3. Decide which row survives and what happens to rows that point at the others: orders of the duplicate customers must be moved to the survivor first (UPDATE orders SET customer_id = survivor …), or the foreign keys will stop the delete or cascade it.
  4. Compute the survivors once, over the whole table, then repoint and delete in batches of a few thousand ids, one short transaction each, so locks stay short, autovacuum keeps up and replicas don’t lag:
CREATE TABLE dedup_map AS
SELECT id, survivor_id
FROM (SELECT id, min(id) OVER (PARTITION BY lower(email)) AS survivor_id
      FROM customers) t
WHERE id <> survivor_id;

-- repeated for each id range, $1 to $2
BEGIN;
UPDATE orders o SET customer_id = m.survivor_id
FROM dedup_map m
WHERE o.customer_id = m.id AND m.id BETWEEN $1 AND $2;

DELETE FROM customers c
USING dedup_map m
WHERE c.id = m.id AND m.id BETWEEN $1 AND $2;
COMMIT;

The tempting shortcut, row_number() computed inside each batch’s id range, only finds duplicates within that range and misses the rest.

  1. Lock the door: CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (lower(email)). If it fails, it leaves an invalid index to drop and retry.

When most of the table is duplicates, copying the survivors into a new table and swapping names is faster than deleting, at the cost of a short exclusive lock for the swap.

  • Top N per group: ranking in a CTE, filter outside (QUALIFY where supported). row_number + tie-breaker for exactly N; rank/dense_rank for ties.
  • Latest per group: DISTINCT ON (PostgreSQL), row_number() = 1, or LATERAL … LIMIT 1 with a matching index.
  • Join-to-max must match the group key and the value.
  • Dedup: survivor = lowest id, repoint foreign keys, delete in batches from a precomputed survivor map, then a unique index built CONCURRENTLY.
SELECT * FROM (
  SELECT e.*, dense_rank() OVER (PARTITION BY department_id ORDER BY salary DESC) AS r
  FROM employees e) t
WHERE r <= 3;

DELETE FROM customers a USING customers b
WHERE lower(a.email) = lower(b.email) AND a.id > b.id;

Check this part

  1. Why can't you write WHERE rank() OVER (…) = 1?

  2. Duplicate customers by email: which one is usually kept?

  3. Each customer's latest order in PostgreSQL, shortest correct query?

  4. You dedupe in batches by id range with row_number() inside each batch. What goes wrong?

Top N per group is a ranking window function in a CTE, filtered outside: row_number for exactly N, rank or dense_rank when ties should all count. The latest row per group is row_number = 1 (or DISTINCT ON in PostgreSQL). Duplicates are found with GROUP BY and HAVING and deleted by keeping the lowest id per key, then prevented with a unique index.

Part Not started

Streaks, growth and retention

Product and analytics interviews love questions about time: “users who logged in three days in a row”, “revenue growth compared with the previous month”, “of the people who signed up in January, how many came back in February?”. Three ideas cover most of them.

1. One row per user and day first. logins has one row per sign-in, and some people sign in five times a day. Most questions are about days, so start by reducing to one row per user and day:

SELECT DISTINCT user_id, login_at::date AS day
FROM logins;

2. Consecutive days share a constant. Number each user’s days in order with row_number(). On consecutive days, the date goes up by one and the number goes up by one, so date minus number stays the same. A gap breaks it:

dayrow_numberday − row_number days
Nov 31Nov 2
Nov 42Nov 2
Nov 53Nov 2
Nov 84Nov 4
Nov 95Nov 4

Group by that value, and each group is a streak: Nov 3–5 (3 days) and Nov 8–9 (2 days). This is the gaps and islands trick from the Window functions lesson.

3. Compare with the previous period using lag, but only over a complete list of periods. If a month has no sales, it has no row, and lag silently compares with the month before it. Generate every month first and left join the data, as in Aggregation.

  • Grain: reduce events to one row per entity and period (DISTINCT user_id, day) before windowing; duplicates break row_number arithmetic and inflate counts.
  • Islands: day - row_number() OVER (PARTITION BY user_id ORDER BY day) * interval '1 day' (or day - rn on date, which gives a date) as the group key; min, max and count per group give streak start, end and length. For “N days in a row” alone, lead(day, N - 1) equals day + N - 1 is shorter.
  • Period over period: lag over a generated series; growth as 100.0 * (cur - prev) / NULLIF(prev, 0); year over year with lag(x, 12) only when every month exists.
  • Time zones: “a day” is a business-time-zone day: (login_at AT TIME ZONE 'Europe/Belgrade')::date.
  • Retention / cohorts: cohort = first activity (or signup) month; age = months between cohort and activity; count(DISTINCT user_id) per cohort and age, divided by the cohort size (first_value or a join). Define “retained” precisely (any activity in month N, or in month N and later).
  • Rolling windows: 7-day active users can’t be a window function, because count(DISTINCT …) OVER isn’t allowed. Join each day of a generated series to the previous seven days of the per-user-day table and count(DISTINCT user_id).

Predict the output

Paid revenue exists for September (100) and November (150), but October had no sales at all, so it has no row. What is prev for November?

WITH monthly AS (
    SELECT date_trunc('month', created_at) AS month, sum(total) AS revenue
    FROM orders
    WHERE status = 'PAID'
    GROUP BY 1
)
SELECT month, revenue,
       lag(revenue) OVER (ORDER BY month) AS prev
FROM monthly;
-- every login streak per user: start, end, length
WITH days AS (
    SELECT DISTINCT user_id, login_at::date AS day
    FROM logins
), grouped AS (
    SELECT user_id, day,
           day - row_number() OVER (PARTITION BY user_id ORDER BY day)::int AS streak_key
    FROM days
)
SELECT user_id, min(day) AS first_day, max(day) AS last_day, count(*) AS length
FROM grouped
GROUP BY user_id, streak_key
ORDER BY length DESC;

-- month-over-month revenue growth, with empty months as 0
WITH months AS (
    SELECT generate_series(date '2026-01-01', date '2026-11-01', interval '1 month') AS month
), monthly AS (
    SELECT m.month, COALESCE(sum(o.total), 0) AS revenue
    FROM months m
    LEFT JOIN orders o
           ON o.status = 'PAID'
          AND o.created_at >= m.month
          AND o.created_at <  m.month + interval '1 month'
    GROUP BY m.month
)
SELECT month, revenue,
       round(100.0 * (revenue - lag(revenue) OVER w) / NULLIF(lag(revenue) OVER w, 0), 1) AS growth_pct
FROM monthly
WINDOW w AS (ORDER BY month)
ORDER BY month;

Practice: three days in a row

Exercisemedium

Users who logged in on three consecutive days

Using logins (user_id, login_at), list each user who logged in on at least three consecutive days at some point. Each user appears once. A user may log in several times a day.

›

Start with one row per user and day. Several logins on one day must count as one day.

›

Two ways work. Either the gaps-and-islands key (day - row_number()) and HAVING count(*) >= 3, or look two rows ahead with lead(day, 2) and check that it is exactly two days later.

SolutionTry it yourself first
WITH days AS (
    SELECT DISTINCT user_id, login_at::date AS day
    FROM logins
), ahead AS (
    SELECT user_id, day,
           lead(day, 2) OVER (PARTITION BY user_id ORDER BY day) AS day_after_next
    FROM days
)
SELECT DISTINCT user_id
FROM ahead
WHERE day_after_next = day + 2;

Because each user has at most one row per day (thanks to DISTINCT), the row two places ahead is exactly two days later only if the day in between is there too. Without the first step, two logins on Monday and one on Tuesday would look like three consecutive days. DISTINCT user_id at the end lists a user with a five-day streak once, not three times.

Deep diveCohort retention in one queryInterview favorite

“Build a retention table: for each signup month, what share of users ordered again 1, 2, 3 months later?” It’s a favourite in product and data interviews because it combines everything: grain, date arithmetic, distinct counts and a ratio.

WITH first_orders AS (                     -- cohort = month of each customer's first paid order
    SELECT customer_id, date_trunc('month', min(created_at)) AS cohort
    FROM orders
    WHERE status = 'PAID'
    GROUP BY customer_id
), activity AS (                           -- one row per customer and active month
    SELECT DISTINCT customer_id, date_trunc('month', created_at) AS month
    FROM orders
    WHERE status = 'PAID'
), aged AS (
    SELECT f.cohort, a.customer_id,
           (extract(year FROM a.month) - extract(year FROM f.cohort)) * 12
         + (extract(month FROM a.month) - extract(month FROM f.cohort)) AS age
    FROM activity a
    JOIN first_orders f USING (customer_id)
)
SELECT cohort, age,
       count(*) AS customers,
       round(100.0 * count(*) / first_value(count(*)) OVER (PARTITION BY cohort ORDER BY age), 1) AS pct
FROM aged
GROUP BY cohort, age
ORDER BY cohort, age;

Details worth saying out loud: activity is already one row per customer and month, so count(*) counts customers; age 0 is the cohort month itself, always 100%, which is why first_value can be the denominator; an age with nobody active is missing rather than 0% (left join to a generated grid of cohorts and ages if the chart needs it); the last cohorts have had less time, so their later ages are empty, not zero. Pivoting ages into columns (count(*) FILTER (WHERE age = 1)) gives the familiar triangle. On big event tables, precompute the per-user-month table (a materialized view or a daily job) rather than scanning events for every dashboard load.

  • Reduce to one row per entity and period first (DISTINCT user_id, day), in the business time zone.
  • Streaks: day - row_number() as the group key; “N in a row”: lead(day, N - 1) = day + N - 1.
  • Growth: lag over a generated series of periods; NULLIF the divisor.
  • Cohorts: first month per user, age in months, count per cohort and age over cohort size (first_value).
WITH d AS (SELECT DISTINCT user_id, login_at::date AS day FROM logins)
SELECT user_id, min(day), max(day), count(*) AS len
FROM (SELECT *, day - row_number() OVER (PARTITION BY user_id ORDER BY day)::int AS k FROM d) t
GROUP BY user_id, k
HAVING count(*) >= 3;

Check this part

  1. Why reduce logins to one row per user and day before counting streaks?

  2. Days Nov 3, 4, 5, 8, 9 with row numbers 1 to 5. How many streaks?

  3. October had no sales. What does lag(revenue) OVER (ORDER BY month) compare November with?

  4. In a cohort table, what is age 0?

Time questions are about consecutive or missing periods. Streaks are gaps and islands: subtract row_number from the day so consecutive days share a group. Month-over-month growth uses lag over a complete series of months, so a missing month doesn't compare November with September. Retention groups users by their first month and counts who came back in later months.

Key takeaways

  • Read the tables, say the grain of the answer, ask about ties, NULLs and empty results, build in named steps, test on a tiny example.
  • Self-join to compare a row with a related row; left join plus count(child.id) to keep zero counts; NOT EXISTS for “never”.
  • Second highest: remove duplicates, and return NULL when there’s none.
  • Top N per group: rank in a CTE, filter outside; the ranking function decides what ties do.
  • Time questions: one row per user and day first; streaks with day minus row number; lag only over a complete list of periods.
  • Interviewers grade edge cases and grain first, then readability, then indexes.
  • row_number + tie-breaker, rank, dense_rank; DISTINCT ON and LATERAL for latest per group; QUALIFY where available.
  • Production dedup: survivor map, repoint foreign keys, batched deletes, CREATE UNIQUE INDEX CONCURRENTLY.
  • Growth over a generated series with NULLIF; cohorts with first month, age and first_value as denominator.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.