Primary Key, Foreign Key and Constraints in SQL, With Examples

6 min read

A primary key is the column, or set of columns, that uniquely identifies each row in a table: it can never repeat and never be NULL. A foreign key is a column in another table that must hold a value that exists in that primary key. Together they are how a relational database links tables, so that every order points at a customer who really exists.

Keys are one kind of constraint, a rule the database enforces on every insert and update. This lesson covers the keys in depth, the other constraints that sit alongside them, and the part most tutorials skip: what an analyst should check when the database was never told to enforce them.

The constraints at a glance

The table lists the six constraints you will meet, with the syntax for declaring each one inside CREATE TABLE.

Constraint What it enforces Syntax Example
PRIMARY KEY Unique and never NULL; one per table column type PRIMARY KEY customer_id INT PRIMARY KEY
FOREIGN KEY Value must exist in the referenced table’s key FOREIGN KEY (col) REFERENCES table (col) FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
UNIQUE No two rows share the value; several allowed per table column type UNIQUE email VARCHAR(100) UNIQUE
NOT NULL The column must always have a value column type NOT NULL name VARCHAR(100) NOT NULL
CHECK The value must satisfy a condition CHECK (condition) CHECK (amount > 0)
DEFAULT Supplies a value when none is given column type DEFAULT value status VARCHAR(20) DEFAULT ‘placed’

Strictly, DEFAULT does not reject anything, but it is declared the same way and usually taught with the rest.

The tables used throughout

The examples follow a Bengaluru D2C home-goods brand with two tables. Each table is built with one CREATE TABLE statement; the clauses are listed one per row.

The customers table:

Clause SQL
Start CREATE TABLE customers (
Primary key customer_id INT PRIMARY KEY,
Required name name VARCHAR(100) NOT NULL,
No duplicate emails email VARCHAR(100) UNIQUE,
End city VARCHAR(50) )

The orders table, with a foreign key back to customers:

Clause SQL
Start CREATE TABLE orders (
Primary key order_id INT PRIMARY KEY,
Link column customer_id INT NOT NULL,
Positive amounts only amount DECIMAL(10,2) CHECK (amount > 0),
Default status status VARCHAR(20) DEFAULT ‘placed’,
Foreign key CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (customer_id) )

Naming the constraint, as with fk_orders_customer here, is optional but worth doing. When an insert fails, the error message quotes the name, and fk_orders_customer tells you what broke far faster than a name the database generated.

After a few inserts the tables hold:

customer_id name email city
101 Kavya Iyer [email protected] Bengaluru
102 Rahul Desai [email protected] Pune
103 Sana Sheikh [email protected] Hyderabad
order_id customer_id amount status
5001 101 1499.00 placed
5002 102 899.00 shipped
5003 101 2199.00 placed

What the constraints refuse

Here is what happens when you try to break each rule. The exact error text varies by database; the outcome does not.

Attempted statement Result Constraint that stopped it
INSERT INTO customers VALUES (101, ‘Arjun Rao’, ‘[email protected]’, ‘Mysuru’) Rejected PRIMARY KEY: 101 already exists
INSERT INTO customers VALUES (NULL, ‘Arjun Rao’, ‘[email protected]’, ‘Mysuru’) Rejected PRIMARY KEY: cannot be NULL
INSERT INTO customers VALUES (104, ‘Arjun Rao’, ‘[email protected]’, ‘Mysuru’) Rejected UNIQUE on email
INSERT INTO orders (order_id, customer_id, amount) VALUES (5004, 107, 649) Rejected FOREIGN KEY: no customer 107
INSERT INTO orders (order_id, customer_id, amount) VALUES (5004, 103, -649) Rejected CHECK (amount > 0)
INSERT INTO orders (order_id, customer_id, amount) VALUES (5004, 103, 649) Accepted, status set to placed DEFAULT fills status
DELETE FROM customers WHERE customer_id = 101 Rejected FOREIGN KEY: orders 5001 and 5003 still point at 101

The last row surprises people. A foreign key protects both directions: you cannot add an order for a customer who does not exist, and you cannot remove a customer who still has orders, unless you tell the database what to do with those orders.

ON DELETE: what happens to the child rows

The ON DELETE clause on a foreign key decides what happens to orders when their customer is deleted. You add it after REFERENCES, for example REFERENCES customers (customer_id) ON DELETE CASCADE.

Option What happens to orders 5001 and 5003 when customer 101 is deleted
NO ACTION or RESTRICT (the default) The delete is refused while any order points at 101
CASCADE Both orders are deleted along with the customer
SET NULL Both orders stay, with customer_id set to NULL (the column must allow NULL)
SET DEFAULT Both orders stay, with customer_id set to the column’s default

CASCADE is convenient and dangerous. On a real order history, deleting one customer can silently remove years of revenue from every report built on those orders. Most companies keep the default and mark customers inactive instead of deleting them. ON UPDATE takes the same options and applies when a primary key value changes, which in a well-designed table should be almost never.

Composite keys: when one column is not enough

Some tables have no single column that is unique. An order_items table holds one row per product per order, so order_id repeats (an order has several products) and product_id repeats (a product appears in many orders). The pair is unique.

order_id product_id quantity
5001 P10 2
5001 P14 1
5003 P10 1

The key is declared on both columns together: PRIMARY KEY (order_id, product_id). Inserting a second row for order 5001 and product P10 is rejected; the business should increase the quantity instead. Here order_id is also a foreign key to orders, so one column can belong to the primary key and to a foreign key at the same time.

Primary key vs unique key vs foreign key

This comparison is a standard interview question, and the differences are precise.

Primary key Unique key Foreign key
Purpose Identifies each row Prevents duplicates in a column that is not the identifier Links a row to a row in another table
How many per table One Any number Any number
NULL allowed Never Yes (how many depends on the database) Yes, unless also NOT NULL
Duplicates allowed Never Never among non-NULL values Yes; many orders can share a customer_id
Index created automatically Yes Yes Not in PostgreSQL or SQL Server; yes in MySQL

Two more terms you will hear. A natural key is a real-world value used as the key, such as a PAN or GSTIN. A surrogate key is a number the database generates, such as customer_id. Most teams use surrogate keys, because real-world values change, get typed wrongly and occasionally turn out not to be unique, and keep the natural value under a UNIQUE constraint instead.

Where MySQL, PostgreSQL and SQL Server differ

Point MySQL PostgreSQL SQL Server
Auto-generated key id INT AUTO_INCREMENT PRIMARY KEY id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, or SERIAL id INT IDENTITY(1,1) PRIMARY KEY
Foreign keys enforced Only on InnoDB tables, the default engine; ignored on MyISAM Yes Yes
CHECK enforced From 8.0.16; earlier versions accept it and ignore it Yes Yes
NULLs in a UNIQUE column Many allowed Many allowed (version 15 adds NULLS NOT DISTINCT to allow one) Only one NULL allowed
ON DELETE options RESTRICT, CASCADE, SET NULL, NO ACTION NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT NO ACTION, CASCADE, SET NULL, SET DEFAULT
Drop a foreign key ALTER TABLE orders DROP FOREIGN KEY fk_orders_customer ALTER TABLE orders DROP CONSTRAINT fk_orders_customer ALTER TABLE orders DROP CONSTRAINT fk_orders_customer

The MySQL CHECK row is worth remembering. A table created on MySQL 5.7 with CHECK (amount > 0) happily stores negative amounts, and nothing tells you.

Why analysts should check keys, not trust them

Here is the part that matters most if your job is querying rather than designing. Many analytics warehouses, including Snowflake, BigQuery and Amazon Redshift, let you declare primary and foreign keys but do not enforce them. The declaration is documentation. Data loaded from spreadsheets, APIs and old systems arrives without checks, so the duplicates and orphans a key would have refused are often already in the table.

Two queries catch most of it. First, duplicate keys: SELECT customer_id, COUNT(*) FROM customers GROUP BY customer_id HAVING COUNT(*) > 1. Any row returned is a key that is not unique, and every join on it will multiply rows.

Second, orphans. Suppose the warehouse copy of orders also holds order 5005 for customer 107, which an enforced foreign key would have refused.

Query: SELECT o.order_id, o.customer_id, o.amount FROM orders o LEFT JOIN customers c ON o.customer_id = c.customer_id WHERE c.customer_id IS NULL

order_id customer_id amount
5005 107 649.00

Order 5005 would vanish from any INNER JOIN between the two tables, and revenue by city would be short by 649 rupees with no warning. Run both checks before you build anything on a new table. The SQL joins guide explains why a LEFT JOIN with an IS NULL filter finds these rows.

Keys are also where good table design starts. Splitting data into linked tables so each fact is stored once is called normalization, which we cover separately. For how data types and the main database families fit around these constraints, read our guide to SQL database types, and for adding a key to a table that already exists, the ALTER TABLE section of DDL commands in SQL.

Frequently asked questions

What is the difference between a primary key and a foreign key?

A primary key uniquely identifies each row in its own table and can never be NULL or repeat. A foreign key is a column in another table that refers to that primary key, and its values must exist there. In an orders table, order_id is the primary key and customer_id is a foreign key pointing at the customers table.

Can a table have more than one primary key?

No. A table has exactly one primary key, but that key can be made of several columns, which is called a composite key. If you need other columns to be unique as well, such as email, use UNIQUE constraints on them, and a table can have as many of those as you like.

Can a foreign key be NULL?

Yes, unless the column is also declared NOT NULL. A NULL foreign key means the row is not linked to anything, which the database allows. Whether it should be allowed is a design decision: an order with no customer is probably a bug, while an employee with no manager is the person at the top.

Can a primary key be NULL?

No. Every database rejects a NULL in a primary key column, because NULL means the value is unknown and an unknown value cannot identify a row. Declaring a column PRIMARY KEY automatically makes it NOT NULL as well.

What is ON DELETE CASCADE?

It is an option on a foreign key that deletes the child rows automatically when the parent row is deleted. If orders reference customers with ON DELETE CASCADE, deleting a customer also deletes all their orders. Without it, the default is to refuse the delete while child rows exist.

What is the difference between a primary key and a unique key?

Both prevent duplicate values, but a table has only one primary key and it can never be NULL, while it can have many unique keys and those usually accept NULL. The primary key is the row’s identifier and the column other tables point at with foreign keys; a unique key just stops repeats in some other column, such as a phone number.

Learn SQL from the table design up

Keys are a short topic with a long reach: almost every wrong join, double-counted total and missing row in a report traces back to a key that was not unique or a relationship nobody enforced.

SkilloVilla’s SQL: Beginner to Advanced course starts with creating databases and tables and runs through joins, aggregation and advanced SQL statements, taught in live classes with mentor support and practice on SQL playgrounds. For SQL inside a complete analyst programme with Python and placement support, see the Data Analytics with Python track.

Statistics for Data Analytics: The Topics an Analyst Needs,…

Statistics for data analytics: the topics an analyst uses, grouped into a learning path, with the business question each answers and a study plan.
SkilloVilla Team
6 min read

Standard Deviation and Variance for Data Analysts, With Worked…

Standard deviation and variance for data analysts: population vs sample (n vs n-1), a worked calculation, Excel and SQL functions, and what it means.
SkilloVilla Team
7 min read

Power BI vs Tableau: Which to Learn for an…

Power BI vs Tableau compared for Indian job-seekers: job demand, cost, learning curve, data prep, Mac support and sharing, with a side-by-side table.
SkilloVilla Team
5 min read

Leave a Reply