← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 15 of 26

Want the full pack? Interview packs · Mock interview · Mentora

Page 15 of 26

Questions 281–300 of 501 · 0 of 20 on this page marked learned

281.sql-0281Hardsenior

What is a LATERAL join, and how would you use it to get each customer's two most recent orders?

A LATERAL subquery in FROM can refer to columns of tables listed before it, so it runs once per outer row. In PostgreSQL, FROM customers c CROSS JOIN LATERAL (SELECT ... FROM orders WHERE customer_id = c.id ORDER BY order_date DESC LIMIT 2) gives the top two per customer and can use an index on (customer_id, order_date). SQLite has no LATERAL; a ROW_NUMBER window does the same job.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

PostgreSQL:

sql
SELECT c.name, o.id, o.order_date
FROM customers c
CROSS JOIN LATERAL (
  SELECT id, order_date FROM orders WHERE customer_id = c.id ORDER BY order_date DESC LIMIT 2
) o
ORDER BY c.name, o.order_date DESC;
nameidorder_date
Ana1022026-02-11
Ana1012026-01-05
Bilal1052026-03-09
Bilal1032026-02-14
Chloe1042026-03-01

The subquery sees c.id, which an ordinary derived table cannot. LEFT JOIN LATERAL ... ON true would also keep Dev, who has no orders.

SQLite rejects the keyword:

sql
SELECT c.name, o.id FROM customers c CROSS JOIN LATERAL (SELECT id FROM orders WHERE customer_id = c.id LIMIT 2) o;  -- error on purpose
text
Error: near "SELECT": syntax error

The window version works on both engines:

sql
SELECT name, id, order_date FROM (
  SELECT c.name, o.id, o.order_date,
         ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY o.order_date DESC) AS rn
  FROM customers c JOIN orders o ON o.customer_id = c.id
) WHERE rn <= 2 ORDER BY name, order_date DESC;
nameidorder_date
Ana1022026-02-11
Ana1012026-01-05
Bilal1052026-03-09
Bilal1032026-02-14
Chloe1042026-03-01

LATERAL shines when the per-row subquery is cheap with an index and the outer table is small, because it reads only N rows per customer. The window version ranks every order first.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

-- error on purpose
SELECT c.name, o.id FROM customers c CROSS JOIN LATERAL (SELECT id FROM orders WHERE customer_id = c.id LIMIT 2) o;

SELECT name, id, order_date FROM (
  SELECT c.name, o.id, o.order_date,
         ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY o.order_date DESC) AS rn
  FROM customers c JOIN orders o ON o.customer_id = c.id
) WHERE rn <= 2 ORDER BY name, order_date DESC;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • LATERAL subqueries can reference earlier FROM items
  • They run once per outer row
  • Ideal for top-N per group with an index
  • SQLite lacks LATERAL; use ROW_NUMBER

Common mistakes

  • Using CROSS JOIN LATERAL and losing parents with no rows
  • Expecting a plain derived table to see outer columns

Follow-ups

  • When would the window version be faster?
  • What does LEFT JOIN LATERAL ... ON true do?

Tips

  • Mention the index that makes LATERAL fast
282.sql-0282Mediummid

Write a query that finds pairs of room bookings that overlap in time.

Two half-open intervals [s1, e1) and [s2, e2) overlap when s1 < e2 AND s2 < e1. Self join the bookings on the same room with that condition and a.id < b.id so each pair appears once. Back-to-back bookings, where one ends exactly when the next starts, do not overlap under half-open rules.

Full answer
sql
WITH b(id, room, s, e) AS (VALUES
  (1, 'A', '09:00', '10:30'), (2, 'A', '10:00', '11:00'),
  (3, 'A', '11:00', '12:00'), (4, 'B', '09:30', '10:30'))
SELECT x.id AS booking, y.id AS clashes_with
FROM b x JOIN b y ON x.room = y.room AND x.id < y.id AND x.s < y.e AND y.s < x.e
ORDER BY booking;
bookingclashes_with
12

Bookings 1 and 2 overlap between 10:00 and 10:30. Booking 3 starts exactly when booking 2 ends, so with half-open intervals it is not a clash. Booking 4 is in another room.

The condition a.start < b.end AND b.start < a.end covers every overlap shape: partial, one inside the other, and identical. Trying to list the cases separately usually misses one.

PostgreSQL can prevent overlaps at write time with range types and an exclusion constraint, EXCLUDE USING gist (room WITH =, tsrange(start, end) WITH &&), which needs the btree_gist extension (not run here).

sql
WITH b(id, room, s, e) AS (VALUES
  (1, 'A', '09:00', '10:30'), (2, 'A', '10:00', '11:00'),
  (3, 'A', '11:00', '12:00'), (4, 'B', '09:30', '10:30'))
SELECT x.id AS booking, y.id AS clashes_with
FROM b x JOIN b y ON x.room = y.room AND x.id < y.id AND x.s < y.e AND y.s < x.e
ORDER BY booking;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Overlap test: s1 < e2 AND s2 < e1
  • Half-open intervals let back-to-back bookings coexist
  • Self join on the same room with a.id < b.id
  • PostgreSQL exclusion constraints can prevent overlaps

Common mistakes

  • Listing overlap cases separately and missing one
  • Using <= and flagging back-to-back bookings as clashes

Follow-ups

  • How would you find free slots in a day?
  • How would you prevent overlaps in SQLite?

Tips

  • Draw the two intervals on a line
283.sql-0283Mediummid

Is EXISTS always faster than IN for subqueries?

Not in modern engines. PostgreSQL usually plans IN (subquery) and EXISTS identically, and SQLite picks between a list lookup and a correlated probe based on indexes. The real differences are semantic: NOT IN breaks when the subquery returns a NULL, while NOT EXISTS does not. Check the plan rather than relying on folklore.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
EXPLAIN QUERY PLAN SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders);
text
QUERY PLAN
SEARCH customers USING INTEGER PRIMARY KEY (rowid=?)
LIST SUBQUERY 1
  SCAN orders
sql
EXPLAIN QUERY PLAN SELECT name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
text
QUERY PLAN
SCAN c
CORRELATED SCALAR SUBQUERY 1
  SCAN o

SQLite plans them differently here. For IN, it reads the orders subquery once into a list and looks up customers by primary key. For EXISTS, it scans customers and runs a correlated probe of orders per row, which is fast only with an index on orders.customer_id. Neither is always better; it depends on table sizes and indexes.

PostgreSQL turns both into the same plan, a hash join against the distinct customer ids from orders:

sql
EXPLAIN (COSTS OFF) SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders);
text
Hash Join
  Hash Cond: (customers.id = orders.customer_id)
  ->  Seq Scan on customers
  ->  Hash
        ->  HashAggregate
              Group Key: orders.customer_id
              ->  Seq Scan on orders
sql
EXPLAIN (COSTS OFF) SELECT name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
text
Hash Join
  Hash Cond: (c.id = o.customer_id)
  ->  Seq Scan on customers c
  ->  Hash
        ->  HashAggregate
              Group Key: o.customer_id
              ->  Seq Scan on orders o

The old advice that EXISTS is always faster comes from older optimizers that ran IN subqueries naively.

What does matter:

  • NOT IN with a nullable column returns no rows if any NULL is present (shown in the NULL questions), so prefer NOT EXISTS for anti-joins.
  • IN (1, 2, 3) with literals is a different case: a list, not a subquery.
  • Correlated EXISTS can use an index on the correlated column.

Pick the form that states the intent most clearly, then confirm with EXPLAIN.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

EXPLAIN QUERY PLAN SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders);

EXPLAIN QUERY PLAN SELECT name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • PostgreSQL gives IN and EXISTS subqueries the same plan here
  • NOT IN fails with NULLs; NOT EXISTS does not
  • Check plans instead of rules of thumb
  • Indexes on the correlated column matter most

Common mistakes

  • Rewriting every IN as EXISTS for speed
  • Using NOT IN on a nullable column

Follow-ups

  • How does a semi-join differ from an inner join?
  • When can IN with a long literal list be slow?

Tips

  • Separate performance from NULL semantics
284.sql-0284Mediummid

Write an UPDATE that stores each customer's latest order date in a last_order_date column.

Use a correlated subquery in SET: UPDATE customers SET last_order_date = (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = customers.id). Customers with no orders get NULL, because MAX over no rows is NULL. Add a WHERE EXISTS if those rows should stay untouched.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
ALTER TABLE customers ADD COLUMN last_order_date TEXT;
UPDATE customers SET last_order_date = (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = customers.id);
SELECT name, last_order_date FROM customers ORDER BY id;
namelast_order_date
Ana2026-02-11
Bilal2026-03-09
Chloe2026-03-01
DevNULL

Each customer row runs the subquery for its own id. Dev has no orders, so his value is NULL.

UPDATE ... FROM with a pre-aggregated subquery computes all maxima in one pass, which helps on large tables:

sql
UPDATE customers SET last_order_date = m.d
FROM (SELECT customer_id, MAX(order_date) AS d FROM orders GROUP BY customer_id) m
WHERE m.customer_id = customers.id;
SELECT COUNT(last_order_date) AS customers_with_date FROM customers;
customers_with_date
3

Stored aggregates like this go stale as new orders arrive. Either recompute on a schedule, update it in the code path that creates orders, or use a trigger, and decide whether cancelled orders count.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

ALTER TABLE customers ADD COLUMN last_order_date TEXT;
UPDATE customers SET last_order_date = (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = customers.id);
SELECT name, last_order_date FROM customers ORDER BY id;

UPDATE customers SET last_order_date = m.d
FROM (SELECT customer_id, MAX(order_date) AS d FROM orders GROUP BY customer_id) m
WHERE m.customer_id = customers.id;
SELECT COUNT(last_order_date) AS customers_with_date FROM customers;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Correlated subqueries can supply values in SET
  • No matching rows yields NULL
  • UPDATE ... FROM with a grouped subquery is a one-pass alternative
  • Stored aggregates need a refresh strategy

Common mistakes

  • Forgetting the correlation and setting one global value
  • Letting the stored value drift

Follow-ups

  • How would you keep the column current?
  • Should cancelled orders count?

Tips

  • Mention staleness
285.sql-0285Hardsenior

A bill of materials says a bike has 2 wheels and each wheel has 32 spokes. Write a recursive query for the total number of each part needed for one bike.

Start from the top assembly with quantity 1, then join each part to its components and multiply the quantity on the path by the component quantity. Sum the results per part at the end, because the same part can appear under several assemblies.

Full answer
sql
WITH RECURSIVE bom(parent, part, qty) AS (VALUES
  ('bike', 'wheel', 2), ('bike', 'frame', 1), ('wheel', 'spoke', 32), ('wheel', 'hub', 1),
  ('wheel', 'bolt', 2), ('frame', 'bolt', 4)),
 need(part, qty) AS (
  SELECT 'bike', 1
  UNION ALL
  SELECT b.part, n.qty * b.qty FROM need n JOIN bom b ON b.parent = n.part
)
SELECT part, SUM(qty) AS total FROM need WHERE part <> 'bike' GROUP BY part ORDER BY part;
parttotal
bolt8
frame1
hub2
spoke64
wheel2

The recursion carries the cumulative quantity down the tree: 1 bike, 2 wheels, 2 × 32 = 64 spokes, 2 × 1 = 2 hubs. The frame's 4 bolts and the wheels' bolts (2 × 2 = 4) are added together in the final GROUP BY, giving 8.

Without the final SUM, a part that appears in several branches shows up as several rows. The same pattern answers "total cost of a product" if each leaf carries a unit price: multiply the quantity by the price and sum.

sql
WITH RECURSIVE bom(parent, part, qty) AS (VALUES
  ('bike', 'wheel', 2), ('bike', 'frame', 1), ('wheel', 'spoke', 32), ('wheel', 'hub', 1),
  ('wheel', 'bolt', 2), ('frame', 'bolt', 4)),
 need(part, qty) AS (
  SELECT 'bike', 1
  UNION ALL
  SELECT b.part, n.qty * b.qty FROM need n JOIN bom b ON b.parent = n.part
)
SELECT part, SUM(qty) AS total FROM need WHERE part <> 'bike' GROUP BY part ORDER BY part;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Seed the recursion with the top item and quantity 1
  • Multiply quantities along each path
  • Sum per part at the end
  • The same part can appear in several branches

Common mistakes

  • Adding quantities instead of multiplying them
  • Forgetting the final aggregation

Follow-ups

  • How would you compute the cost of one bike?
  • How would you detect a cycle in the parts data?

Tips

  • Walk through the multiplication for spokes
286.sql-0286Hardsenior

Write a recursive query that finds the fewest hops between two stations in a network of direct connections.

Run a breadth-first search with a recursive CTE: start at the source with 0 hops, follow edges while recording the path to avoid revisiting nodes, and stop at a depth limit. Then take the minimum hops among rows that reached the target. SQL can do this for small graphs; large graphs belong in a graph tool or application code.

Full answer
sql
WITH RECURSIVE edges(a, b) AS (VALUES ('A','B'),('A','C'),('B','D'),('C','E'),('E','D'),('D','F')),
 walk(node, hops, path) AS (
  SELECT 'A', 0, '/A/'
  UNION ALL
  SELECT e.b, w.hops + 1, w.path || e.b || '/'
  FROM walk w JOIN edges e ON e.a = w.node
  WHERE instr(w.path, '/' || e.b || '/') = 0 AND w.hops < 5
)
SELECT MIN(hops) AS fewest_hops, (SELECT path FROM walk WHERE node = 'D' ORDER BY hops LIMIT 1) AS path
FROM walk WHERE node = 'D';
fewest_hopspath
2/A/B/D/

The path string prevents loops: a station already on the path is not added again. The depth limit stops the search from exploring long detours. A to D can be reached as A, B, D (2 hops) or A, C, E, D (3 hops); the outer query keeps the shortest.

The number of paths grows quickly with graph size, because every distinct route is a row. For networks beyond a few thousand edges, use a dedicated graph algorithm, PostgreSQL's pgRouting extension, or code that tracks visited nodes globally.

sql
WITH RECURSIVE edges(a, b) AS (VALUES ('A','B'),('A','C'),('B','D'),('C','E'),('E','D'),('D','F')),
 walk(node, hops, path) AS (
  SELECT 'A', 0, '/A/'
  UNION ALL
  SELECT e.b, w.hops + 1, w.path || e.b || '/'
  FROM walk w JOIN edges e ON e.a = w.node
  WHERE instr(w.path, '/' || e.b || '/') = 0 AND w.hops < 5
)
SELECT MIN(hops) AS fewest_hops, (SELECT path FROM walk WHERE node = 'D' ORDER BY hops LIMIT 1) AS path
FROM walk WHERE node = 'D';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Recursive CTEs can run breadth-first searches
  • Track the path to avoid cycles
  • Limit depth to bound the work
  • Paths explode on large graphs

Common mistakes

  • Recursing without cycle protection
  • Using SQL for large-scale routing

Follow-ups

  • How would you return the actual path?
  • Why does UNION not prevent this explosion?

Tips

  • Mention the scaling limit
287.sql-0287Easyfresher

Write a query that lists managers with more than two direct reports.

Group employees by manager_id, keep groups with COUNT(*) > 2, and join to employees again for the manager's name. Exclude NULL manager_id so the top of the hierarchy is not treated as a manager group.

Full answer
sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT m.name AS manager, COUNT(*) AS direct_reports
FROM employees e JOIN employees m ON m.id = e.manager_id
GROUP BY m.id, m.name
HAVING COUNT(*) > 2
ORDER BY direct_reports DESC;
managerdirect_reports
Asha4

Asha manages Ravi, Mei, Tom and Diego, so she has four direct reports. Tom manages Sara and Lena (two), and Diego manages Omar (one), so neither passes the filter.

The join direction matters: e is the report and m the manager, joined on m.id = e.manager_id. Grouping by m.id rather than by name keeps two managers with the same name apart. Counting all levels below a manager, not just direct reports, needs the recursive query from the CTE questions.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT m.name AS manager, COUNT(*) AS direct_reports
FROM employees e JOIN employees m ON m.id = e.manager_id
GROUP BY m.id, m.name
HAVING COUNT(*) > 2
ORDER BY direct_reports DESC;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Group by manager_id to count direct reports
  • HAVING filters the counts
  • Join back for the manager's name
  • Indirect reports need recursion

Common mistakes

  • Counting all descendants when the question asks for direct reports
  • Treating NULL manager_id as a manager

Follow-ups

  • How would you count all reports at every level?
  • How would you list managers with no reports?

Tips

  • Clarify direct versus indirect
288.sql-0288Easyfresher

Generate one row for each month from January to June 2026, using a recursive CTE.

Seed the CTE with '2026-01-01' and add one month per step with date(m, '+1 month') until June. Starting on the first of the month keeps month arithmetic safe. In PostgreSQL, generate_series(DATE '2026-01-01', DATE '2026-06-01', INTERVAL '1 month') does the same.

Full answer
sql
WITH RECURSIVE m(month) AS (
  SELECT '2026-01-01'
  UNION ALL
  SELECT date(month, '+1 month') FROM m WHERE month < '2026-06-01'
)
SELECT substr(month, 1, 7) AS month FROM m;
month
2026-01
2026-02
2026-03
2026-04
2026-05
2026-06

Each step adds one month to the previous row, and the WHERE in the recursive part stops after June. Because every value is the first of a month, there is no month-end normalization problem.

PostgreSQL:

sql
SELECT to_char(d, 'YYYY-MM') AS month
FROM generate_series(DATE '2026-01-01', DATE '2026-06-01', INTERVAL '1 month') AS d;
month
2026-01
2026-02
2026-03
2026-04
2026-05
2026-06

A month list like this is the left side of a LEFT JOIN for reports that must show months with no data.

sql
WITH RECURSIVE m(month) AS (
  SELECT '2026-01-01'
  UNION ALL
  SELECT date(month, '+1 month') FROM m WHERE month < '2026-06-01'
)
SELECT substr(month, 1, 7) AS month FROM m;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Seed with the first month and add +1 month per step
  • Stop with a condition in the recursive part
  • Use first-of-month dates to avoid normalization
  • PostgreSQL generate_series works with intervals

Common mistakes

  • Starting from the 31st and drifting
  • Forgetting the stop condition

Follow-ups

  • How would you count orders per month with zeros?
  • How would you generate weeks instead?

Tips

  • Use it as a calendar for LEFT JOINs
289.sql-0289Hardsenior

When does an optimizer turn a correlated subquery into a join, and when does it really run once per row?

Optimizers decorrelate simple EXISTS, IN and some scalar subqueries into semi-joins, anti-joins or joins with aggregation, so they do not literally run per row. Subqueries with LIMIT, complex expressions or scalar results used in SELECT often stay correlated and run per outer row, which is fine with an index on the correlated column and slow without one.

Full answer

SQLite shows correlated scalar subqueries explicitly:

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
EXPLAIN QUERY PLAN
SELECT name, (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) AS last_order FROM customers c;
text
QUERY PLAN
SCAN c
CORRELATED SCALAR SUBQUERY 1
  SEARCH o

CORRELATED SCALAR SUBQUERY means it runs for each customer row, and the inner step names no index. After an index on orders(customer_id, order_date) is created, the plan shows a covering index search, so each per-row run is a direct lookup:

sql
CREATE INDEX orders_customer_date ON orders(customer_id, order_date);
EXPLAIN QUERY PLAN
SELECT name, (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) AS last FROM customers c;
text
QUERY PLAN
SCAN c
CORRELATED SCALAR SUBQUERY 1
  SEARCH o USING COVERING INDEX orders_customer_date (customer_id=?)

PostgreSQL rewrites EXISTS and IN into semi-joins but usually keeps a scalar subquery in SELECT as a SubPlan executed per row, unless it can be rewritten safely.

Practical rule: correlated subqueries are not automatically slow. They are slow when each execution scans a large table. Check the plan, index the correlated column, and rewrite as a join plus GROUP BY when the outer table is large and the subquery would scan.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

EXPLAIN QUERY PLAN
SELECT name, (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) AS last_order FROM customers c;

CREATE INDEX orders_customer_date ON orders(customer_id, order_date);
EXPLAIN QUERY PLAN
SELECT name, (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) AS last FROM customers c;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Simple EXISTS and IN become semi-joins
  • Scalar subqueries in SELECT often run per row
  • An index on the correlated column makes per-row runs cheap
  • Check the plan before rewriting

Common mistakes

  • Assuming every correlated subquery is slow
  • Rewriting into joins that change results (duplicates)

Follow-ups

  • How do you read a SubPlan in PostgreSQL EXPLAIN?
  • When would you rewrite with LATERAL?

Tips

  • Point to the plan line
290.sql-0290Mediummid

A join uses ON o.customer_id = c.id OR o.email = c.email. Why can an OR in a join condition be slow, and how does SQLite plan it?

An OR across different columns rules out a hash or merge join on one key. SQLite can still probe both indexes per row with a MULTI-INDEX OR plan, but only if every branch has an index; otherwise it compares rows pair by pair. Splitting the join into two joins combined with UNION gives each branch its own plan.

Full answer
sql
CREATE TABLE c (id INTEGER PRIMARY KEY, email TEXT);
CREATE TABLE o (id INTEGER PRIMARY KEY, customer_id INTEGER, email TEXT);
CREATE INDEX c_email ON c(email);
EXPLAIN QUERY PLAN SELECT o.id, c.id FROM o JOIN c ON o.customer_id = c.id OR o.email = c.email;
text
QUERY PLAN
SCAN o
MULTI-INDEX OR
  INDEX 3
    SEARCH c USING COVERING INDEX c_email (email=?)
  INDEX 4
    SEARCH c USING INTEGER PRIMARY KEY (rowid=?)

SQLite scans o and, for each order, probes the email index and the primary key separately, then merges the matches. That works because both branches are indexed. Without the email index, the email branch has nothing to probe:

sql
DROP INDEX c_email;
EXPLAIN QUERY PLAN SELECT o.id AS oid, c.id AS cid FROM o JOIN c ON o.customer_id = c.id OR o.email = c.email;
text
QUERY PLAN
SCAN o
SCAN c

The UNION rewrite gives each branch its own join plan and removes pairs that matched both ways:

sql
EXPLAIN QUERY PLAN
SELECT o.id, c.id FROM o JOIN c ON o.customer_id = c.id
UNION
SELECT o.id, c.id FROM o JOIN c ON o.email = c.email;
text
QUERY PLAN
COMPOUND QUERY
  LEFT-MOST SUBQUERY
    SCAN o
    SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
  UNION USING TEMP B-TREE
    SCAN o
    SEARCH c USING COVERING INDEX c_email (email=?)

Engines that cannot combine indexes for a join condition fall back to a nested loop that tests the OR for every pair of rows, which grows with the product of the table sizes.

The deeper question is the data model: if orders sometimes carry an id and sometimes only an email, a cleanup step that resolves emails to customer ids once makes every later query simple.

sql
CREATE TABLE c (id INTEGER PRIMARY KEY, email TEXT);
CREATE TABLE o (id INTEGER PRIMARY KEY, customer_id INTEGER, email TEXT);
CREATE INDEX c_email ON c(email);
EXPLAIN QUERY PLAN SELECT o.id, c.id FROM o JOIN c ON o.customer_id = c.id OR o.email = c.email;

EXPLAIN QUERY PLAN
SELECT o.id, c.id FROM o JOIN c ON o.customer_id = c.id
UNION
SELECT o.id, c.id FROM o JOIN c ON o.email = c.email;

DROP INDEX c_email;
EXPLAIN QUERY PLAN SELECT o.id AS oid, c.id AS cid FROM o JOIN c ON o.customer_id = c.id OR o.email = c.email;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • OR across different columns rules out hash joins on one key
  • Split into one join per key and UNION them
  • SQLite MULTI-INDEX OR needs an index on every branch
  • Fix inconsistent keys at the source when possible

Common mistakes

  • Accepting nested-loop scans for OR joins
  • Using UNION ALL and double-counting pairs that match both ways

Follow-ups

  • How would you resolve emails to ids permanently?
  • When can an engine use a multi-index OR here?

Tips

  • Compare the two plans
291.sql-0291Easyfresher

Write a query that shows each employee next to the name of the highest-paid person in their department.

Use FIRST_VALUE(name) OVER (PARTITION BY dept_id ORDER BY salary DESC, name). The frame always starts at the first row of the partition, so the default frame is fine for FIRST_VALUE. Add a tie-breaker so the result is deterministic when two people share the top salary.

Full answer
sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT name, dept_id, salary,
       FIRST_VALUE(name) OVER (PARTITION BY dept_id ORDER BY salary DESC, name) AS top_earner
FROM employees WHERE dept_id IS NOT NULL
ORDER BY dept_id, salary DESC, name;
namedept_idsalarytop_earner
Asha1120000Asha
Mei195000Asha
Ravi195000Asha
Tom270000Tom
Sara262000Tom
Diego355000Diego
Omar348000Diego

Every Engineering row shows Asha, every Sales row Tom and every Support row Diego. Unlike LAST_VALUE, FIRST_VALUE does not need a frame clause, because the default frame starts at the partition's first row.

A join to a per-department MAX would also work, but it returns two rows per employee if two people tie for the top salary. The window version with a tie-breaker always returns exactly one name.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT name, dept_id, salary,
       FIRST_VALUE(name) OVER (PARTITION BY dept_id ORDER BY salary DESC, name) AS top_earner
FROM employees WHERE dept_id IS NOT NULL
ORDER BY dept_id, salary DESC, name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • FIRST_VALUE returns the first row's value in window order
  • The default frame is fine for FIRST_VALUE
  • Add a tie-breaker for deterministic results
  • Joining to MAX can duplicate rows on ties

Common mistakes

  • Using LAST_VALUE with the default frame for the same task
  • Leaving ties unresolved

Follow-ups

  • How would you show the lowest-paid person too?
  • How would you show the gap to the top salary?

Tips

  • Contrast with LAST_VALUE
292.sql-0292Mediummid

Write a centered 3-day average that uses the day before, the day itself and the day after.

Use AVG(amount) OVER (ORDER BY day ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING). The first and last rows average only two values, because one neighbour is missing. As with trailing averages, ROWS counts rows, not calendar days.

Full answer
sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
SELECT day, amount,
       ROUND(AVG(amount) OVER w, 1) AS centered_avg,
       COUNT(*) OVER w AS rows_in_frame
FROM daily_sales
WINDOW w AS (ORDER BY day ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
ORDER BY day;
dayamountcentered_avgrows_in_frame
2026-03-01120100.02
2026-03-0280116.73
2026-03-03150106.73
2026-03-0590100.03
2026-03-0660116.73
2026-03-09200130.02

The frame reaches one row back and one row forward. The first row has no predecessor and the last no successor, so their windows hold two rows. Counting rows in the same frame shows that directly.

Centered averages smooth a series without shifting peaks in time, which suits charts. They cannot be computed for the latest day until the next day's data arrives, so live dashboards usually prefer trailing windows.

sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

SELECT day, amount,
       ROUND(AVG(amount) OVER w, 1) AS centered_avg,
       COUNT(*) OVER w AS rows_in_frame
FROM daily_sales
WINDOW w AS (ORDER BY day ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
ORDER BY day;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING centers the window
  • Edge rows have smaller windows
  • Centered windows need future data
  • ROWS counts rows, not days

Common mistakes

  • Using a centered window on live data and seeing the last value change
  • Forgetting that missing days distort row-based windows

Follow-ups

  • How would you hide averages with fewer than 3 values?
  • When is a trailing window better?

Tips

  • Show the frame size per row
293.sql-0293Hardsenior

How does a GROUPS frame differ from ROWS when the ORDER BY column has duplicates?

ROWS BETWEEN 1 PRECEDING AND CURRENT ROW counts physical rows, so it may include only part of a group of equal values. GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW counts peer groups, so it includes the whole current group and the whole previous group. SQLite 3.28+ and PostgreSQL 11+ support GROUPS.

Full answer
sql
WITH t(id, day, amount) AS (VALUES (1, 1, 10), (2, 2, 5), (3, 2, 7), (4, 3, 1))
SELECT id, day, amount,
       SUM(amount) OVER (ORDER BY day, id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rows_sum,
       SUM(amount) OVER (ORDER BY day GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS groups_sum
FROM t ORDER BY id;
iddayamountrows_sumgroups_sum
11101010
2251522
3271222
431813

Day 2 has two rows. With ROWS, the second day-2 row sums itself and the row just before it (the other day-2 row). With GROUPS, every day-2 row sums all of day 2 plus all of day 1, because the frame is measured in groups of equal day values.

GROUPS is the natural choice for "this day and the previous day" when days can have several rows and every day is present. If days can be missing, use RANGE with a numeric offset on a day number instead, since GROUPS also ignores gaps.

sql
WITH t(id, day, amount) AS (VALUES (1, 1, 10), (2, 2, 5), (3, 2, 7), (4, 3, 1))
SELECT id, day, amount,
       SUM(amount) OVER (ORDER BY day, id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rows_sum,
       SUM(amount) OVER (ORDER BY day GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS groups_sum
FROM t ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • ROWS counts physical rows
  • GROUPS counts peer groups of equal ORDER BY values
  • GROUPS includes whole groups at each end
  • Supported in SQLite 3.28+ and PostgreSQL 11+

Common mistakes

  • Using ROWS for per-day windows when days have several rows
  • Assuming GROUPS skips missing days correctly

Follow-ups

  • How would RANGE BETWEEN 1 PRECEDING work here?
  • What does EXCLUDE TIES do?

Tips

  • Point to a duplicate-day row
294.sql-0294Hardsenior

How can a window compare each employee's salary with the average of their colleagues, excluding themselves?

Use a full-partition frame with EXCLUDE CURRENT ROW: AVG(salary) OVER (PARTITION BY dept_id ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING EXCLUDE CURRENT ROW). SQLite 3.28+ and PostgreSQL 11+ support EXCLUDE. The arithmetic alternative is (SUM - salary) / (COUNT - 1).

Full answer
sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT name, dept_id, salary,
       AVG(salary) OVER (PARTITION BY dept_id ORDER BY id
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING EXCLUDE CURRENT ROW) AS peers_avg
FROM employees WHERE dept_id IS NOT NULL ORDER BY dept_id, id;
namedept_idsalarypeers_avg
Asha112000095000.0
Ravi195000107500.0
Mei195000107500.0
Tom27000062000.0
Sara26200070000.0
Diego35500048000.0
Omar34800055000.0

For Asha, the colleagues' average is the mean of Ravi and Mei, 95000. For Tom, it is Sara's 62000 alone. EXCLUDE CURRENT ROW removes only the current row from the frame; EXCLUDE TIES would also remove peers with equal ORDER BY values, and EXCLUDE GROUP both.

The arithmetic form works on any engine with window aggregates:

sql
SELECT name, salary,
       CASE WHEN COUNT(*) OVER (PARTITION BY dept_id) > 1
            THEN (SUM(salary) OVER (PARTITION BY dept_id) - salary) * 1.0 / (COUNT(*) OVER (PARTITION BY dept_id) - 1) END AS peers_avg
FROM employees WHERE dept_id IS NOT NULL ORDER BY dept_id, id;
namesalarypeers_avg
Asha12000095000.0
Ravi95000107500.0
Mei95000107500.0
Tom7000062000.0
Sara6200070000.0
Diego5500048000.0
Omar4800055000.0

The CASE avoids dividing by zero for a department of one, which would have no colleagues.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT name, dept_id, salary,
       AVG(salary) OVER (PARTITION BY dept_id ORDER BY id
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING EXCLUDE CURRENT ROW) AS peers_avg
FROM employees WHERE dept_id IS NOT NULL ORDER BY dept_id, id;

SELECT name, salary,
       CASE WHEN COUNT(*) OVER (PARTITION BY dept_id) > 1
            THEN (SUM(salary) OVER (PARTITION BY dept_id) - salary) * 1.0 / (COUNT(*) OVER (PARTITION BY dept_id) - 1) END AS peers_avg
FROM employees WHERE dept_id IS NOT NULL ORDER BY dept_id, id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • EXCLUDE CURRENT ROW drops the current row from the frame
  • Needs an explicit frame such as the whole partition
  • (SUM - x) / (COUNT - 1) is a portable alternative
  • Guard single-member partitions

Common mistakes

  • Comparing with an average that includes the person themselves
  • Dividing by COUNT - 1 when the count is 1

Follow-ups

  • What do EXCLUDE TIES and EXCLUDE GROUP do?
  • How would you flag people more than 10 percent above peers?

Tips

  • Mention the single-member edge case
295.sql-0295Mediummid

What does NTH_VALUE(salary, 2) OVER (ORDER BY salary DESC) return on the first row, and how do you get the second-highest salary on every row?

On the first row it returns NULL, because the default frame ends at the current row and holds only one row. Extend the frame to UNBOUNDED FOLLOWING so every row sees the whole ordered set. NTH_VALUE counts rows, so tied salaries count separately.

Full answer
sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT name, salary, NTH_VALUE(salary, 2) OVER (ORDER BY salary DESC, name) AS second
FROM employees WHERE salary IS NOT NULL ORDER BY salary DESC, name LIMIT 3;
namesalarysecond
Asha120000NULL
Mei9500095000
Ravi9500095000

With the default frame, the first row's frame contains only Asha, so there is no second value. From the second row on, the frame includes Mei or Ravi, so 95000 appears.

sql
SELECT name, salary,
       NTH_VALUE(salary, 2) OVER (ORDER BY salary DESC, name ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second
FROM employees WHERE salary IS NOT NULL ORDER BY salary DESC, name LIMIT 3;
namesalarysecond
Asha12000095000
Mei9500095000
Ravi9500095000

With the full frame, every row shows 95000. Because NTH_VALUE counts rows, the third value is also 95000 (the other tied employee). For the second distinct salary, use DENSE_RANK instead.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT name, salary, NTH_VALUE(salary, 2) OVER (ORDER BY salary DESC, name) AS second
FROM employees WHERE salary IS NOT NULL ORDER BY salary DESC, name LIMIT 3;

SELECT name, salary,
       NTH_VALUE(salary, 2) OVER (ORDER BY salary DESC, name ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second
FROM employees WHERE salary IS NOT NULL ORDER BY salary DESC, name LIMIT 3;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • NTH_VALUE(x, n) returns the n-th row's value in the frame
  • The default frame makes early rows return NULL
  • Extend the frame to the whole partition
  • Ties count as separate rows

Common mistakes

  • Expecting NTH_VALUE to skip duplicates
  • Forgetting the frame and getting NULL on top rows

Follow-ups

  • How would you get the second distinct salary?
  • Does NTH_VALUE support FROM LAST in SQLite?

Tips

  • Explain the frame before the fix
296.sql-0296Mediummid

Write a query that flags each day on which sales reached a new record high.

Compare each amount with the running maximum of all earlier days: MAX(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING). A day is a record when its amount is greater than that, or when there is no earlier day. Excluding the current row from the frame is what makes the comparison meaningful.

Full answer
sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
SELECT day, amount, prev_max,
       CASE WHEN prev_max IS NULL OR amount > prev_max THEN 'record' END AS flag
FROM (
  SELECT day, amount,
         MAX(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prev_max
  FROM daily_sales
) ORDER BY day;
dayamountprev_maxflag
2026-03-01120NULLrecord
2026-03-0280120NULL
2026-03-03150120record
2026-03-0590150NULL
2026-03-0660150NULL
2026-03-09200150record

The first day is a record by definition, because the previous maximum is NULL. 3 March beats 120 and 9 March beats 150; the days in between are below the earlier peak.

A running maximum that includes the current row (... AND CURRENT ROW) would always be at least the current amount, so "amount > running max" could never be true. Ending the frame at 1 PRECEDING is the key.

sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

SELECT day, amount, prev_max,
       CASE WHEN prev_max IS NULL OR amount > prev_max THEN 'record' END AS flag
FROM (
  SELECT day, amount,
         MAX(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prev_max
  FROM daily_sales
) ORDER BY day;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Running MAX over earlier rows tracks the previous record
  • End the frame at 1 PRECEDING
  • Treat the first row explicitly
  • Ties with the previous record are not new records

Common mistakes

  • Including the current row in the running max
  • Forgetting the first row's NULL

Follow-ups

  • How would you count records per month?
  • How would you find the longest period without a new record?

Tips

  • Explain why the frame stops before the current row
297.sql-0297Easyfresher

Show each day's sales as a percentage change from the first day of the series.

Divide by FIRST_VALUE(amount) OVER (ORDER BY day) and subtract 1: 100.0 * (amount - first) / first. This indexes the series to its starting point, which makes several series comparable on one chart. Partition by series key to give each its own baseline.

Full answer
sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
SELECT day, amount,
       ROUND(100.0 * (amount - FIRST_VALUE(amount) OVER (ORDER BY day)) / NULLIF(FIRST_VALUE(amount) OVER (ORDER BY day), 0), 1) AS pct_vs_first
FROM daily_sales ORDER BY day;
dayamountpct_vs_first
2026-03-011200.0
2026-03-0280-33.3
2026-03-0315025.0
2026-03-0590-25.0
2026-03-0660-50.0
2026-03-0920066.7

Every row is compared with 1 March's 120. A value of -33.3 means a third below the starting level; 66.7 means two thirds above.

For several stores, PARTITION BY store_id gives each store its own first day as the baseline. Guard against a zero baseline with NULLIF, or the division will fail on PostgreSQL and return NULL on SQLite.

sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

SELECT day, amount,
       ROUND(100.0 * (amount - FIRST_VALUE(amount) OVER (ORDER BY day)) / NULLIF(FIRST_VALUE(amount) OVER (ORDER BY day), 0), 1) AS pct_vs_first
FROM daily_sales ORDER BY day;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • FIRST_VALUE gives the baseline
  • Percentage change = (value - baseline) / baseline
  • Partition to give each series its own baseline
  • Guard a zero baseline with NULLIF

Common mistakes

  • Integer division producing 0
  • Using the global first value for every store

Follow-ups

  • How would you index to a fixed date instead of the first row?
  • How would you chart several stores together?

Tips

  • Mention the partitioned version
298.sql-0298Hardsenior

How can a RANGE frame with a numeric offset count events in the last 7 days, even when some days are missing?

Order the window by a numeric day value, such as julianday(day), and use RANGE BETWEEN 6 PRECEDING AND CURRENT ROW. RANGE offsets are measured in the ORDER BY value, so the frame covers seven calendar days whether or not every day has a row. PostgreSQL also accepts interval offsets on date columns.

Full answer
sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
SELECT day, amount,
       SUM(amount) OVER (ORDER BY julianday(day) RANGE BETWEEN 6 PRECEDING AND CURRENT ROW) AS last_7_days,
       SUM(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS last_7_rows
FROM daily_sales ORDER BY day;
dayamountlast_7_dayslast_7_rows
2026-03-01120120120
2026-03-0280200200
2026-03-03150350350
2026-03-0590440440
2026-03-0660500500
2026-03-09200500700

On 9 March, the frame covers 3 to 9 March, so it sums 150, 90, 60 and 200 even though only four of those seven days have rows. A ROWS frame of 6 PRECEDING would instead reach back six rows, to 1 March.

PostgreSQL can use the date type directly:

sql
SELECT day, SUM(amount) OVER (ORDER BY day::date RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS last_7_days
FROM daily_sales ORDER BY day;
daylast_7_days
2026-03-01120
2026-03-02200
2026-03-03350
2026-03-05440
2026-03-06500
2026-03-09500

RANGE with an offset requires exactly one ORDER BY expression of a numeric or date type. It is the cleanest way to write calendar-based rolling windows without generating a calendar first.

sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

SELECT day, amount,
       SUM(amount) OVER (ORDER BY julianday(day) RANGE BETWEEN 6 PRECEDING AND CURRENT ROW) AS last_7_days,
       SUM(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS last_7_rows
FROM daily_sales ORDER BY day;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • RANGE offsets are measured in ORDER BY values
  • Order by a numeric day value for calendar windows
  • Missing days are handled correctly
  • PostgreSQL supports interval offsets on dates

Common mistakes

  • Using ROWS and calling it a 7-day window
  • Ordering by a text date with a numeric offset

Follow-ups

  • How would you compute a rolling 30-day distinct user count?
  • Why does RANGE need a single ORDER BY expression?

Tips

  • Contrast with ROWS on the same data
299.sql-0299Mediummid

Which day had the biggest increase in sales over the previous day?

Compute the change with amount - LAG(amount) OVER (ORDER BY day) in a subquery, then order by that change descending and take the first row. Exclude the NULL change of the first day, and decide whether 'previous day' means the previous row or the previous calendar day.

Full answer
sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
SELECT day, change FROM (
  SELECT day, amount - LAG(amount) OVER (ORDER BY day) AS change FROM daily_sales
) WHERE change IS NOT NULL
ORDER BY change DESC LIMIT 1;
daychange
2026-03-09140

9 March rose by 140 over the previous row, 6 March. Note that the previous row is three days earlier here, because 7 and 8 March have no sales. If the business means the previous calendar day, fill the calendar with zeros first; then 9 March would compare with a zero on 8 March.

The window cannot be used directly in ORDER BY ... LIMIT with a filter on it, so the subquery computes the change first. SQLite does allow ORDER BY amount - LAG(amount) OVER (...) directly, but filtering out the NULL still needs the subquery.

sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

SELECT day, change FROM (
  SELECT day, amount - LAG(amount) OVER (ORDER BY day) AS change FROM daily_sales
) WHERE change IS NOT NULL
ORDER BY change DESC LIMIT 1;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • LAG gives the previous row's value
  • Compute the change in a subquery, then sort
  • Exclude the first row's NULL change
  • Previous row may not be the previous calendar day

Common mistakes

  • Sorting with NULL changes first
  • Ignoring missing days

Follow-ups

  • How would you find the biggest drop?
  • How would you report the top increase per month?

Tips

  • Mention the missing-day definition
300.sql-0300Mediummid

Can you nest one window function inside another, such as RANK() OVER (ORDER BY SUM(x) OVER (...))?

No. Window functions cannot be nested inside other window functions; both SQLite and PostgreSQL reject it. Compute the inner window in a subquery or CTE, then apply the outer window to its result. Aggregates can appear inside window functions, because GROUP BY runs first.

Full answer
sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT name, RANK() OVER (ORDER BY SUM(salary) OVER (PARTITION BY dept_id) DESC) FROM employees;  -- error on purpose
text
Error: misuse of window function SUM()
sql
SELECT name, RANK() OVER (ORDER BY SUM(salary) OVER (PARTITION BY dept_id) DESC) FROM employees;  -- error on purpose
text
Error: window functions are not allowed in window definitions

Split the steps:

sql
WITH t AS (
  SELECT name, dept_id, SUM(salary) OVER (PARTITION BY dept_id) AS dept_total FROM employees WHERE dept_id IS NOT NULL
)
SELECT name, dept_total, DENSE_RANK() OVER (ORDER BY dept_total DESC) AS dept_rank
FROM t ORDER BY dept_rank, name;
namedept_totaldept_rank
Asha3100001
Mei3100001
Ravi3100001
Sara1320002
Tom1320002
Diego1030003
Omar1030003

The CTE computes each employee's department total; the outer query ranks those totals. This is the same staging pattern used to filter on window results: each window layer gets its own query level.

Contrast with RANK() OVER (ORDER BY SUM(salary)) in a grouped query, which is allowed, because SUM there is an ordinary aggregate evaluated by GROUP BY before any window function runs.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

-- error on purpose
SELECT name, RANK() OVER (ORDER BY SUM(salary) OVER (PARTITION BY dept_id) DESC) FROM employees;

WITH t AS (
  SELECT name, dept_id, SUM(salary) OVER (PARTITION BY dept_id) AS dept_total FROM employees WHERE dept_id IS NOT NULL
)
SELECT name, dept_total, DENSE_RANK() OVER (ORDER BY dept_total DESC) AS dept_rank
FROM t ORDER BY dept_rank, name;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Window functions cannot be nested
  • Use a CTE or subquery for each window layer
  • Aggregates inside windows are allowed with GROUP BY
  • Both SQLite and PostgreSQL reject nesting

Common mistakes

  • Trying to rank a window result in the same SELECT
  • Confusing window nesting with aggregate nesting

Follow-ups

  • How would you rank departments by headcount and salary together?
  • Why is SUM(SUM(x)) OVER () allowed?

Tips

  • Separate the two layers clearly