Chapter 9 · Lesson 6 of 9

Feel the Delete Anomaly

Experience a delete anomaly, where removing an order row would also erase the only record of a product, using GROUP BY and HAVING.

The flat table also has a delete problem. Product facts exist only because they are attached to order rows.

If a product appears in exactly one row, deleting that order would also delete the only stored record of that product. The database would forget that the product ever existed.

Try finding the products that are hanging by a single row.

Sample data

This lesson loads the orders_flat table (denormalized order lines) into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for orders_flat
CREATE OR REPLACE TABLE orders_flat (
    order_id INTEGER,
    customer_name VARCHAR,
    customer_email VARCHAR,
    customer_city VARCHAR,
    product_name VARCHAR,
    product_price DECIMAL(10,2),
    quantity INTEGER
  );

INSERT INTO orders_flat VALUES
    (1001, 'Alice Kim', '[email protected]', 'Berlin', 'Keyboard', 89.00, 1),
    (1002, 'Alice Kim', '[email protected]', 'Berlin', 'Mouse', 25.00, 2),
    (1003, 'Ben Fox', '[email protected]', 'Hamburg', 'Keyboard', 89.00, 1),
    (1004, 'Alice Kim', '[email protected]', 'Berlin', 'USB-C Hub', 45.00, 1),
    (1005, 'Cara Lane', '[email protected]', 'Munich', 'Webcam', 120.00, 1),
    (1006, 'Dan Reed', '[email protected]', 'Cologne', 'Desk Mat', 19.00, 1);

Practice challenge

Find the products that appear in exactly one order row. Return product_name and row_count, ordered by product_name.

Hint: GROUP BY product_name and keep only groups with COUNT(*) = 1.

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Normalization

See why well-designed databases split data into related tables, feel update, insert, and delete anomalies, and learn 1NF, 2NF, and 3NF.

  1. 01 · Why Normalization Matters
  2. 02 · Feel the Update Anomaly
  3. 03 · One Row to Update in a Good Schema
  4. 04 · Feel Why Packed Lists Break 1NF
  5. 05 · Order Items Feel Better
  6. 06 · Feel the Delete Anomaly
  7. 07 · Products Can Exist Without Orders
  8. 08 · 1NF, 2NF, and 3NF
  9. 09 · Why We Build Tables in Normal Forms

Related guides