← SQL and databases

One-to-many and avoiding duplicated data

Where the pointer column goes.

Start this lesson

One customer can have many orders, but each order belongs to one customer. This is a one-to-many relationship, and the pointer (customer_id) goes in the "many" table, orders. When both sides can have many (an order has many products, a product is in many orders), you add a bridge table, like order_items, with a pointer to each side. Storing each fact once avoids a classic problem: if the customer's city were copied into every order, updating it in one place would leave old copies wrong elsewhere.

CREATE TABLE reviews (
  id INTEGER PRIMARY KEY,
  product_id INTEGER REFERENCES products(id),
  stars INTEGER,
  comment TEXT
);

One product can have many reviews, so each review points to its product. REFERENCES documents that product_id is a foreign key to products.id.

The school grades table is a bridge too: students take many courses, and courses have many students.