SteelReed

Search

Search posts, questions…

4. Database & SQL

Databases: ERDs, foreign keys, JOINs and GROUP BY

Why a SQL report comes out three times too high or drops rows: ERDs and foreign keys for 1-1, 1-n and n-n, ON DELETE, JOINs, GROUP BY, HAVING, the logical order of SELECT, and how to review SQL an AI wrote.

17 Nov 20268 min readJunior

–

1. The problem

The dashboard says VIP customer Lan spent 45 million this month; accounting says 15 million. The SQL runs in 20 ms with no errors, and tests pass because each sample customer has one address. Lan has 5 orders and 3 delivery addresses.

2. Key idea

A JOIN doesn't "look up extra info" for each row. It builds a new table where each row is a matching pair, so the grain changes: before the JOIN a row is an order, after it a row is an (order, address) pair. Write down "each result row is one ___"; if a JOIN changes that sentence, re-check every SUM and COUNT after it.

Bug Symptom Root cause
Fan-out totals doubled, tripled two 1-n child tables joined at the same level
LEFT JOIN becomes INNER customers with no orders vanish a right-table condition in WHERE
COUNT(*) after LEFT JOIN customers with 0 orders show 1 counting the NULL row
Approach Use when Don't use when
INNER JOIN you only need rows with a match on both sides you must keep customers who never bought
LEFT JOIN keep every left row, including zeros the right-table condition sits in WHERE
Aggregate in a subquery, then join totals from two or more 1-n child tables there's only one child table
ON DELETE CASCADE children are meaningless without the parent, few rows orders, payments, enrollments

3. In SQL

SQL
-- Wrong: 5 orders × 3 addresses = 15 rows, SUM tripled
SELECT c.id, SUM(o.total) AS spent, COUNT(a.id) AS addresses
FROM customer c
JOIN orders o  ON o.customer_id = c.id
JOIN address a ON a.customer_id = c.id
GROUP BY c.id;
 
-- Right: reduce each child table to one row per customer, then join
SELECT c.id, COALESCE(o.spent, 0) AS spent, COALESCE(a.addresses, 0) AS addresses
FROM customer c
LEFT JOIN (SELECT customer_id, SUM(total) AS spent
           FROM orders WHERE status = 'PAID'
           GROUP BY customer_id) o ON o.customer_id = c.id
LEFT JOIN (SELECT customer_id, COUNT(*) AS addresses
           FROM address GROUP BY customer_id) a ON a.customer_id = c.id;

The status = 'PAID' condition sits in the subquery, so customers who never bought remain with spent = 0. JDBC, jOOQ and JPA all send the query as-is, so the bug survives; a Hibernate fetch join of two collections multiplies rows the same way.

ERDs, foreign keys and GROUP BY
  • 1-1: an FK with UNIQUE (a user's profile). 1-n: the FK on the many side (orders.customer_id). n-n: a junction table with two FKs and a composite primary key (enrollment(student_id, course_id)).
  • Crow's foot notation: a bar is "one", a crow's foot is "many", a circle is "may be none".
  • The default RESTRICT blocks deleting a parent with children. SET NULL when the child still makes sense without a parent (a course with no teacher yet).
  • PostgreSQL doesn't index FK columns automatically; MySQL InnoDB does.
  • Every SELECT column must be in GROUP BY, in an aggregate, or functionally dependent on a grouped primary key (ONLY_FULL_GROUP_BY is on by default since MySQL 5.7).
  • SELECT aliases can't be used in WHERE because WHERE runs first; MySQL allows them in HAVING, PostgreSQL doesn't.

4. Working with AI

Hand to AI: DDL from an agreed ERD, data with edge cases (a customer with 0 orders, one with 3 addresses), draft report queries, explaining EXPLAIN.

Check yourself in AI-written code:

  • The sentence "each result row is one ___" appears in a comment or the PR description.
  • No two 1-n child tables are joined and then SUM/COUNTed at the same level.
  • After a LEFT JOIN, right-table conditions are in ON, and counting uses COUNT(right_table_column).
  • Important tables don't use ON DELETE CASCADE; every CASCADE has a written reason.

5. Exercises

Exercise 1: Review an AI-written report

Requirement: "every customer, with paid-order revenue since the start of 2026 and support ticket count". The AI says "it uses LEFT JOIN, so no customer is missing". Find the bugs, give test data, fix it.

SQL
SELECT c.name, SUM(o.total) AS revenue, COUNT(t.id) AS tickets
FROM customer c
LEFT JOIN orders o ON o.customer_id = c.id
LEFT JOIN ticket t ON t.customer_id = c.id
WHERE o.status = 'PAID' AND o.created_at >= '2026-01-01'
GROUP BY c.id, c.name;
Solution 1
  • WHERE o.status = ... drops every customer with no orders, turning the first LEFT JOIN into an INNER JOIN.
  • Orders and tickets are two 1-n children at the same level: 2 orders and 3 tickets make 6 rows; revenue triples, tickets doubles.
  • Test data: customer A has 2 PAID orders (100 + 200) and 3 tickets; customer B has nothing. Expected A = (300, 3), B = (0, 0). The AI's query gives A = (900, 6) and no B.
  • Fix as in section 3: aggregate orders (with the PAID and date conditions inside) and ticket in two subqueries, LEFT JOIN them to customer, COALESCE to 0.

Exercise 2: Read a data-deletion incident

An admin runs DELETE FROM teacher WHERE id = 17 for a teacher who left, with no error. An hour later: 6 courses, 3,200 enrollment rows and 41,000 lesson_progress rows are gone. Last week's AI-written migration set ON DELETE CASCADE on every FK "to keep things clean". Diagnose it, say what to do in 15 minutes, fix the root cause.

Solution 2
  • Diagnosis: a cascade chain teacher → course → chapter → lesson → lesson_progress, plus course → enrollment. The database did exactly what was declared.
  • 15 minutes: disable teacher deletion; restore from backup plus binlog up to just before the DELETE (point-in-time recovery) into a separate instance, then copy the lost rows back.
  • Root fix: course.teacher_id uses SET NULL or RESTRICT; FKs to enrollment and lesson_progress stay at the default RESTRICT. Departing teachers are soft-deleted (status = 'INACTIVE').

Summary

  • Each relationship becomes a foreign key; n-n uses a junction table.
  • A JOIN changes the grain; say what a row is before aggregating.
  • Two 1-n children: aggregate each first, then join.
  • LEFT JOIN: right-table conditions in ON, count COUNT(right_table_column).
  • CASCADE only for children that are meaningless without the parent.

Further reading: Normalization.

Practice interview questions on this topic

All SQL & Query Tuning questions →All Data Modeling & Scaling questions →

Loading comments…