SQL course · Advanced SQL lesson
Advanced SQL Interviews: CTEs, Optimization and Edge Cases
Reason through CTEs, null-safe comparisons, indexes and execution plans with a runnable PostgreSQL scenario.
Original PostgreSQL examples · Learn the method, test the output, explain the result.
Core idea
Prove correctness before claiming a query is faster.
EXPLAIN (ANALYZE, BUFFERS)
Check the actual plan
The direct answer
Make assumptions explicit before optimising the query.
Advanced SQL interview questions often combine a correct-result problem with a performance discussion. The safest order is to define the expected rows, handle nulls and ties, test on a small dataset, and only then discuss an index or execution plan. An index is a possible access path, not a guarantee that every query will use it.
This PostgreSQL lesson includes a null-safe matching case, a CTE that makes the intermediate result visible, and a plan-review checklist. The examples show engine assumptions openly. For a foundation in ranking and partitions, use the window lesson first. Course options follow this overview.
Course access
Choose your next step in SQL.
Review the current course options and access details here.
Heycademy Courses · Coming Soon
Master SQL with Heycademy
We’re preparing an interactive learning experience with practical exercises, skill assessments and personalized learning to help you build confidence and master new skills.
We’re putting the finishing touches on this course. Please check back for updates.
Engine and task assumptions
State what NULL means in the data.
Consider a customer table with an optional region code and a region-target table whose code may also be NULL. The task is to pair customers with the target row that represents the same region, treating two missing codes as a match. Ordinary = does not return true for NULL = NULL. PostgreSQL supports IS NOT DISTINCT FROM for null-safe equality; its comparison reference defines this behavior.
This is a business rule, not a universal instruction to match missing values. In another problem, two missing regions may mean “unknown” and must not be treated as equal. Explain that choice to the interviewer before selecting an operator.
Original advanced scenario
Two missing codes, one intentional match.
| customer id | name | region code |
|---|---|---|
| 1 | Ada | N |
| 2 | Ben | NULL |
| 3 | Cleo | S |
| code | target |
|---|---|
| N | 100 |
| NULL | 50 |
| S | 75 |
CREATE TEMP TABLE customers (id integer PRIMARY KEY,name text,region_code text);
CREATE TEMP TABLE region_targets (id integer PRIMARY KEY,code text,target integer);
INSERT INTO customers VALUES (1,'Ada','N'),(2,'Ben',NULL),(3,'Cleo','S');
INSERT INTO region_targets VALUES (10,'N',100),(11,NULL,50),(12,'S',75);
SELECT c.name,t.target
FROM customers c JOIN region_targets t
ON c.region_code IS NOT DISTINCT FROM t.code
ORDER BY c.id;| name | target |
|---|---|
| Ada | 100 |
| Ben | 50 |
| Cleo | 75 |
An ordinary equality join returns Ada and Cleo but drops Ben. That is wrong under the stated matching rule. A quick verification is to test the three pairs individually, including the missing-code pair, before discussing indexes.
CTE reasoning
Name the intermediate relation you need to inspect.
WITH matched AS (
SELECT c.id,c.name,t.target
FROM customers c JOIN region_targets t
ON c.region_code IS NOT DISTINCT FROM t.code
)
SELECT name,target FROM matched WHERE target>=75 ORDER BY id;| name | target |
|---|---|
| Ada | 100 |
| Cleo | 75 |
The CTE gives the matched rows a name, then the outer query filters targets. Ben’s match exists in the CTE but has target 50 and is removed by the outer filter. A CTE can make reasoning clearer, but it is not automatically faster. PostgreSQL’s WITH documentation describes when common table expressions may be folded or materialised. Verify the actual engine and version rather than claiming a universal rule.
Keep building this skill
Apply the method on fresh SQL problems.
The course options are above. Return to the synced pricing block whenever you are ready.
Plan review
Measure before and after an index.
CREATE INDEX region_targets_code_idx ON region_targets(code);
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name,t.target
FROM customers c JOIN region_targets t
ON c.region_code IS NOT DISTINCT FROM t.code;This command is for PostgreSQL. It reports a chosen plan and observed execution statistics when run in a real PostgreSQL environment. On a three-row teaching table, a sequential scan may be cheaper than an index lookup. Do not label that as a failed index. The right question is whether the plan is sensible for realistic data, selectivity and workload.
| Plan review question | Evidence to inspect | What it means |
|---|---|---|
| Did the result stay correct? | Same rows and target values before/after index. | Performance changes must not change semantics. |
| How many rows were estimated and returned? | Estimate and actual row counts. | Large gaps can affect plan selection. |
| What access path was chosen? | Scan and join nodes in EXPLAIN output. | An index may or may not be chosen. |
| What changed under a realistic workload? | Repeatable timing and buffer readings. | One tiny run is not a reliable benchmark. |
The official PostgreSQL EXPLAIN guide and index guide are the primary references for plan interpretation.
Advanced scenario set
Test the assumptions that are easiest to miss.
| Scenario | Question to ask | Safe check |
|---|---|---|
| Duplicate target code | Can one customer match several target rows? | Add a second N target; inspect join cardinality and define which target is valid. |
| Missing code | Should two unknown regions match? | Confirm the business rule before using null-safe equality. |
| Tie in ranking | Should all tied rows appear or exactly N? | Choose RANK or ROW_NUMBER with a tie-break deliberately. |
| Large table | Is an index justified? | Compare actual plans with representative data and workload. |
For an unseen check, add a second target row with code N. Ada will now match two targets. The query is still valid SQL, but the original “one target per customer” assumption has failed. Repair the data constraint or state a deterministic rule for choosing one target; DISTINCT is not a substitute for deciding which target is correct.
How to answer aloud
Separate correctness from speed.
- Restate the required output and the meaning of missing values.
- Show a tiny example including the edge case.
- Write a query whose output you can predict.
- Discuss cardinality, constraints and plan choices.
- Measure on realistic data before claiming an optimisation.
This sequence gives an interviewer a view of your reasoning even if the final plan differs between PostgreSQL versions or data distributions. For other mistakes involving NULL and double counting, continue with the error-repair lesson.
Plan discussion checklist
Separate a measured result from a prediction.
In a live interview, you may be asked whether an index on region_targets.code will speed up the join. A careful answer is conditional. On the three-row example, scanning is cheap. With millions of targets and a selective lookup, an index might help, but join method, statistics, NULL distribution, data type, collation and the exact comparison operator all matter. Check the plan on realistic data and confirm the indexed expression supports the predicate being used.
EXPLAIN estimates a plan; EXPLAIN ANALYZE runs the query and reports observed work. Read both estimated and actual row counts, the scan type and the join node. A single wall-clock time from a warm cache is not enough to claim a stable improvement. Indexes also have write and storage costs, so discuss the workload rather than treating “add an index” as a universal answer.
What if the second target row also has a NULL code?
Ben would match both NULL-code target rows under IS NOT DISTINCT FROM. The query would then return two Ben rows. A uniqueness rule or a defined “current target” criterion is needed if the requirement is one row per customer.
The official EXPLAIN documentation gives plan-reading examples. Use it alongside correctness tests; a faster wrong answer is still wrong.
FAQ
Questions about this skill.
Does a CTE always improve performance?
No. Use it to express an intermediate result clearly, then inspect your engine’s actual plan when performance matters.
Will an index always appear in EXPLAIN?
No. The planner may prefer a scan, especially on a tiny table or low-selectivity condition.
Should NULL values always be matched to each other?
Only when the problem’s business rule says two missing values are equivalent for this comparison.
Continue with the SQL course
Make this skill reliable on new data.
Return to the course options and choose the next learning step.