Chapter 9 · Lesson 5 of 9

Order Items Feel Better

Model order lines in their own order_items table to satisfy first normal form, then find orders that contain a product with a JOIN.

In a normalized schema, each ordered product gets its own row in order_items. That means products are queryable with normal joins and filters.

Instead of asking, "Does this big text blob contain Keyboard?", you can say, "Which order_items rows point to the Keyboard product?" That is much cleaner and much more reliable.

Load the normalized tables and try the same business question again.

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

List the orders that contain the Keyboard product. Return order_id and product_name, ordered by order_id.

Hint: Join order_items to products and filter to product_name = 'Keyboard'.

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