Chapter 9 · Lesson 7 of 9

Products Can Exist Without Orders

See how a separate products table fixes insert and delete anomalies, and find products that have never been ordered with a LEFT JOIN.

A normalized schema fixes both insert and delete anomalies by giving products their own table.

That means a product can exist before the first order is placed, and it can still exist after the last order is deleted. Product facts are no longer tied to the survival of order rows.

In the sample below, Monitor Stand exists in the products catalog but has not been ordered yet. See if you can find it.

Sample data

This lesson loads the customers, products, orders, and order_items tables into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for customers, products, orders, order_items
CREATE OR REPLACE TABLE customers (
    customer_id INTEGER,
    customer_name VARCHAR,
    customer_email VARCHAR,
    customer_city VARCHAR
  );

INSERT INTO customers VALUES
    (1, 'Alice Kim', '[email protected]', 'Berlin'),
    (2, 'Ben Fox', '[email protected]', 'Hamburg'),
    (3, 'Cara Lane', '[email protected]', 'Munich'),
    (4, 'Dan Reed', '[email protected]', 'Cologne');

CREATE OR REPLACE TABLE products (
    product_id INTEGER,
    product_name VARCHAR,
    product_price DECIMAL(10,2)
  );

INSERT INTO products VALUES
    (1, 'Keyboard', 89.00),
    (2, 'Mouse', 25.00),
    (3, 'USB-C Hub', 45.00),
    (4, 'Webcam', 120.00),
    (5, 'Desk Mat', 19.00),
    (6, 'Monitor Stand', 59.00);

CREATE OR REPLACE TABLE orders (
    order_id INTEGER,
    customer_id INTEGER,
    order_date DATE
  );

INSERT INTO orders VALUES
    (1001, 1, '2024-01-05'),
    (1002, 1, '2024-01-07'),
    (1003, 2, '2024-01-09'),
    (1004, 1, '2024-01-10'),
    (1005, 3, '2024-01-14'),
    (1006, 4, '2024-01-15');

CREATE OR REPLACE TABLE order_items (
    order_id INTEGER,
    product_id INTEGER,
    quantity INTEGER
  );

INSERT INTO order_items VALUES
    (1001, 1, 1),
    (1002, 2, 2),
    (1003, 1, 1),
    (1004, 3, 1),
    (1005, 4, 1),
    (1006, 5, 1);

Practice challenge

Find the products that have not been ordered yet. Return product_name and times_ordered, ordered by product_name.

Hint: LEFT JOIN products to order_items, then group by product_name and count matching order_items rows.

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