Enforcing uniqueness with PRIMARY KEY #
A PRIMARY KEY marks a column as the unique identifier for each row in a table. No two rows can ever share the same primary key value, and the database will reject any attempt to insert a duplicate one.
CREATE TABLE table_name (
id PRIMARY KEY,
column_2,
column_3
);
id PRIMARY KEY: Marks theidcolumn as the table's primary key.
Every table you design should have a primary key. It is what lets you (and other tables, through foreign keys, which you will learn about next) reliably refer to one exact row.
Exercise #
Write a command that creates a table called reviews with the columns id, product_id, rating, and comment, where id is the primary key.
Tests #
- The
reviewstable has the columnsid,product_id,rating, andcomment. - The
idcolumn is set as the primary key.
Solution
CREATE TABLE reviews (
id PRIMARY KEY,
product_id,
rating,
comment
);
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity