$ settings --editor

$ settings --general

$ save --settings

SQL for beginners

Linking tables with FOREIGN KEY #

You already used columns like customer_id and product_id to join tables together in the joins section. A FOREIGN KEY makes that relationship official: it tells the database that a column's values must match a primary key value in another table.

CREATE TABLE table_name (
    id PRIMARY KEY,
    other_table_id REFERENCES other_table(id)
);
  • other_table_id REFERENCES other_table(id): Declares that other_table_id refers to the id column of other_table.

This is exactly the same relationship that already exists between order_items.product_id and products.id, or between orders.customer_id and customers.id — a foreign key just makes it explicit in the table definition, so the database (and anyone reading the schema) knows the two tables are linked.


Exercise #

Write a command that creates a table called reviews with the columns id (as the primary key), product_id, rating, and comment, where product_id references the id column of the products table.

Tests #

  • The reviews table has a foreign key on product_id that references products(id).
Solution
CREATE TABLE reviews (
    id PRIMARY KEY,
    product_id REFERENCES products(id),
    rating,
    comment
);
Output will be displayed here