Explain CTEs, recursive queries and LATERAL joins in PostgreSQL.
Common Table Expressions
WITH name AS (...) names a subquery to make complex queries readable. Since PostgreSQL 12, simple CTEs are inlined into the main query (optimised together); add MATERIALIZED to force computing them once, or NOT MATERIALIZED to force inlining.
Data-modifying CTEs can chain writes: WITH moved AS (DELETE ... RETURNING *) INSERT INTO archive SELECT * FROM moved.
Recursive CTEs
WITH RECURSIVE has an anchor query plus a recursive part that references the CTE, repeated until no new rows appear. Used for hierarchies (org charts, category trees, bill of materials) and graph walks. Add a depth limit or cycle detection (CYCLE clause) for safety.
LATERAL
A LATERAL subquery can reference columns of tables earlier in the FROM clause, like a for-each loop. It is the cleanest way to get top N per group with an index, or to call a set-returning function per row.
Example
-- All reports (direct and indirect) of manager 1, with depth and path
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 1 AS depth, ARRAY[name] AS path
FROM employees WHERE id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id, o.depth + 1, o.path || e.name
FROM employees e
JOIN org o ON e.manager_id = o.id
WHERE o.depth < 10
)
SELECT name, depth, array_to_string(path, ' > ') FROM org ORDER BY path;
-- Latest 3 orders per customer, using an index on orders(customer_id, created_at DESC)
SELECT c.name, o.id, o.created_at
FROM customers c
CROSS JOIN LATERAL (
SELECT id, created_at FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) o;
-- Archive old rows in one statement
WITH moved AS (
DELETE FROM orders WHERE created_at < now() - interval '2 years' RETURNING *
)
INSERT INTO orders_archive SELECT * FROM moved;Follow-up questions interviewers ask
Try answering each one before you open it.
How would you implement a job queue on PostgreSQL?
Workers claim jobs with SELECT ... FROM jobs WHERE status = 'READY' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED, so concurrent workers skip rows already locked by others instead of waiting, then update the status in the same transaction. Libraries such as JobRunr and db-scheduler (Java) use this pattern; keep the table small and vacuumed.