Interview Question: "Explain the difference between NOT EXISTS and LEFT JOIN...IS NULL for anti-joins. When would you use a materialized CTE? How do you optimize subqueries?" â Asked at Amazon, Google, Microsoft for Senior Backend roles
âšī¸
Difficulty: Advanced | Companies: Amazon, Google, Microsoft, Meta, Apple | Time: 60-75 minutes
Semi-Join Patterns
Semi-join returns rows from left table that match right table:
The planner treats EXISTS, IN, INTERSECT, and an inner join on a unique key as one logical operation, then picks a physical form from the statistics. On the sample below â 5 customers, 4 orders â every form is a trivial nested loop. Scale the same shape to 200,000 customers and 1.2 million orders with an index on orders.customer_id and the planner switches to an index-driven nested loop: roughly 200,000 probes, each a few hundredths of a millisecond, which is seconds of CPU before any rows reach the client. Drop that index and it hashes the orders side instead, scanning both inputs once and probing 200,000 times against an in-memory table.
-- Create sample tables
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(255)
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
total_amount DECIMAL(12,2)
);
-- Generate sample data
INSERT INTO customers VALUES
(1, 'Alice', '[email protected]'),
(2, 'Bob', '[email protected]'),
(3, 'Charlie', '[email protected]'),
(4, 'Diana', '[email protected]'),
(5, 'Eve', '[email protected]');
INSERT INTO orders VALUES
(1, 1, '2024-01-01', 100.00),
(2, 1, '2024-01-15', 150.00),
(3, 2, '2024-02-01', 200.00),
(4, 3, '2024-02-15', 175.00);
-- Semi-Join: IN clause
SELECT * FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);
-- Semi-Join: EXISTS (often more efficient)
SELECT * FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
);
-- Semi-Join: INTERSECT
SELECT * FROM customers
WHERE customer_id IN (
SELECT customer_id FROM orders
INTERSECT
SELECT customer_id FROM orders WHERE total_amount > 100
);
Output:
| customer_id | name | |
|---|---|---|
| 1 | Alice | [email protected] |
| 2 | Bob | [email protected] |
| 3 | Charlie | [email protected] |
Anti-Join Patterns
Anti-join returns rows from left table that don't match right table:
-- Anti-Join: NOT IN (beware of NULLs!)
SELECT * FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);
-- Anti-Join: NOT EXISTS (usually more efficient)
SELECT * FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
);
-- Anti-Join: LEFT JOIN...IS NULL
SELECT c.* FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.customer_id IS NULL;
-- Anti-Join: EXCEPT
SELECT customer_id FROM customers
EXCEPT
SELECT customer_id FROM orders;
Output:
| customer_id | name | |
|---|---|---|
| 4 | Diana | [email protected] |
| 5 | Eve | [email protected] |
â ī¸
NULL Trap: NOT IN with NULL values returns empty results. Always use NOT EXISTS or ensure the subquery excludes NULLs.
The NULL That Empties NOT IN
NOT IN looks like the negation of IN and is not. IN is true when any member matches; NOT IN must prove that no member matches, and three-valued logic makes an unprovable case return no rows at all. One NULL in the subquery result therefore collapses the predicate to UNKNOWN for every candidate row, and the query returns an empty set without raising an error â the classic silent data loss in reporting queries.
-- One NULL empties the whole result
CREATE TABLE eligible (customer_id INT);
INSERT INTO eligible VALUES (1), (2), (NULL);
SELECT * FROM customers WHERE customer_id NOT IN (SELECT customer_id FROM eligible);
-- 0 rows: customers 4 and 5 never appear
SELECT * FROM customers c WHERE NOT EXISTS (
SELECT 1 FROM eligible e WHERE e.customer_id = c.customer_id
);
-- Rows 4 and 5: NULL never satisfies the equality, so it never matches
The asymmetry also appears with a nullable key on either side. NOT EXISTS compares o.customer_id = c.customer_id, which is UNKNOWN when either operand is NULL, and UNKNOWN counts as no match, so the outer row survives the anti-join. NOT IN degrades the entire predicate instead. Use NOT IN only when the subquery carries an IS NOT NULL guard on a column you control; prefer NOT EXISTS everywhere else.
What the Plan Tells You About the Join Shape
After running the two EXPLAIN (ANALYZE, BUFFERS) statements later in this lesson, compare three numbers instead of total time alone: estimated rows against actual rows, shared buffers hit against read, and loops. An index-driven semi join that reports loops=200000 on its index scan is performing 200,000 separate probes; a hash semi join reports loops=1 on each input. Estimation error is the usual culprit â when the planner expects 1 row from a subquery and receives 40,000, it priced a nested loop against the wrong number, and the fix is ANALYZE or a higher statistics target on the key column rather than a different join syntax.
| Plan shape | Typical signature | Wins when |
|---|---|---|
| Index nested loop | loops equals outer rows, tiny row count per loop | Right side indexed and outer filter selective |
| Hash semi join | One build plus one probe, loops=1 | Large right side with no usable index |
| Merge semi join | Both inputs sorted, buffer reads dominate | Inputs already ordered by the join key |
Re-run the analysis after every index change. The choice the planner makes at 1,000 test rows rarely survives contact with 10 million production rows.
Materialized CTE
Materialized CTEs compute results once and reuse:
-- Non-materialized CTE (computed multiple times)
WITH order_stats AS (
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(total_amount) AS total_spent
FROM orders
GROUP BY customer_id
)
SELECT
c.name,
s.order_count,
s.total_spent,
s.total_spent / NULLIF(s.order_count, 0) AS avg_order_value
FROM customers c
JOIN order_stats s ON c.customer_id = s.customer_id;
-- Materialized CTE (PostgreSQL 12+)
WITH order_stats AS MATERIALIZED (
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(total_amount) AS total_spent
FROM orders
GROUP BY customer_id
)
SELECT
c.name,
s.order_count,
s.total_spent
FROM customers c
JOIN order_stats s ON c.customer_id = s.customer_id;
-- Not Materialized (inline, may be optimized away)
WITH order_stats AS NOT MATERIALIZED (
SELECT
customer_id,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
)
SELECT * FROM order_stats WHERE order_count > 1;
When a CTE Is Really Materialized
PostgreSQL 12 stopped treating every CTE as an optimization fence, which surprises anyone who learned the old rule. A CTE body is materialized when you write AS MATERIALIZED, when the statement is recursive, when the CTE name is referenced more than once, or when the body contains a volatile function. Everything else is folded into the outer query like an inline view, so a filter written in the outer WHERE reaches down into the CTE and reduces its scan.
-- Referenced twice: the planner cannot inline it
WITH order_stats AS (
SELECT customer_id, COUNT(*) AS order_count
FROM orders GROUP BY customer_id
)
SELECT
(SELECT order_count FROM order_stats WHERE customer_id = c.customer_id) AS first_lookup,
(SELECT order_count FROM order_stats WHERE customer_id = c.customer_id) AS second_lookup
FROM customers c;
-- Explicitly inline so the outer filter prunes before aggregation
WITH recent AS NOT MATERIALIZED (
SELECT * FROM orders WHERE order_date > '2024-01-01'
)
SELECT customer_id, COUNT(*) FROM recent GROUP BY customer_id;
The decision rule is simple: materialize when the body is expensive and reused, because the work is paid once; inline when the outer query filters or aggregates heavily, because inlining lets that predicate shrink the input. On a 10-million-row table the difference runs in either direction by an order of magnitude, so measure both forms with EXPLAIN (ANALYZE, BUFFERS) instead of trusting a habit formed on an older release.
Semi-Join Versus Inner Join
An inner join against a table with duplicate keys multiplies rows; a semi join never does, and that semantic difference is why the planner rewrites IN and EXISTS into semi joins rather than into a join plus DISTINCT. If you hand-write the join and then add DISTINCT to repair the multiplicity, you have asked the planner to build and de-duplicate a set it could have skipped â with a covering index it might have answered the query without touching the heap at all. Keep the semi-join form in the text so the rewrite stays available, and switch to an explicit join only when you genuinely need columns from the right side, at which point it is no longer a semi join and the row-multiplication risk is yours to manage.
Tuning the Switch: Cost Knobs and Statistics
Join strategy is a cost decision, so the controls are cost controls. random_page_cost at the historical default of 4.0 makes index probes look expensive and pushes the planner toward hash joins; on SSD storage a value near 1.1 often reflects reality and flips plans back to index-driven semi joins. join_collapse_limit and geqo_threshold bound how many join orders get enumerated, and lowering them freezes an ordering you have already verified by hand. Neither knob repairs a wrong row estimate: check n_distinct, null_frac and histogram_bounds in pg_stats for the join key, run ANALYZE after every bulk load, and raise statistics target on the column whose estimate is furthest from the truth. A plan built on a bad estimate stays bad under every cost setting you change.
Subquery Optimization
-- Correlated subquery (can be slow)
SELECT
c.*,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers c;
-- Rewrite with JOIN (usually faster)
SELECT
c.*,
COALESCE(s.order_count, 0) AS order_count
FROM customers c
LEFT JOIN (
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
) s ON c.customer_id = s.customer_id;
-- EXISTS vs IN for large datasets
-- EXISTS is often faster for large right tables
SELECT * FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date > '2024-01-01'
);
Join Optimization Patterns
-- Filter early (reduce join size)
SELECT o.*, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date > '2024-01-01' -- Filter before join
AND o.total_amount > 100;
-- Use covering indexes
CREATE INDEX idx_orders_covering ON orders(customer_id, order_date, total_amount);
-- Join order optimization
-- PostgreSQL optimizer usually handles this, but you can hint
SET join_collapse_limit = 12; -- Allow more join reordering
-- LATERAL for dependent subqueries
SELECT
c.*,
latest.order_date,
latest.total_amount
FROM customers c
CROSS JOIN LATERAL (
SELECT order_date, total_amount
FROM orders
WHERE customer_id = c.customer_id
ORDER BY order_date DESC
LIMIT 1
) latest;
Performance Comparison Table
| Pattern | Time Complexity | When to Use |
|---|---|---|
| Semi-Join (EXISTS) | Large right table | |
| Anti-Join (NOT EXISTS) | Exclusion queries | |
| Materialized CTE | Reuse results | |
| Correlated Subquery | Avoid if possible | |
| LATERAL JOIN | Top-N per group |
-- Compare execution plans
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM customers c
WHERE c.customer_id IN (SELECT customer_id FROM orders);
Window Function Optimization
-- Avoid multiple window passes
-- Bad: Multiple window functions
SELECT
customer_id,
order_date,
SUM(total_amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total,
AVG(total_amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_avg,
COUNT(*) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_count
FROM orders;
-- Good: Combine if possible
WITH windowed AS (
SELECT
customer_id,
order_date,
total_amount,
SUM(total_amount) OVER w AS running_total,
AVG(total_amount) OVER w AS running_avg,
COUNT(*) OVER w AS running_count
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date)
)
SELECT * FROM windowed;
Mathematical Formulas
For join performance:
The optimizer chooses based on:
âšī¸
Pro Tip: Use EXPLAIN (ANALYZE, BUFFERS) to compare actual I/O between different query patterns. Buffer hits indicate cached data, reads indicate disk I/O.
Anti-Patterns to Avoid
- SELECT * in subqueries
- NOT IN with nullable columns
- Correlated subqueries in SELECT
- Multiple scans of same table
- Unnecessary DISTINCT or ORDER BY
-- Bad: SELECT * in subquery
SELECT * FROM customers
WHERE customer_id IN (SELECT * FROM orders);
-- Good: Specify columns
SELECT * FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);
-- Bad: Correlated subquery
SELECT *, (SELECT MAX(order_date) FROM orders WHERE customer_id = c.customer_id)
FROM customers c;
-- Good: Join
SELECT c.*, o.max_date
FROM customers c
LEFT JOIN (
SELECT customer_id, MAX(order_date) AS max_date
FROM orders
GROUP BY customer_id
) o ON c.customer_id = o.customer_id;
â ī¸
Performance Warning: Always test queries with realistic data volumes. Small test datasets may not reveal performance issues.
Choosing a Pattern Under Deadline Pressure
Start from the data shape rather than the syntax. A large, unindexed right side points at a hash semi join; a small right side with a unique index points at EXISTS with an index scan; a top-N-per-group requirement points at LATERAL; a result used twice in one statement points at an explicitly materialized CTE. Verify each choice with EXPLAIN (ANALYZE, BUFFERS) on production-sized data and keep the comparison in the pull request, because the winning shape changes when volumes cross the point where the hash table stops fitting in work_mem.
Key Takeaways
- Semi-join and anti-join are set operations: row multiplicity never changes, which is what distinguishes them from inner and outer joins
- NOT IN fails closed on a single NULL, while NOT EXISTS fails open; treat NOT IN as unsafe unless the subquery is NULL-guarded
- Plan shape follows statistics: index nested loop, hash, and merge each win under a different shape, and loops reveals which one ran
- PostgreSQL 12+ inlines CTEs by default, so materialize only when the body is expensive and referenced more than once
- Cost knobs move a plan, statistics make it correct â check estimated versus actual rows before changing anything