Questions 101–120 of 501 · 0 of 20 on this page marked learned
101.sql-0101Easyfresher
Does PostgreSQL or SQLite require an alias for a subquery in the FROM clause?
SQLite never required one, and PostgreSQL has not required one since version 16, so SELECT * FROM (SELECT ...) works on both. MySQL and older PostgreSQL versions require an alias. Giving every derived table a short, meaningful alias is good practice anyway, because you need it to qualify columns in joins.
Full answer
A subquery in FROM is called a derived table: its result is used like a table for the rest of the query.
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');
SQLite accepts it without an alias:
sql
SELECT MAX(n) AS biggest_team
FROM (SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id);
biggest_team
3
So does PostgreSQL 17:
sql
SELECT MAX(n) AS biggest_team
FROM (SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id);
biggest_team
3
PostgreSQL 15 and earlier raised "subquery in FROM must have an alias", and MySQL still requires one ("Every derived table must have its own alias"); those come from their documentation and were not run here.
An alias costs nothing and pays off as soon as the derived table is joined, because columns then need a prefix:
sql
SELECT d.name, t.n
FROM departments d
JOIN (SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id) AS t
ON t.dept_id = d.id
ORDER BY t.n DESC, d.name;
name
n
Engineering
3
Sales
2
Support
2
Portable code should always alias derived tables.
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 MAX(n) AS biggest_team
FROM (SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id);
SELECT d.name, t.n
FROM departments d
JOIN (SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id) AS t
ON t.dept_id = d.id
ORDER BY t.n DESC, d.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
A subquery in FROM is a derived table
SQLite and PostgreSQL 16+ allow it without an alias
MySQL and PostgreSQL 15 and earlier require one
Always alias derived tables in portable code
Common mistakes
Writing alias-free derived tables and breaking on MySQL or older PostgreSQL
Using meaningless aliases like t1, t2 in long queries
Follow-ups
When would you use a CTE instead of a derived table?
Can a derived table refer to columns of other tables in the same FROM clause?
Tips
Quote the version boundary for PostgreSQL; it shows you keep up with releases
102.sql-0102Mediummid
Write a query for students who have not taken any 4-credit course.
Use NOT EXISTS with a correlated subquery that joins enrolments to courses and checks credits = 4. A student is returned only when no such enrolment exists, including students with no enrolments at all. It is safe with NULLs, unlike NOT IN.
Full answer
sql
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
city TEXT,
year INTEGER
);
CREATE TABLE courses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
credits INTEGER
);
CREATE TABLE enrolments (
student_id INTEGER REFERENCES students(id),
course_id INTEGER REFERENCES courses(id),
marks INTEGER,
PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
(1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
(3,10,64),(3,20,71),(3,30,80),(5,20,55);
sql
SELECT s.name
FROM students s
WHERE NOT EXISTS (
SELECT 1
FROM enrolments e
JOIN courses c ON c.id = e.course_id
WHERE e.student_id = s.id AND c.credits = 4)
ORDER BY s.name;
name
Dara
The subquery asks, for each student, "is there an enrolment of this student in a 4-credit course?". NOT EXISTS keeps the students for whom the answer is no. Dara has no enrolments, so she qualifies. Ben took Databases, a 4-credit course, so he is excluded, and the same holds for everyone else: every student except Dara has at least one 4-credit course.
Changing the question slightly shows the pattern's flexibility. Students who took no course with fewer than 4 credits:
sql
SELECT s.name
FROM students s
WHERE NOT EXISTS (
SELECT 1
FROM enrolments e
JOIN courses c ON c.id = e.course_id
WHERE e.student_id = s.id AND c.credits < 4)
ORDER BY s.name;
name
Asha
Dara
Eli
The same anti-join written with LEFT JOIN works, but the join must include the credits filter in ON, not WHERE, or it turns into an inner join:
sql
SELECT s.name
FROM students s
LEFT JOIN (enrolments e JOIN courses c ON c.id = e.course_id AND c.credits = 4)
ON e.student_id = s.id
WHERE e.student_id IS NULL
ORDER BY s.name;
name
Dara
sql
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
city TEXT,
year INTEGER
);
CREATE TABLE courses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
credits INTEGER
);
CREATE TABLE enrolments (
student_id INTEGER REFERENCES students(id),
course_id INTEGER REFERENCES courses(id),
marks INTEGER,
PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
(1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
(3,10,64),(3,20,71),(3,30,80),(5,20,55);
SELECT s.name
FROM students s
WHERE NOT EXISTS (
SELECT 1
FROM enrolments e
JOIN courses c ON c.id = e.course_id
WHERE e.student_id = s.id AND c.credits = 4)
ORDER BY s.name;
SELECT s.name
FROM students s
WHERE NOT EXISTS (
SELECT 1
FROM enrolments e
JOIN courses c ON c.id = e.course_id
WHERE e.student_id = s.id AND c.credits < 4)
ORDER BY s.name;
SELECT s.name
FROM students s
LEFT JOIN (enrolments e JOIN courses c ON c.id = e.course_id AND c.credits = 4)
ON e.student_id = s.id
WHERE e.student_id IS NULL
ORDER BY s.name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
NOT EXISTS returns rows with no matching related row
The subquery can join and filter freely
Students with no enrolments at all are included
With a LEFT JOIN version, filters belong in ON
Common mistakes
Using NOT IN on a column that may contain NULL
Putting the credits filter in WHERE in the LEFT JOIN version
Follow-ups
How would you find students who took only 4-credit courses?
Which of these versions is fastest on your database?
Tips
Point out that students with no enrolments count; it is a frequent follow-up
103.sql-0103Easyfresher
What is a common table expression (CTE), and why use one instead of a nested subquery?
A CTE is a named, temporary result defined with WITH name AS (SELECT ...) and used by the query that follows. It lets you build a query in readable steps, reuse the same intermediate result more than once, and write recursive queries. It lasts only for that one statement.
Full answer
A CTE gives a subquery a name and moves it to the top of the statement, so the main query reads like a short story instead of an inside-out puzzle.
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');
"Departments whose total pay is above the average department total", as a chain of named steps:
sql
WITH dept_totals AS (
SELECT dept_id, SUM(salary) AS total
FROM employees
WHERE dept_id IS NOT NULL
GROUP BY dept_id
),
avg_total AS (
SELECT AVG(total) AS avg_t FROM dept_totals
)
SELECT d.name, t.total
FROM dept_totals t
JOIN departments d ON d.id = t.dept_id
WHERE t.total > (SELECT avg_t FROM avg_total)
ORDER BY t.total DESC;
name
total
Engineering
310000
Each step has a name that explains it, and dept_totals is used twice without being written twice. The nested version needs the same derived table copied into two places:
sql
SELECT d.name, t.total
FROM (SELECT dept_id, SUM(salary) AS total FROM employees
WHERE dept_id IS NOT NULL GROUP BY dept_id) t
JOIN departments d ON d.id = t.dept_id
WHERE t.total > (SELECT AVG(total)
FROM (SELECT dept_id, SUM(salary) AS total FROM employees
WHERE dept_id IS NOT NULL GROUP BY dept_id))
ORDER BY t.total DESC;
name
total
Engineering
310000
Both return Engineering. The CTE version is easier to review and to change.
A CTE is not stored anywhere; it exists for one statement. Whether the engine computes it once or inlines it into the main query is an optimizer decision. PostgreSQL 12 and later usually inline a CTE that is referenced once, and you can force either behaviour with AS MATERIALIZED or AS NOT MATERIALIZED.
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');
WITH dept_totals AS (
SELECT dept_id, SUM(salary) AS total
FROM employees
WHERE dept_id IS NOT NULL
GROUP BY dept_id
),
avg_total AS (
SELECT AVG(total) AS avg_t FROM dept_totals
)
SELECT d.name, t.total
FROM dept_totals t
JOIN departments d ON d.id = t.dept_id
WHERE t.total > (SELECT avg_t FROM avg_total)
ORDER BY t.total DESC;
SELECT d.name, t.total
FROM (SELECT dept_id, SUM(salary) AS total FROM employees
WHERE dept_id IS NOT NULL GROUP BY dept_id) t
JOIN departments d ON d.id = t.dept_id
WHERE t.total > (SELECT AVG(total)
FROM (SELECT dept_id, SUM(salary) AS total FROM employees
WHERE dept_id IS NOT NULL GROUP BY dept_id))
ORDER BY t.total DESC;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
WITH name AS (...) defines a named result for one statement
CTEs make multi-step logic readable and reusable within the query
They enable recursive queries
The optimizer may inline or materialize them
Common mistakes
Assuming a CTE is a temporary table that persists after the statement
Assuming a CTE is always computed only once
Follow-ups
When would you choose a temporary table over a CTE?
What does AS MATERIALIZED change in PostgreSQL?
Tips
Name each CTE after what it contains, like dept_totals, not t1
104.sql-0104Mediummid
How does a recursive CTE work? Use it to generate the numbers 1 to 5.
A recursive CTE has an anchor query that produces the starting rows, then UNION ALL, then a recursive query that refers to the CTE itself and produces new rows from the previous step. The engine repeats the recursive part until it returns no rows. A WHERE condition in the recursive part is what stops it.
Full answer
sql
WITH RECURSIVE counter(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n FROM counter;
n
1
2
3
4
5
How the engine runs it:
Run the anchor, SELECT 1. The working set is {1}.
Run the recursive part using only the rows from the last step: from 1 it produces 2.
Repeat with {2}, then {3}, {4}. From 5 the condition n < 5 fails, so the step returns no rows.
Stop, and return everything produced: 1 to 5.
The WHERE n < 5 is the stopping condition. Without it the query never ends; SQLite would keep going until it ran out of memory or hit a LIMIT. A LIMIT on the outer query is a useful safety net while experimenting:
sql
WITH RECURSIVE forever(n) AS (
SELECT 1 UNION ALL SELECT n + 1 FROM forever
)
SELECT n FROM forever LIMIT 3;
n
1
2
3
The same counter pattern generates dates, which is the everyday use: a calendar of days to LEFT JOIN facts onto.
sql
WITH RECURSIVE days(d) AS (
SELECT '2026-03-01'
UNION ALL
SELECT date(d, '+1 day') FROM days WHERE d < '2026-03-05'
)
SELECT d FROM days;
d
2026-03-01
2026-03-02
2026-03-03
2026-03-04
2026-03-05
PostgreSQL requires the keyword WITH RECURSIVE. SQLite accepts plain WITH too, but writing RECURSIVE keeps the query portable.
sql
WITH RECURSIVE counter(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n FROM counter;
WITH RECURSIVE forever(n) AS (
SELECT 1 UNION ALL SELECT n + 1 FROM forever
)
SELECT n FROM forever LIMIT 3;
WITH RECURSIVE days(d) AS (
SELECT '2026-03-01'
UNION ALL
SELECT date(d, '+1 day') FROM days WHERE d < '2026-03-05'
)
SELECT d FROM days;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Anchor query, UNION ALL, recursive query referring to the CTE
Each step uses only the rows produced by the previous step
Recursion stops when a step returns no rows
Always include a stopping condition; LIMIT is a safety net
Common mistakes
Forgetting the stopping condition
Using UNION and relying on it to stop cycles, which only works if rows repeat exactly
Follow-ups
How would you generate every month of 2026?
How do you stop a recursive CTE that walks a graph with cycles?
Tips
Describe the iteration step by step; interviewers want to see the mental model
105.sql-0105Mediummid
Write a recursive query that lists every employee under a given manager, with their level in the hierarchy.
Anchor on the manager's direct reports (manager_id = the manager's id) with level 1, then repeatedly join employees to the rows found so far on employees.manager_id = previous.id, adding 1 to the level. Stop when no new reports are found. This walks an adjacency-list tree of any depth.
Full answer
An adjacency list stores each employee's manager in the same table. A self join finds one level; a recursive CTE finds all levels.
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');
Everyone under Asha (id 1):
sql
WITH RECURSIVE reports(id, name, manager_id, level) AS (
SELECT id, name, manager_id, 1 FROM employees WHERE manager_id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id, r.level + 1
FROM employees e
JOIN reports r ON e.manager_id = r.id
)
SELECT name, level FROM reports ORDER BY level, name;
name
level
Diego
1
Mei
1
Ravi
1
Tom
1
Lena
2
Omar
2
Sara
2
Asha's direct reports are level 1. Sara and Lena report to Tom, and Omar reports to Diego, so those three are level 2. The query would keep going for deeper trees with no changes.
Carrying a path string shows the chain and is handy for sorting the tree into display order:
sql
WITH RECURSIVE tree(id, name, path) AS (
SELECT id, name, name FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, t.path || ' > ' || e.name
FROM employees e JOIN tree t ON e.manager_id = t.id
)
SELECT path FROM tree ORDER BY path;
path
Asha
Asha > Diego
Asha > Diego > Omar
Asha > Mei
Asha > Ravi
Asha > Tom
Asha > Tom > Lena
Asha > Tom > Sara
Two cautions. If the data accidentally contains a cycle (A manages B, B manages A), the recursion never ends; guard with a depth limit such as WHERE level < 20, or with a path check that stops when an id is already in the path. And on large hierarchies, an index on manager_id keeps each step a quick lookup.
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');
WITH RECURSIVE reports(id, name, manager_id, level) AS (
SELECT id, name, manager_id, 1 FROM employees WHERE manager_id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id, r.level + 1
FROM employees e
JOIN reports r ON e.manager_id = r.id
)
SELECT name, level FROM reports ORDER BY level, name;
WITH RECURSIVE tree(id, name, path) AS (
SELECT id, name, name FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, t.path || ' > ' || e.name
FROM employees e JOIN tree t ON e.manager_id = t.id
)
SELECT path FROM tree ORDER BY path;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Anchor: direct reports of the starting manager
Recursive step: join employees to the previous level on manager_id
Carry level and path columns for depth and display order
Guard against cycles with a depth limit or path check
Common mistakes
Writing one self join per level and missing deeper levels
Recursing without a cycle guard on data that is not guaranteed to be a tree
Follow-ups
How would you find the chain of managers above Omar?
How would you count everyone under each manager?
Tips
Mention cycles; it shows you have dealt with dirty hierarchy data
106.sql-0106Mediummid
Write a query that returns the full chain of managers above a given employee, from the employee up to the top.
Walk the tree upward: anchor on the employee's own row, then repeatedly join to employees on employees.id = previous.manager_id. The recursion stops at the top, where manager_id is NULL and the join finds nothing. Carry a step counter to keep the order.
Full answer
Going up a tree is the mirror of going down. Instead of finding rows whose manager is the current row, find the row that is the current row's manager.
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');
The chain above Omar:
sql
WITH RECURSIVE chain(id, name, manager_id, step) AS (
SELECT id, name, manager_id, 0 FROM employees WHERE name = 'Omar'
UNION ALL
SELECT m.id, m.name, m.manager_id, c.step + 1
FROM employees m
JOIN chain c ON m.id = c.manager_id
)
SELECT step, name FROM chain ORDER BY step;
step
name
0
Omar
1
Diego
2
Asha
Omar reports to Diego, who reports to Asha. At Asha, manager_id is NULL, the join returns no row, and the recursion ends by itself, so this direction needs no explicit stop condition as long as the data has no cycles.
A compact one-line answer for display:
sql
WITH RECURSIVE chain(id, name, manager_id, step) AS (
SELECT id, name, manager_id, 0 FROM employees WHERE name = 'Omar'
UNION ALL
SELECT m.id, m.name, m.manager_id, c.step + 1
FROM employees m JOIN chain c ON m.id = c.manager_id
)
SELECT GROUP_CONCAT(name, ' > ' ORDER BY step) AS chain FROM chain;
chain
Omar > Diego > Asha
The ORDER BY inside the derived table controls the order of names in the chain. SQLite documents that group_concat follows the order of its input rows in this simple form, but the portable way is the aggregate ORDER BY clause (string_agg(name, ' > ' ORDER BY step) in PostgreSQL, also accepted by SQLite 3.44+).
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');
WITH RECURSIVE chain(id, name, manager_id, step) AS (
SELECT id, name, manager_id, 0 FROM employees WHERE name = 'Omar'
UNION ALL
SELECT m.id, m.name, m.manager_id, c.step + 1
FROM employees m
JOIN chain c ON m.id = c.manager_id
)
SELECT step, name FROM chain ORDER BY step;
WITH RECURSIVE chain(id, name, manager_id, step) AS (
SELECT id, name, manager_id, 0 FROM employees WHERE name = 'Omar'
UNION ALL
SELECT m.id, m.name, m.manager_id, c.step + 1
FROM employees m JOIN chain c ON m.id = c.manager_id
)
SELECT GROUP_CONCAT(name, ' > ' ORDER BY step) AS chain FROM chain;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Walking up: join on employees.id = previous.manager_id
Stops naturally at the root where manager_id is NULL
Carry a step number to preserve order
Use an ordered aggregate to build a readable chain
Common mistakes
Reversing the join condition and walking down instead of up
Relying on unordered string aggregation for the chain
Follow-ups
How would you find the lowest common manager of two employees?
How would you store a hierarchy so ancestor queries need no recursion?
Tips
Contrast walking up with walking down in one sentence
107.sql-0107Mediummid
How do you list every day in a date range, including days with no sales, with a sales total for each?
Generate the days with a recursive CTE (or generate_series in PostgreSQL), then LEFT JOIN the sales onto the calendar and use COALESCE to show 0 where nothing was sold. Grouping the sales table alone can never produce rows for days that have no sales.
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);
The sales table has gaps on 4, 7 and 8 March. Grouping it directly shows only days with data. A generated calendar fills the gaps:
sql
WITH RECURSIVE days(day) AS (
SELECT '2026-03-01'
UNION ALL
SELECT date(day, '+1 day') FROM days WHERE day < '2026-03-09'
)
SELECT d.day, COALESCE(s.amount, 0) AS amount
FROM days d
LEFT JOIN daily_sales s ON s.day = d.day
ORDER BY d.day;
day
amount
2026-03-01
120
2026-03-02
80
2026-03-03
150
2026-03-04
0
2026-03-05
90
2026-03-06
60
2026-03-07
0
2026-03-08
0
2026-03-09
200
The calendar drives the query, so every day appears. COALESCE turns the missing totals into 0 for the chart.
PostgreSQL has generate_series, which replaces the recursive CTE:
sql
SELECT d::date AS day, COALESCE(s.amount, 0) AS amount
FROM generate_series(DATE '2026-03-01', DATE '2026-03-09', INTERVAL '1 day') AS d
LEFT JOIN daily_sales s ON s.day = d::date
ORDER BY day;
day
amount
2026-03-01
120
2026-03-02
80
2026-03-03
150
2026-03-04
0
2026-03-05
90
2026-03-06
60
2026-03-07
0
2026-03-08
0
2026-03-09
200
Many teams keep a permanent calendar table (one row per date, with columns such as weekday, month and holiday flag) instead of generating dates in every query. It is easy to index, easy to join, and makes questions such as "sales per working day" simple.
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);
WITH RECURSIVE days(day) AS (
SELECT '2026-03-01'
UNION ALL
SELECT date(day, '+1 day') FROM days WHERE day < '2026-03-09'
)
SELECT d.day, COALESCE(s.amount, 0) AS amount
FROM days d
LEFT JOIN daily_sales s ON s.day = d.day
ORDER BY d.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
Generate the full list of dates first
LEFT JOIN the facts onto the calendar
COALESCE missing totals to 0 when zero is meaningful
generate_series in PostgreSQL; a calendar table for reuse
Common mistakes
Grouping the fact table and expecting missing days to appear
Inner joining to the calendar and losing the empty days again
Follow-ups
How would you show every week instead of every day?
What columns would you put in a calendar table?
Tips
Explain why the calendar must be on the left side of the join
108.sql-0108Mediummid
Can a CTE be used with INSERT, UPDATE or DELETE?
Yes. In SQLite and PostgreSQL a WITH clause can precede INSERT, UPDATE and DELETE, so the change can use a named intermediate result. PostgreSQL also allows data-modifying statements inside the CTE itself, with RETURNING, which lets one statement move rows between tables. SQLite does not allow DML inside a CTE.
Full answer
A CTE in front of a data change keeps the logic readable, for example "give a 5 percent raise to everyone below their department's average".
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');
CREATE TABLE orders (id INTEGER PRIMARY KEY, status TEXT);
CREATE TABLE orders_archive (id INTEGER PRIMARY KEY, status TEXT);
INSERT INTO orders VALUES (1,'shipped'),(2,'cancelled'),(3,'cancelled');
sql
WITH dept_avg AS (
SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id
)
UPDATE employees
SET salary = CAST(salary * 1.05 AS INTEGER)
WHERE salary < (SELECT avg_sal FROM dept_avg WHERE dept_avg.dept_id = employees.dept_id);
SELECT name, salary FROM employees ORDER BY id;
name
salary
Asha
120000
Ravi
99750
Mei
99750
Tom
70000
Sara
65100
Diego
55000
Lena
NULL
Omar
50400
The CTE computes the averages, and the UPDATE uses them. Ravi, Mei, Sara and Omar were below their department averages and got the raise.
PostgreSQL goes further: the CTE itself can change data, and RETURNING passes the changed rows on. This archives and deletes cancelled orders in one statement:
sql
WITH moved AS (
DELETE FROM orders WHERE status = 'cancelled' RETURNING id, status
)
INSERT INTO orders_archive SELECT id, status FROM moved;
SELECT (SELECT COUNT(*) FROM orders) AS left_in_orders,
(SELECT COUNT(*) FROM orders_archive) AS archived;
left_in_orders
archived
1
2
SQLite does not accept a DELETE inside a WITH clause:
sql
WITH moved AS (DELETE FROM orders WHERE status = 'cancelled' RETURNING id)
SELECT * FROM moved;
-- error on purpose
text
Error: near "DELETE": syntax error
In SQLite, the same job takes two statements in one transaction: INSERT INTO the archive with a SELECT, then DELETE.
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');
CREATE TABLE orders (id INTEGER PRIMARY KEY, status TEXT);
CREATE TABLE orders_archive (id INTEGER PRIMARY KEY, status TEXT);
INSERT INTO orders VALUES (1,'shipped'),(2,'cancelled'),(3,'cancelled');
WITH dept_avg AS (
SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id
)
UPDATE employees
SET salary = CAST(salary * 1.05 AS INTEGER)
WHERE salary < (SELECT avg_sal FROM dept_avg WHERE dept_avg.dept_id = employees.dept_id);
SELECT name, salary FROM employees ORDER BY id;
-- error on purpose
WITH moved AS (DELETE FROM orders WHERE status = 'cancelled' RETURNING id)
SELECT * FROM moved;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
WITH can precede INSERT, UPDATE and DELETE
The CTE supplies a named intermediate result to the change
PostgreSQL allows DML inside CTEs with RETURNING
SQLite needs separate statements in a transaction for the same effect
Common mistakes
Computing averages after some rows have already been updated, in a multi-step script
Assuming DML-in-CTE syntax works on SQLite
Follow-ups
How would you preview which rows the UPDATE will change?
Why is the data-modifying CTE in PostgreSQL atomic?
Tips
Preview the affected rows with the same CTE and a SELECT before running the UPDATE
109.sql-0109Hardsenior
In PostgreSQL, what is the difference between a materialized and an inlined CTE, and when does it matter?
A materialized CTE is computed once and stored as a temporary result; the main query reads that result and filters cannot be pushed into it. An inlined CTE is merged into the main query like a subquery, so the planner can push filters down and use indexes. Since PostgreSQL 12, a side-effect-free CTE referenced once is inlined by default, and AS MATERIALIZED or AS NOT MATERIALIZED overrides the choice.
Full answer
Before PostgreSQL 12, every CTE was an "optimization fence": it was computed in full and the outer WHERE could not reach inside. Teams sometimes used that on purpose to control plans, and sometimes suffered from it when a CTE scanned a whole table only for the outer query to keep one row.
From version 12 the default changed. A CTE that is referenced once and has no side effects is inlined. You can see the difference in the plans:
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
EXPLAIN (COSTS OFF)
WITH e AS (SELECT * FROM employees)
SELECT name FROM e WHERE dept_id = 1;
text
Seq Scan on employees
Filter: (dept_id = 1)
sql
EXPLAIN (COSTS OFF)
WITH e AS MATERIALIZED (SELECT * FROM employees)
SELECT name FROM e WHERE dept_id = 1;
text
CTE Scan on e
Filter: (dept_id = 1)
CTE e
-> Seq Scan on employees
The inlined plan applies the dept_id = 1 filter directly to the scan of employees. The materialized plan builds the full CTE result first (the CTE Scan over all departments' rows) and filters afterwards.
When materializing helps: the CTE is expensive and referenced several times (it is then computed once by default), or you need to stop the planner from choosing a bad plan that it keeps picking. When it hurts: a broad CTE followed by a selective outer filter, as above.
SQLite also decides per query whether to materialize or inline (it calls the latter "query flattening"), and accepts the same MATERIALIZED hints since 3.35.
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');
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Materialized: computed once, outer filters cannot be pushed in
Inlined: merged into the main query, filters and indexes can be used
PostgreSQL 12+ inlines single-reference, side-effect-free CTEs by default
AS MATERIALIZED and AS NOT MATERIALIZED override the default
Common mistakes
Assuming CTEs are always an optimization fence, which was only true before PostgreSQL 12
Assuming CTEs are always inlined, even when referenced several times
Follow-ups
How would you check which version of a plan PostgreSQL chose?
When would you deliberately add AS MATERIALIZED?
Tips
Quote the version where the default changed
110.sql-0110Hardsenior
Explain the difference between UNION and UNION ALL inside a recursive CTE, and how to stop a traversal from looping on a graph with cycles.
With UNION ALL every produced row is kept, so a cycle in the data makes the recursion run forever. UNION discards rows already produced, which stops a cycle only when the repeated rows are identical; once you carry a depth or path column, rows differ and UNION no longer helps. The reliable guard is to carry the visited path and refuse to revisit a node, or to cap the depth.
Full answer
Graphs, unlike trees, can loop back. A small route map with a cycle A to B to C to A:
With UNION, only the node is carried, so revisiting A produces a row that already exists, and UNION drops it. The recursion ends:
sql
WITH RECURSIVE reach(node) AS (
SELECT 'A'
UNION
SELECT r.dst FROM routes r JOIN reach ON r.src = reach.node
)
SELECT node FROM reach ORDER BY node;
node
A
B
C
D
As soon as a depth column is added, the row (A, 3) differs from (A, 0) and UNION no longer prevents the loop. A path column with a visited check is the guard that keeps working:
sql
WITH RECURSIVE walk(node, path, depth) AS (
SELECT 'A', '/A/', 0
UNION ALL
SELECT r.dst, w.path || r.dst || '/', w.depth + 1
FROM routes r JOIN walk w ON r.src = w.node
WHERE instr(w.path, '/' || r.dst || '/') = 0
)
SELECT node, path, depth FROM walk ORDER BY depth, node;
node
path
depth
A
/A/
0
B
/A/B/
1
C
/A/B/C/
2
D
/A/B/D/
2
The instr check (position or strpos in PostgreSQL) refuses to step into a node already on the path. Delimiters around each name avoid false matches such as 'A' inside 'AB'.
PostgreSQL 14 added a built-in CYCLE clause that does this bookkeeping for you:
sql
WITH RECURSIVE walk(node, depth) AS (
SELECT 'A'::text, 0
UNION ALL
SELECT r.dst, w.depth + 1 FROM routes r JOIN walk w ON r.src = w.node
) CYCLE node SET is_cycle USING path
SELECT node, depth, is_cycle FROM walk ORDER BY depth, node;
node
depth
is_cycle
A
0
false
B
1
false
C
2
false
D
2
false
A
3
true
sql
CREATE TABLE routes (src TEXT, dst TEXT);
INSERT INTO routes VALUES ('A','B'),('B','C'),('C','A'),('B','D');
WITH RECURSIVE reach(node) AS (
SELECT 'A'
UNION
SELECT r.dst FROM routes r JOIN reach ON r.src = reach.node
)
SELECT node FROM reach ORDER BY node;
WITH RECURSIVE walk(node, path, depth) AS (
SELECT 'A', '/A/', 0
UNION ALL
SELECT r.dst, w.path || r.dst || '/', w.depth + 1
FROM routes r JOIN walk w ON r.src = w.node
WHERE instr(w.path, '/' || r.dst || '/') = 0
)
SELECT node, path, depth FROM walk ORDER BY depth, node;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
UNION ALL keeps every row; a cycle means infinite recursion
UNION stops repeats only when whole rows are identical
Carry a visited path and skip nodes already on it
PostgreSQL 14+ has a CYCLE clause
Common mistakes
Relying on UNION after adding a depth column
Path checks without delimiters that confuse 'A' and 'AB'
Follow-ups
How would you find the shortest number of hops from A to C?
What does the SEARCH clause in PostgreSQL do?
Tips
Mention that a depth cap is a second safety net
111.sql-0111Hardsenior
Write a query that splits a comma-separated string such as 'sql,joins,cte' into one row per value.
In SQLite, a recursive CTE can peel off one item at a time with instr and substr until the string is empty. PostgreSQL has string_to_table (or unnest(string_to_array(...))) for this. Storing lists in one column is usually a design smell; splitting is mostly needed to clean imported data.
Full answer
SQLite has no built-in split function, so a recursive CTE takes the string apart piece by piece. Each step keeps the first item and passes the rest on:
sql
WITH RECURSIVE parts(item, rest) AS (
SELECT NULL, 'sql,joins,cte' || ','
UNION ALL
SELECT substr(rest, 1, instr(rest, ',') - 1),
substr(rest, instr(rest, ',') + 1)
FROM parts
WHERE rest <> ''
)
SELECT item FROM parts WHERE item IS NOT NULL;
item
sql
joins
cte
How it works: rest always has a trailing comma appended, so instr(rest, ',') finds the end of the next item. substr before the comma is the item; substr after it is what remains. The recursion stops when nothing remains.
PostgreSQL does the same in one function call:
sql
SELECT string_to_table('sql,joins,cte', ',') AS item;
item
sql
joins
cte
SQLite's JSON functions offer another route if the string can be turned into a JSON array:
sql
SELECT value AS item
FROM json_each('["' || replace('sql,joins,cte', ',', '","') || '"]')
ORDER BY key;
item
sql
joins
cte
If a column regularly holds comma-separated values, that usually means a missing child table (one row per tag). Splitting is a one-time repair step on the way to that design, not something to run in every query.
sql
WITH RECURSIVE parts(item, rest) AS (
SELECT NULL, 'sql,joins,cte' || ','
UNION ALL
SELECT substr(rest, 1, instr(rest, ',') - 1),
substr(rest, instr(rest, ',') + 1)
FROM parts
WHERE rest <> ''
)
SELECT item FROM parts WHERE item IS NOT NULL;
SELECT value AS item
FROM json_each('["' || replace('sql,joins,cte', ',', '","') || '"]')
ORDER BY key;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
A recursive CTE can split strings in SQLite
Each step emits one item and passes the remainder
PostgreSQL has string_to_table and string_to_array
Comma-separated columns usually mean a missing child table
Common mistakes
Forgetting the trailing delimiter and losing the last item
Keeping lists in a column and splitting them in every query
Follow-ups
How would you count how many items each row's list contains?
How would you turn the split values into rows of a tags table?
Tips
Recommend the schema fix after showing the split
112.sql-0112Easyfresher
Can one CTE refer to another CTE defined earlier in the same WITH clause? Can it refer to one defined later?
Yes to the first: each CTE in a WITH list can use the ones defined before it. Referring to a CTE defined later is rejected by PostgreSQL, while SQLite resolves the forward reference anyway. Write CTEs in dependency order so the query works everywhere and reads top to bottom.
Full answer
A WITH clause is a list of named steps, read top to bottom. Later steps can build on earlier ones:
sql
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
city TEXT,
year INTEGER
);
CREATE TABLE courses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
credits INTEGER
);
CREATE TABLE enrolments (
student_id INTEGER REFERENCES students(id),
course_id INTEGER REFERENCES courses(id),
marks INTEGER,
PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
(1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
(3,10,64),(3,20,71),(3,30,80),(5,20,55);
sql
WITH scored AS (
SELECT student_id, marks, marks >= 70 AS passed FROM enrolments WHERE marks IS NOT NULL
),
pass_counts AS (
SELECT student_id, SUM(passed) AS passes FROM scored GROUP BY student_id
)
SELECT s.name, p.passes
FROM pass_counts p JOIN students s ON s.id = p.student_id
ORDER BY s.name;
name
passes
Asha
2
Ben
1
Chen
2
Eli
0
pass_counts uses scored, which was defined just before it.
Referring forward is where engines differ. SQLite accepts it and finds b even though it is defined later:
sql
WITH a AS (SELECT * FROM b), b AS (SELECT 1 AS x)
SELECT * FROM a;
x
1
PostgreSQL does not. Without RECURSIVE, a CTE can only see the CTEs listed before it:
sql
WITH a AS (SELECT * FROM b), b AS (SELECT 1 AS x)
SELECT * FROM a;
-- error on purpose
text
Error: relation "b" does not exist
Writing CTEs in dependency order avoids the question entirely, and it keeps WITH clauses readable: each step depends only on what is above it, so a reviewer can check them one at a time.
sql
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
city TEXT,
year INTEGER
);
CREATE TABLE courses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
credits INTEGER
);
CREATE TABLE enrolments (
student_id INTEGER REFERENCES students(id),
course_id INTEGER REFERENCES courses(id),
marks INTEGER,
PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
(1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
(3,10,64),(3,20,71),(3,30,80),(5,20,55);
WITH scored AS (
SELECT student_id, marks, marks >= 70 AS passed FROM enrolments WHERE marks IS NOT NULL
),
pass_counts AS (
SELECT student_id, SUM(passed) AS passes FROM scored GROUP BY student_id
)
SELECT s.name, p.passes
FROM pass_counts p JOIN students s ON s.id = p.student_id
ORDER BY s.name;
WITH a AS (SELECT * FROM b), b AS (SELECT 1 AS x)
SELECT * FROM a;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
CTEs in one WITH list are defined in order
Each CTE can use the CTEs above it
PostgreSQL rejects forward references; SQLite accepts them
Self-reference needs WITH RECURSIVE in PostgreSQL
Common mistakes
Ordering CTEs by importance instead of by dependency
Expecting a CTE from one statement to be visible in the next statement
Follow-ups
Can you define a CTE inside a subquery?
Can two CTEs refer to each other?
Tips
Describe a WITH list as a pipeline of named steps
113.sql-0113Easyfresher
What is a window function, and how is it different from GROUP BY?
A window function computes a value across a set of rows related to the current row, written with OVER (...), but it keeps every row in the output. GROUP BY collapses each group into one row. So AVG(salary) OVER (PARTITION BY dept_id) can show each employee next to their department's average, which GROUP BY alone cannot.
Full answer
GROUP BY answers "one row per department". A window function answers "every employee, plus something about their department".
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');
With GROUP BY, the individual employees disappear:
sql
SELECT dept_id, ROUND(AVG(salary), 0) AS dept_avg
FROM employees GROUP BY dept_id ORDER BY dept_id;
dept_id
dept_avg
NULL
NULL
1
103333.0
2
66000.0
3
51500.0
With a window, each employee stays and gets the department figures alongside:
sql
SELECT name, dept_id, salary,
ROUND(AVG(salary) OVER (PARTITION BY dept_id), 0) AS dept_avg,
COUNT(*) OVER (PARTITION BY dept_id) AS dept_size
FROM employees
ORDER BY dept_id, salary DESC, name;
name
dept_id
salary
dept_avg
dept_size
Lena
NULL
NULL
NULL
1
Asha
1
120000
103333.0
3
Mei
1
95000
103333.0
3
Ravi
1
95000
103333.0
3
Tom
2
70000
66000.0
2
Sara
2
62000
66000.0
2
Diego
3
55000
51500.0
2
Omar
3
48000
51500.0
2
PARTITION BY dept_id splits rows into groups for the calculation without merging them. An empty OVER () treats the whole result as one partition. Lena has no department, so her partition is the NULL group with only herself in it.
Window functions are evaluated after WHERE, GROUP BY and HAVING, and before ORDER BY and LIMIT. That position explains two rules: you cannot use a window function in WHERE, and you can apply one to the result of a GROUP BY.
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 dept_id, ROUND(AVG(salary), 0) AS dept_avg
FROM employees GROUP BY dept_id ORDER BY dept_id;
SELECT name, dept_id, salary,
ROUND(AVG(salary) OVER (PARTITION BY dept_id), 0) AS dept_avg,
COUNT(*) OVER (PARTITION BY dept_id) AS dept_size
FROM employees
ORDER BY dept_id, salary DESC, name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
OVER (...) makes an aggregate a window function
Window functions keep every input row
PARTITION BY groups rows for the calculation only
They run after GROUP BY and HAVING, before ORDER BY
Common mistakes
Expecting PARTITION BY to reduce the number of rows
Putting a window function in WHERE
Follow-ups
How would you show each employee's salary as a percentage of their department total?
Can you combine GROUP BY and a window function in one query?
Tips
Show the same data with GROUP BY and with OVER side by side
114.sql-0114Easyfresher
Given salaries 120000, 95000, 95000, 70000, what do ROW_NUMBER, RANK and DENSE_RANK return?
ROW_NUMBER gives 1, 2, 3, 4: always unique, with ties broken arbitrarily unless ORDER BY decides. RANK gives 1, 2, 2, 4: ties share a rank and the next rank skips. DENSE_RANK gives 1, 2, 2, 3: ties share a rank and no numbers are skipped.
Full answer
All three number rows in the order given by OVER (ORDER BY ...). They differ only in how they treat ties.
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,
ROW_NUMBER() OVER (ORDER BY salary DESC, name) AS row_num,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees
WHERE salary >= 70000
ORDER BY salary DESC, name;
name
salary
row_num
rnk
dense_rnk
Asha
120000
1
1
1
Mei
95000
2
2
2
Ravi
95000
3
2
2
Tom
70000
4
4
3
ROW_NUMBER never repeats. Ravi and Mei earn the same, so the name tie-breaker in the ORDER BY decides who gets 2 and who gets 3. Without a tie-breaker, the assignment between tied rows is arbitrary.
RANK gives tied rows the same rank and then leaves a gap, like a race result where two runners share second place and the next runner is fourth.
DENSE_RANK gives tied rows the same rank and continues with the next number, so there are no gaps.
Which to use depends on the question. "Exactly one row per group" needs ROW_NUMBER. "Top 3 salaries, including everyone tied" needs DENSE_RANK with <= 3. "Olympic-style position" needs RANK.
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,
ROW_NUMBER() OVER (ORDER BY salary DESC, name) AS row_num,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees
WHERE salary >= 70000
ORDER BY salary DESC, name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
ROW_NUMBER: unique numbers, ties broken by ORDER BY or arbitrarily
RANK: ties share a rank, then a gap
DENSE_RANK: ties share a rank, no gaps
Pick by question: one per group, distinct salary levels, or positions
Common mistakes
Using ROW_NUMBER for 'top N salaries' and silently dropping tied employees
Leaving ROW_NUMBER without a tie-breaker and getting different results across runs
Follow-ups
How would you find the second-highest distinct salary?
What does NTILE(4) do?
Tips
Use a race result to explain RANK's gap
115.sql-0115Easyfresher
Write a query that shows a running total of daily sales.
Use SUM(amount) OVER (ORDER BY day). With an ORDER BY in the window, the default frame runs from the first row up to the current row, so each row shows the total so far. Add PARTITION BY to restart the total per group, such as per store or per month.
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 day) AS running_total
FROM daily_sales
ORDER BY day;
day
amount
running_total
2026-03-01
120
120
2026-03-02
80
200
2026-03-03
150
350
2026-03-05
90
440
2026-03-06
60
500
2026-03-09
200
700
Each row's running_total is the sum of all amounts up to and including that day. The ORDER BY inside OVER defines the order of accumulation; the ORDER BY at the end only decides the display order.
To restart the total each month, partition by month:
sql
SELECT day, amount,
SUM(amount) OVER (PARTITION BY substr(day, 1, 7) ORDER BY day) AS month_to_date
FROM daily_sales
ORDER BY day;
day
amount
month_to_date
2026-03-01
120
120
2026-03-02
80
200
2026-03-03
150
350
2026-03-05
90
440
2026-03-06
60
500
2026-03-09
200
700
All the March days are in one month here, so the result matches, but the partition would reset the total on 1 April.
For running totals, writing the frame explicitly is a good habit, because the default frame (RANGE) treats rows with the same ORDER BY value as one step:
text
SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
With a unique day, ROWS and RANGE give the same numbers. With duplicate keys they do not.
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 day) AS running_total
FROM daily_sales
ORDER BY day;
SELECT day, amount,
SUM(amount) OVER (PARTITION BY substr(day, 1, 7) ORDER BY day) AS month_to_date
FROM daily_sales
ORDER BY day;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
SUM(x) OVER (ORDER BY ...) gives a running total
The window's ORDER BY sets the accumulation order
PARTITION BY restarts the total per group
Write the ROWS frame explicitly when order keys can repeat
Common mistakes
Using a self join or correlated subquery for running totals on large tables
Confusing the window ORDER BY with the query's ORDER BY
Follow-ups
What changes if two rows have the same day?
How would you compute a 3-day moving average?
Tips
Mention the frame; it is what separates a good answer
116.sql-0116Hardsenior
A running total over transactions jumps by two amounts at once on days with two transactions. Why, and how do you fix it?
With ORDER BY in the window and no frame clause, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE includes all peers, meaning rows with the same ORDER BY value, so both transactions on the same day show the day's combined total. Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW and a unique tie-breaker for a row-by-row running total.
Full answer
sql
CREATE TABLE txns (id INTEGER PRIMARY KEY, day TEXT, amount INTEGER);
INSERT INTO txns VALUES (1,'2026-03-01',100),(2,'2026-03-02',50),(3,'2026-03-02',25),(4,'2026-03-03',10);
sql
SELECT id, day, amount,
SUM(amount) OVER (ORDER BY day) AS running_default
FROM txns
ORDER BY id;
id
day
amount
running_default
1
2026-03-01
100
100
2
2026-03-02
50
175
3
2026-03-02
25
175
4
2026-03-03
10
185
Both rows for 2 March show 175. RANGE treats rows with the same day as peers and includes all of them in the frame of each. So the "running" total jumps from 100 to 175 in one step and the intermediate value is never shown.
ROWS counts physical rows instead, so each row adds only itself. A tie-breaker (id) makes the order of the two same-day rows defined:
sql
SELECT id, day, amount,
SUM(amount) OVER (ORDER BY day, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_rows
FROM txns
ORDER BY id;
id
day
amount
running_rows
1
2026-03-01
100
100
2
2026-03-02
50
150
3
2026-03-02
25
175
4
2026-03-03
10
185
Which is right depends on the question. "Balance at the end of each day" wants the RANGE behaviour, and a GROUP BY day would be even clearer. "Balance after each transaction" wants ROWS.
PostgreSQL behaves the same:
sql
SELECT id, SUM(amount) OVER (ORDER BY day) AS running_default
FROM txns ORDER BY id;
id
running_default
1
100
2
175
3
175
4
185
A third frame type, GROUPS (in PostgreSQL 11+ and SQLite 3.28+), counts groups of peers, which is handy for "this day and the previous two days" when days have several rows.
sql
CREATE TABLE txns (id INTEGER PRIMARY KEY, day TEXT, amount INTEGER);
INSERT INTO txns VALUES (1,'2026-03-01',100),(2,'2026-03-02',50),(3,'2026-03-02',25),(4,'2026-03-03',10);
SELECT id, day, amount,
SUM(amount) OVER (ORDER BY day) AS running_default
FROM txns
ORDER BY id;
SELECT id, day, amount,
SUM(amount) OVER (ORDER BY day, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_rows
FROM txns
ORDER BY 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
Default frame with ORDER BY is RANGE ... CURRENT ROW
RANGE includes all peers with the same ORDER BY value
ROWS includes only physical rows up to the current one
Add a unique tie-breaker for deterministic row-by-row totals
Common mistakes
Relying on the default frame for per-transaction running balances
ROWS without a tie-breaker, which makes same-day order arbitrary
Follow-ups
What does GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW mean?
How would you show the end-of-day balance only once per day?
Tips
Name the default frame exactly; interviewers look for RANGE
117.sql-0117Mediummid
Write a query for a 3-day moving average of sales.
Use AVG(amount) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW). The first two rows average over fewer days because there are not enough earlier rows. ROWS counts rows, not calendar days, so if days are missing from the table, fill the calendar first or the window will span more than three 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 (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS avg_3_rows
FROM daily_sales
ORDER BY day;
day
amount
avg_3_rows
2026-03-01
120
120.0
2026-03-02
80
100.0
2026-03-03
150
116.7
2026-03-05
90
106.7
2026-03-06
60
100.0
2026-03-09
200
116.7
The frame ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means "this row and the two before it". On 1 March only one row exists, so the average is the amount itself; on 2 March it averages two rows.
There is a catch in this data. The table has no rows for 4, 7 and 8 March, so the "3-day" average on 9 March actually covers 5, 6 and 9 March. ROWS counts rows, whatever dates they hold.
If the business means three calendar days, generate the missing days first and treat them as zero:
sql
WITH RECURSIVE days(day) AS (
SELECT '2026-03-01' UNION ALL
SELECT date(day, '+1 day') FROM days WHERE day < '2026-03-09'
)
SELECT d.day, COALESCE(s.amount, 0) AS amount,
ROUND(AVG(COALESCE(s.amount, 0)) OVER (ORDER BY d.day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS avg_3_days
FROM days d LEFT JOIN daily_sales s ON s.day = d.day
ORDER BY d.day;
day
amount
avg_3_days
2026-03-01
120
120.0
2026-03-02
80
100.0
2026-03-03
150
116.7
2026-03-04
0
76.7
2026-03-05
90
80.0
2026-03-06
60
50.0
2026-03-07
0
50.0
2026-03-08
0
20.0
2026-03-09
200
66.7
Now the 9 March value covers 7, 8 and 9 March. To hide the incomplete averages at the start, add a count in the same frame and blank the value when it is below 3:
text
CASE WHEN COUNT(*) OVER w = 3 THEN AVG(amount) OVER w END
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 (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS avg_3_rows
FROM daily_sales
ORDER BY day;
WITH RECURSIVE days(day) AS (
SELECT '2026-03-01' UNION ALL
SELECT date(day, '+1 day') FROM days WHERE day < '2026-03-09'
)
SELECT d.day, COALESCE(s.amount, 0) AS amount,
ROUND(AVG(COALESCE(s.amount, 0)) OVER (ORDER BY d.day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS avg_3_days
FROM days d LEFT JOIN daily_sales s ON s.day = d.day
ORDER BY d.day;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is a 3-row window
Early rows have smaller windows
ROWS counts rows, not calendar days
Fill missing days first when the window must be calendar-based
Common mistakes
Calling a 3-row window a 3-day window when days are missing
Using the default frame, which is a running average, not a moving one
Follow-ups
How would you compute a 7-day moving sum per store?
Could RANGE with an interval solve the missing-day problem in PostgreSQL?
Tips
Point out the gap in the data before showing the fix
118.sql-0118Mediummid
How do you compare each day's sales with the previous day's? Explain LAG and LEAD.
LAG(expr) returns the value from the previous row in the window order and LEAD(expr) from the next row. LAG(amount) OVER (ORDER BY day) gives yesterday's amount, so amount - LAG(amount) is the change. Both take an offset and a default: LAG(amount, 1, 0) returns 0 instead of NULL for the first row.
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,
LAG(amount) OVER (ORDER BY day) AS prev_amount,
amount - LAG(amount) OVER (ORDER BY day) AS change
FROM daily_sales
ORDER BY day;
day
amount
prev_amount
change
2026-03-01
120
NULL
NULL
2026-03-02
80
120
-40
2026-03-03
150
80
70
2026-03-05
90
150
-60
2026-03-06
60
90
-30
2026-03-09
200
60
140
The first row has no previous row, so LAG returns NULL, and the change is NULL too. That is usually more honest than 0, which would claim the first day had "no change".
The percentage change needs care with division:
sql
SELECT day, amount,
ROUND(100.0 * (amount - LAG(amount) OVER (ORDER BY day))
/ NULLIF(LAG(amount) OVER (ORDER BY day), 0), 1) AS pct_change
FROM daily_sales
ORDER BY day;
day
amount
pct_change
2026-03-01
120
NULL
2026-03-02
80
-33.3
2026-03-03
150
87.5
2026-03-05
90
-40.0
2026-03-06
60
-33.3
2026-03-09
200
233.3
1.0 * avoids integer division, and NULLIF would protect against a previous value of 0.
LEAD looks forward. It answers "how many days until the next sale?":
sql
SELECT day,
LEAD(day) OVER (ORDER BY day) AS next_sale_day,
CAST(julianday(LEAD(day) OVER (ORDER BY day)) - julianday(day) AS INTEGER) AS days_until_next
FROM daily_sales
ORDER BY day;
day
next_sale_day
days_until_next
2026-03-01
2026-03-02
1
2026-03-02
2026-03-03
1
2026-03-03
2026-03-05
2
2026-03-05
2026-03-06
1
2026-03-06
2026-03-09
3
2026-03-09
NULL
NULL
As with moving averages, "previous row" is not the same as "previous calendar day" when days are missing. 5 March is compared with 3 March here, which may or may not be what the report means.
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,
LAG(amount) OVER (ORDER BY day) AS prev_amount,
amount - LAG(amount) OVER (ORDER BY day) AS change
FROM daily_sales
ORDER BY day;
SELECT day, amount,
ROUND(100.0 * (amount - LAG(amount) OVER (ORDER BY day))
/ NULLIF(LAG(amount) OVER (ORDER BY day), 0), 1) AS pct_change
FROM daily_sales
ORDER BY day;
SELECT day,
LEAD(day) OVER (ORDER BY day) AS next_sale_day,
CAST(julianday(LEAD(day) OVER (ORDER BY day)) - julianday(day) AS INTEGER) AS days_until_next
FROM daily_sales
ORDER BY day;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
LAG reads the previous row; LEAD reads the next
Both accept an offset and a default value
The first row's LAG is NULL unless a default is given
Previous row is not previous calendar day when days are missing
Common mistakes
Defaulting LAG to 0 and reporting a fake change on the first day
Dividing integers when computing percentage change
Follow-ups
How would you compare each month with the same month last year?
How would you find the longest gap between sales?
Tips
Mention the missing-day issue; it shows attention to data
119.sql-0119Mediummid
Write a query that returns the two highest-paid employees in each department.
Number rows within each department by salary with ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC, id), then keep rows numbered 1 or 2 in an outer query. Use DENSE_RANK instead if everyone tied at second place should be included.
Full answer
"Top N per group" is a window-function classic. The window does the ranking; an outer query does the filtering, because window functions cannot appear in WHERE.
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
WITH ranked AS (
SELECT name, dept_id, salary,
ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC, name) AS rn
FROM employees
WHERE dept_id IS NOT NULL
)
SELECT dept_id, name, salary FROM ranked WHERE rn <= 2 ORDER BY dept_id, rn;
dept_id
name
salary
1
Asha
120000
1
Mei
95000
2
Tom
70000
2
Sara
62000
3
Diego
55000
3
Omar
48000
Engineering has three people, so Ravi (95000) is cut, even though he earns the same as Mei. That is ROW_NUMBER doing exactly what it promises: two rows per department, ties broken by name.
If ties should all be kept, rank instead:
sql
WITH ranked AS (
SELECT name, dept_id, salary,
DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM employees
WHERE dept_id IS NOT NULL
)
SELECT dept_id, name, salary, rnk FROM ranked WHERE rnk <= 2 ORDER BY dept_id, rnk, name;
dept_id
name
salary
rnk
1
Asha
120000
1
1
Mei
95000
2
1
Ravi
95000
2
2
Tom
70000
1
2
Sara
62000
2
3
Diego
55000
1
3
Omar
48000
2
Now Engineering returns all three, because Ravi and Mei share rank 2. Sales and Support have only two people each, so both versions return them.
An index on (dept_id, salary DESC) helps engines that can read each department's top rows directly. Without window functions, the same result needs a correlated count ("fewer than 2 colleagues in the same department earn more"), which is harder to read.
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');
WITH ranked AS (
SELECT name, dept_id, salary,
ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC, name) AS rn
FROM employees
WHERE dept_id IS NOT NULL
)
SELECT dept_id, name, salary FROM ranked WHERE rn <= 2 ORDER BY dept_id, rn;
WITH ranked AS (
SELECT name, dept_id, salary,
DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM employees
WHERE dept_id IS NOT NULL
)
SELECT dept_id, name, salary, rnk FROM ranked WHERE rnk <= 2 ORDER BY dept_id, rnk, name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Rank inside each group with PARTITION BY
Filter the rank in an outer query or CTE
ROW_NUMBER gives exactly N per group
DENSE_RANK keeps all ties at the cut-off
Common mistakes
Filtering the window function in WHERE
Using ROW_NUMBER and silently dropping a tied employee
Follow-ups
How would you write this without window functions?
How would you get the top 2 per department by hire date instead?
Tips
Ask whether ties should be included before choosing the function
120.sql-0120Mediummid
Why does WHERE ROW_NUMBER() OVER (...) = 1 fail, and how do you filter on a window function result?
Window functions are computed after WHERE, GROUP BY and HAVING, so they do not exist yet when WHERE runs, and the engine rejects the query. Compute the window in a subquery or CTE and filter in the outer query. Some engines, such as Snowflake, BigQuery and DuckDB, add a QUALIFY clause for this; SQLite and PostgreSQL do not.
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 FROM employees
WHERE ROW_NUMBER() OVER (ORDER BY salary DESC) = 1;
-- error on purpose
text
Error: misuse of window function ROW_NUMBER()
PostgreSQL gives a clearer message:
sql
SELECT name FROM employees
WHERE ROW_NUMBER() OVER (ORDER BY salary DESC) = 1;
-- error on purpose
text
Error: window functions are not allowed in WHERE
The logical order is FROM, WHERE, GROUP BY, HAVING, then window functions, then SELECT, ORDER BY and LIMIT. WHERE cannot filter on something that is computed later.
Wrap the window in a CTE (or a derived table) and filter outside:
sql
WITH ranked AS (
SELECT name, salary, ROW_NUMBER() OVER (ORDER BY salary DESC NULLS LAST, name) AS rn
FROM employees
)
SELECT name, salary FROM ranked WHERE rn = 1;
name
salary
Asha
120000
This also lets you filter on several window results at once and keeps the ranking logic readable. QUALIFY, where it exists, is shorthand for exactly this pattern (... QUALIFY ROW_NUMBER() OVER (...) = 1); it is not standard SQL and was not run here.
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 FROM employees
WHERE ROW_NUMBER() OVER (ORDER BY salary DESC) = 1;
WITH ranked AS (
SELECT name, salary, ROW_NUMBER() OVER (ORDER BY salary DESC NULLS LAST, name) AS rn
FROM employees
)
SELECT name, salary FROM ranked WHERE rn = 1;
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 are evaluated after WHERE and HAVING
They cannot appear in WHERE, GROUP BY or HAVING
Filter them in an outer query or CTE
QUALIFY exists in some warehouses but not in SQLite or PostgreSQL
Common mistakes
Moving the window function into HAVING, which fails for the same reason
Writing the filter as a correlated subquery when a CTE is clearer
Follow-ups
Can ORDER BY use a window function?
How would you keep only the latest order per customer?