Identifying Keys
in SQL
Learn how primary keys and foreign keys organize relational databases, enforce data integrity, and connect tables together.
What Is a Key?
In a relational database, a key is a column (or set of columns) that serves a special purpose: it either uniquely identifies each row in a table or links one table to another.
Why Keys Matter
The Two Main Key Types
Primary Key Rules
Foreign Key Rules
How Tables Connect
Primary vs Foreign Key
| Property | Primary Key | Foreign Key |
|---|---|---|
| Purpose | Uniquely identifies a row | References a row in another table |
| Allows NULL? | No | Yes (unless restricted) |
| Allows duplicates? | No | Yes |
| How many per table? | Exactly one | Zero or many |
| Auto-indexed? | Yes (automatic) | Varies by DBMS |
How to Identify Keys
Declaring Keys in SQL
Example 1: Library Database
Example 2: E-Commerce Schema
Example 3: Composite Primary Key
Candidate Keys & Unique Keys
Before choosing a primary key, you may find multiple columns that could uniquely identify rows. Each of these is a candidate key.
Common Mistakes
Key Types Summary
| Key Type | Unique? | NOT NULL? | Per Table |
|---|---|---|---|
| Primary Key | Yes | Yes | Exactly 1 |
| Foreign Key | No | No (optional) | 0 or many |
| Candidate Key | Yes | Yes | 1 or more |
| Unique Key | Yes | No (allows NULL) | 0 or many |
| Composite Primary Key | Yes (combined) | Yes | 0 or 1 |
Question 1 of 5
Which property is required of a primary key but not of a foreign key?
Question 2 of 5
Table: Orders
order_id (INT, PRIMARY KEY)
customer_id (INT)
order_date (DATE)
total (DECIMAL)
Table: Customers
customer_id (INT, PRIMARY KEY)
name (VARCHAR)
email (VARCHAR)
In the schema above, what role does customer_id play in the Orders table?
Question 3 of 5
A table called Enrollment uses the combination of student_id and course_id as its primary key. What type of key is this?
Question 4 of 5
A student tries to insert a row into the Enrollments table with a student_id value of 999, but no student with that ID exists in the Students table. What happens?
Question 5 of 5
Which of the following is the worst choice for a primary key?