SQL course · Error-repair lesson

SQL Interview Mistakes: NULL, DISTINCT and Double Counting

Repair three common SQL interview errors with executable NOT IN, DISTINCT and join examples and checked outputs.

Original PostgreSQL examples · Learn the method, test the output, explain the result.

SQL LEARNING PREVIEW
Error-repair lessonPostgreSQL

Core idea

A plausible query can return the wrong rows.

NOT IN (2, NULL)
→ no safe exclusion
Use NOT EXISTS
First understand the query.Then try the next variation without copying the answer.

The direct answer

Find the first clause that changed the answer.

Three SQL mistakes cause many convincing but wrong answers: comparing to NULL as if it were an ordinary value, adding DISTINCT to hide a join problem, and summing a header amount after a one-to-many join. Repair them by predicting a small dataset’s output, then changing one row to test whether the corrected rule transfers.

The examples use PostgreSQL and show both the incorrect result and the corrected query. They are learning exercises for interview preparation, not a catalogue of any employer’s exact questions. The fundamentals lesson introduces join behavior. 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.

Launching soon!
We’re putting the finishing touches on this course. Please check back for updates.

Mistake 1

NOT IN can be undone by a NULL.

employees
employee idname
1Ada
2Ben
3Cleo
exclusions
excluded employee id
2
NULL
CREATE TEMP TABLE employees (id integer PRIMARY KEY,name text);
CREATE TEMP TABLE exclusions (employee_id integer);
INSERT INTO employees VALUES (1,'Ada'),(2,'Ben'),(3,'Cleo');
INSERT INTO exclusions VALUES (2),(NULL);

-- Tempting, but returns no rows:
SELECT name FROM employees
WHERE id NOT IN (SELECT employee_id FROM exclusions)
ORDER BY id;

The intended answer is Ada and Cleo. Ben is explicitly excluded. Yet the query returns no rows: for Ada and Cleo, the comparison with the NULL list entry is unknown, so the NOT IN condition is not true. PostgreSQL’s comparison documentation specifies this behavior.

Corrected anti-joinExpress the exclusion as existence
SELECT e.name FROM employees e
WHERE NOT EXISTS (
  SELECT 1 FROM exclusions x WHERE x.employee_id=e.id
)
ORDER BY e.id;
Expected corrected output
name
Ada
Cleo

The NULL exclusion row cannot equal a non-null employee id, so it does not exclude Ada or Cleo. Confirm the intended meaning of a NULL exclusion entry before using any anti-join in a real task.

Related null error

Use IS NULL for a missing value.

SELECT employee_id FROM exclusions WHERE employee_id = NULL; -- no row
SELECT employee_id FROM exclusions WHERE employee_id IS NULL; -- one NULL row

= NULL yields unknown under ordinary SQL null comparison, so a WHERE filter does not retain it. IS NULL asks whether the value is missing. This is a query semantics issue, not a formatting preference. When explaining it aloud, distinguish false from unknown.

Mistake 2

DISTINCT removes duplicate values, not bad logic.

Suppose a report joins two orders to their line items and obtains repeated order headers. The wrong fix is SUM(DISTINCT order_total). If two legitimate orders both total 100, that expression returns 100, while the correct total is 200. You removed a repeated value, not an accidental repeated order.

Counterexample with equal legitimate amounts
order idorder totalitem rows
101002
111001
-- Correct when the measure belongs to order headers:
SELECT customer_id, SUM(order_total) AS revenue
FROM orders
GROUP BY customer_id;

Start from the measure’s source table or aggregate at the correct grain before joining. The joins and aggregation lesson provides a complete data setup and both outputs.

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.

Explore course options →

Mistake 3

A join can multiply a header amount.

Joined rows entering SUM
joined orderitemheader amount
101100
102100
11380

Summing the header amount on these three rows gives 280, even though the two orders total 180. A SQL engine is not “double-counting” by mistake; the query asked it to sum the repeated joined rows. A correct repair could sum order headers without the item join, or sum item amounts if item revenue is the actual question.

Predict the output after adding a third item to order 10. The bad header sum rises by another 100 even if the order header remains 100. That unseen check shows the query is tied to item count rather than customer revenue.

Reusable repair card

Correct the first broken assumption.

Mistake-to-method map
SymptomLikely causeRepair and test
Unexpectedly empty anti-listNOT IN subquery contains NULL.Use NOT EXISTS where it matches the business rule; test an explicit exclusion plus NULL.
Too-low SUM(DISTINCT)Two real entities share a numeric value.Aggregate by entity identity; test equal-valued orders.
Too-high joined SUMOne-to-many join repeats a header measure.Aggregate before the fan-out or use item measure; count joined rows.
Missing left rowsRight-table condition in WHERE.Move qualifying match rule into ON if every left row must remain.

After each correction, write an error log entry: “I assumed X; this input shows Y; the corrected rule is Z.” Then solve a fresh variation. The 20-question practice set gives varied inputs for checking transfer.

One-minute challenge

Can you predict the NULL edge case?

Remove the NULL row from exclusions and rerun the original NOT IN query. It now returns Ada and Cleo. That does not make NOT IN universally safe: a later NULL in the subquery can change its result again. Decide whether the exclusion column is constrained NOT NULL or prefer a query whose meaning remains clear when data changes.

Why is this an interview-worthy explanation?

The result depends on a data constraint that may not be visible in a short prompt. Naming the assumption, demonstrating the counterexample and choosing a robust form shows query reasoning rather than memorised syntax.

Why the empty result happens

Unknown is not the same as false.

Three-valued logic in the example
comparisontruth valueWHERE keeps row?
1 = 2falseno
1 = NULLunknownno
1 NOT IN (2, NULL)unknownno
2 NOT IN (2, NULL)falseno

A WHERE clause keeps rows only when its condition is true. For 1 NOT IN (2, NULL), the “different from 2” part is true, but the “different from NULL” part is unknown. True combined with unknown is unknown, so Ada’s row is not retained. For 2 NOT IN (2, NULL), the known equality already makes the NOT IN result false. The outcome is an empty result, but for two different reasons.

NOT EXISTS asks whether a matching exclusion row exists for each employee. The NULL exclusion row does not match a non-null employee id, so it has no excluding effect. That is why Ada and Cleo appear. If missing exclusion ids have a special business meaning, the query needs an explicit rule for them; no SQL operator can infer that meaning from NULL alone.

FAQ

Questions about this skill.

Is NOT IN always wrong?

No. It can be appropriate when null behavior and the subquery column constraints are understood. NOT EXISTS often expresses an anti-match more clearly.

Can DISTINCT ever be right?

Yes, when the requested result truly requires unique values. It is not a general repair for join cardinality.

What should I inspect first when a total is inflated?

Check the grain and row count before and after each join, then identify the table that owns the measure.

Continue with the SQL course

Make this skill reliable on new data.

Return to the course options and choose the next learning step.

Take the next step →
Scroll to Top