Primary Keys
A primary key is a column (or combination of columns) that uniquely identifies each row in a table. It ensures that each row has a unique key value and that the key cannot contain NULL
.
Why Use a Primary Key?
Primary keys are used to:
- Guarantees each record is unique
- Prevents duplicate rows
- Enables accurate referencing between tables (e.g. linking clients to orders)
Defining a Primary Key
You can define a primary key when creating a table by using the PRIMARY KEY
constraint.
CREATE TABLE orders ( order_id INT PRIMARY KEY, client_id INT, amount REAL, order_date TEXT );
In this example, order_id
is the primary key, and each order must have a unique ID.
Composite Primary Key
Sometimes, one column isn't enough to uniquely identify a row. You can combine columns to form a composite primary key.
CREATE TABLE order_items ( order_id INT, product_id INT, quantity INT, PRIMARY KEY (order_id, product_id) );
This ensures that each product appears only once in an order, preventing duplicates for the same product in the same order.
Why is a primary key important in SQL tables?
It allows NULL values in the column
It makes columns optional
It ensures each row has a unique, non-null identifier
It formats the table for printing
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Tables
Execution Result