Lesson 7 · Walkthrough · Milestone: Join + group

1581 step by step

This lesson solves 1581 slowly, one decision at a time. You'll build the query clause by clause in run order, see a second way to write it, and then see two versions that look right but hide a bug. At the end, you write it yourself.

What you will be able to do:

Step 0 · Read the question and the data

Visits(visit_id, customer_id) and Transactions(transaction_id, visit_id, amount). For each customer, count the visits that had no transaction. Output customer_id and count_no_trans. LeetCode's example:

Visits                      Transactions
visit_id customer_id        transaction_id visit_id amount
1        23                 2              5        310
2        9                  3              5        300
4        30                 9              5        200
5        54                 12             1        910
6        96                 13             2        970
7        54
8        54

Do it by hand first. Visits 1, 2 and 5 appear in Transactions. Visits 4, 6, 7 and 8 don't. So the answer is: customer 30 → 1, customer 54 → 2 (visits 7 and 8), customer 96 → 1. Solving a small example by hand before writing SQL is a good interview habit, because it gives you something to check your query against.

Every query output in this lesson comes from actually running the query on this data (SQLite in Python, which handles NULL in NOT IN, IS NULL and LEFT JOIN the same way MySQL does). The two "trap" rows later on are invented, and they are labelled.

Step 1 · Name the pattern

Two words in the question tell you which tools to use:

Which table goes on the left? We need to keep visits, because we're looking for visits that are missing a transaction. So Visits goes after FROM.

Step 2 · Build the query in run order

Write it in the order it runs, checking the rows after each clause. Click through:

1 · FROM Visits v LEFT JOIN Transactions t visit cust t.visit amount 1     23   1       910 2     9    2       970 4     30   NULL    NULL 5     54   5       310 5     54   5       300 5     54   5       200 6     96   NULL    NULL 7     54   NULL    NULL 8     54   NULL    NULL 9 rows: visit 5 appears 3 times 2 · WHERE t.visit_id IS NULL visit cust 4     30 6     96 7     54 8     54 4 rows; visit 5's copies are gone, so each visit appears only once 3 · GROUP BY + COUNT(*) customer count_no_trans 30       1 54       2 96       1 matches the hand answer

FROM Visits v LEFT JOIN Transactions t ON v.visit_id = t.visit_id. Every visit stays. Visit 5 has 3 transactions, so it becomes 3 rows. Visits 4, 6, 7 and 8 found no partner, so all their t. columns are NULL.

Add WHERE t.visit_id IS NULL. This keeps only the rows where the join found nothing: 4, 6, 7, 8. The only duplicated visit (5) is removed here.

Add GROUP BY v.customer_id and SELECT v.customer_id, COUNT(*) AS count_no_trans. Each customer bucket is counted. Check it against Step 0: it matches.

The finished query:

SELECT v.customer_id, COUNT(*) AS count_no_trans
FROM Visits v
LEFT JOIN Transactions t ON v.visit_id = t.visit_id   -- keep every visit
WHERE t.visit_id IS NULL                              -- only visits with no match
GROUP BY v.customer_id;                               -- one row per customer

Why test t.visit_id?

A row is only matched when v.visit_id = t.visit_id is TRUE, and a comparison with NULL is never TRUE. So on a matched row, t.visit_id can't be NULL. If it is NULL, the only possible reason is "no match". (t.transaction_id, the primary key, works too, because a primary key is never NULL.)

Why COUNT(*) and not COUNT(DISTINCT v.visit_id)?

The join only creates duplicates for visits that have transactions (visit 5 × 3), and step 2 removes exactly those rows. After the filter, each visit appears once, so DISTINCT would do nothing. In an interview, saying "I don't need DISTINCT, because the IS NULL filter removes the only duplicated rows" shows you traced where duplicates come from.

Step 3 · A second way: NOT EXISTS

Read the question literally: "visits for which no transaction exists".

SELECT v.customer_id, COUNT(*) AS count_no_trans
FROM Visits v
WHERE NOT EXISTS (                     -- keep v if the subquery finds NO row
  SELECT 1 FROM Transactions t
  WHERE t.visit_id = v.visit_id        -- "a transaction for THIS visit"
)
GROUP BY v.customer_id;

Step 4 · Two versions that look right but aren't

Both of these return the correct answer on LeetCode's example, so tests alone won't catch them. An interviewer can.

Trap 1: NOT IN

SELECT customer_id, COUNT(*) AS count_no_trans
FROM Visits
WHERE visit_id NOT IN (SELECT visit_id FROM Transactions)
GROUP BY customer_id;

x NOT IN (a, b, c) means x <> a AND x <> b AND x <> c. Suppose one transaction has no visit, so its visit_id is NULL (invented row: 14, NULL, 50):

4 NOT IN (5, 5, 5, 1, 2, NULL)
=  TRUE AND TRUE AND TRUE AND TRUE AND TRUE AND (4 <> NULL)
=  TRUE AND … AND UNKNOWN
=  UNKNOWN                      → WHERE drops visit 4

That happens to every visit. Real output with that one extra row: an empty result. No error, no warning. NOT EXISTS doesn't have this problem, because it never compares the visit id with the NULL.

Interview talking point. Since MySQL 8.0.17, both NOT IN (SELECT …) and NOT EXISTS (SELECT …) are rewritten internally as an antijoin. But the manual says the antijoin "cannot in most cases be applied if the expressions being compared are nullable" (MySQL manual). Nullable columns make NOT IN riskier and potentially slower.

Trap 2: testing a non-key column

… LEFT JOIN Transactions t ON v.visit_id = t.visit_id
WHERE t.amount IS NULL     -- ✗ amount, not the join column
…

t.amount IS NULL is TRUE in two situations: "there was no transaction" and "there was a transaction, but its amount is missing". Suppose visit 4 really had a transaction with no amount (invented row: 15, 4, NULL). The joined row still passes the test, so customer 30 is counted.

Real output: (30, 1), (54, 2), (96, 1). The correct answer with that row is (54, 2), (96, 1).

All four, three datasets (real runs)

QueryBaseTrap 1Trap 2
LEFT JOIN, t.visit_id IS NULL✓ (30,1) (54,2) (96,1)✓ (30,1) (54,2) (96,1)✓ (54,2) (96,1)
NOT EXISTS✓ (30,1) (54,2) (96,1)✓ (30,1) (54,2) (96,1)✓ (54,2) (96,1)
NOT IN✓ (30,1) (54,2) (96,1)✗ empty result✓ (54,2) (96,1)
LEFT JOIN, t.amount IS NULL✓ (30,1) (54,2) (96,1)✓ (30,1) (54,2) (96,1)✗ (30,1) (54,2) (96,1)

Base is LeetCode's example. Trap 1 adds a transaction whose visit_id is NULL. Trap 2 adds a real transaction on visit 4 whose amount is NULL. Only the first two queries survive both traps.

Practice from memory

Try not to scroll up.

1. In the LEFT JOIN solution, which table goes after FROM?

2. After Visits v LEFT JOIN Transactions t, which column should you test with IS NULL?

3. What is 4 NOT IN (5, 1, NULL) inside a WHERE?

4. The subquery's column contains a NULL. Which form still gives the right answer?

5. In the LEFT JOIN solution, do you need COUNT(DISTINCT v.visit_id)?

Fill in the blanks: NOT EXISTS on Lesson 5's tables

Students(id, name) and Lockers(student_id, locker_no). Return the names of students with no locker, using NOT EXISTS.

SELECT s.name
FROM Students s
WHERE  (
  SELECT 1 FROM Lockers l
  WHERE l. = s.
);

🏆 Challenge: solve 1581 yourself

Your task: close this page (really close it). Open 1581, choose MySQL, and write from memory:

  1. The LEFT JOIN + IS NULL version.
  2. The NOT EXISTS version.

If you get stuck, ask me for a hint in the chat instead of reopening this page. Recalling it on your own is what makes it stick.

Send me in the chat: both queries and both LeetCode results.

To pass:

Read next

Main source: Subqueries with EXISTS or NOT EXISTS (MySQL 8.0 manual). It's short, and the "store type present in no cities" example is this exact pattern.

💬 Is something still unclear? Ask me in the chat. I'm your tutor for this course.