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 thatother_table_idrefers to theidcolumn ofother_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
reviewstable has a foreign key onproduct_idthat referencesproducts(id).
Solution
CREATE TABLE reviews (
id PRIMARY KEY,
product_id REFERENCES products(id),
rating,
comment
);
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity