Changing Data · Problem 118 of 118

Design a Wishlist Table

HardChanging DataShop data

Create a table wishlist for customers' wished products with exactly these columns, in this order:

  • customer_id (integer, not null, references customers)
  • product_id (integer, not null, references products)
  • added_on (text, not null)

A customer can wish for a product only once, so (customer_id, product_id) must be the primary key.

Check query. After your statements run, this query is run on the changed data and its result is compared with the expected one:

SELECT name, type, "notnull" AS not_null, pk
FROM pragma_table_info('wishlist')
ORDER BY cid;
Hint 1

A key over two columns is written after the columns: PRIMARY KEY (a, b).

Reference solution

CREATE TABLE wishlist (
  customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
  product_id  INTEGER NOT NULL REFERENCES products (product_id),
  added_on    TEXT NOT NULL,
  PRIMARY KEY (customer_id, product_id)
);

A composite primary key says "each combination appears at most once", which is exactly the rule of a wishlist or any many-to-many link table. The check query reads the table's structure (pragma_table_info): pk shows the position of each column inside the key (1 and 2 here, 0 for non-key columns). The foreign keys make sure nobody can wish for a product that does not exist.