Backend & Databases Comparisonbeginner

Primary Key vs Foreign Key: Differences

A primary key identifies each row in its own table. A foreign key points to a primary key in another table. See both in two small tables, with the errors each one blocks.

6 min read

Our verdict in 30 seconds

A primary key is a column (or set of columns) that uniquely identifies each row in a table; it cannot repeat or be NULL, and a table has only one. A foreign key is a column in one table that refers to the primary key (or another unique key) of another table; it can repeat, can usually be NULL, and a table can have many. The primary key gives each row an identity, and the foreign key builds the link between tables.

On This Page

Primary key vs foreign key is about two different jobs. A primary key gives every row in a table its own identity, like a roll number. A foreign key is a column that points to a primary key in another table, like a department number written on an employee's record. One identifies; the other connects.

Primary key vs foreign key: the difference table

Point Primary key Foreign key
Job Uniquely identifies each row Links a row to a row in another table
Duplicates Not allowed Allowed
NULL values Not allowed Allowed, unless you add NOT NULL
How many per table One (can span several columns) Zero, one or many
Refers to Nothing; it is the target A primary key or unique key in the parent table
Index Created automatically MySQL InnoDB creates one if missing; many databases do not
Blocks Duplicate or missing IDs Links to rows that do not exist
Table role Parent side of a relationship Child side of a relationship

In one line: the primary key says "this is me". The foreign key says "I belong to that".

Two small tables showing both keys

Here are a departments table and an employees table. Each department has a primary key dept_id. Each employee has a primary key emp_id and a foreign key dept_id that points to departments.

PRAGMA foreign_keys = ON;  -- SQLite only: turns on foreign key checks

CREATE TABLE departments (
  dept_id INTEGER PRIMARY KEY,
  dept_name VARCHAR(30) NOT NULL
);

CREATE TABLE employees (
  emp_id INTEGER PRIMARY KEY,
  emp_name VARCHAR(30) NOT NULL,
  dept_id INTEGER,
  FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);

INSERT INTO departments VALUES (10, 'Development'), (20, 'Testing'), (30, 'Support');

INSERT INTO employees VALUES
  (101, 'Asha', 10),
  (102, 'Ravi', 20),
  (103, 'Meena', 10),
  (104, 'Kiran', NULL);

The data now looks like this:

departments (parent table)

dept_id (PK) dept_name
10 Development
20 Testing
30 Support

employees (child table)

emp_id (PK) emp_name dept_id (FK)
101 Asha 10
102 Ravi 20
103 Meena 10
104 Kiran NULL

Notice three things in the foreign key column:

  1. 10 appears twice. Asha and Meena are both in Development. Duplicates are normal in a foreign key.
  2. Kiran has NULL. He has not been given a department yet. That is allowed because dept_id in employees is not NOT NULL.
  3. Every non-NULL value exists in departments. That is the rule the foreign key enforces.

The link lets you join the tables:

SELECT e.emp_name, d.dept_name
FROM employees e
JOIN departments d ON d.dept_id = e.dept_id
ORDER BY e.emp_id;

Result:

emp_name   dept_name
Asha       Development
Ravi       Testing
Meena      Development

Kiran is missing because an inner join keeps only matching rows, and NULL matches nothing. Use a LEFT JOIN to keep him; inner join vs outer join explains why.

What each key blocks

Keys are rules, and rules show their value when you break them. All three statements below fail.

1. Duplicate primary key:

INSERT INTO departments VALUES (10, 'Design');
SQLite: UNIQUE constraint failed: departments.dept_id
MySQL:  ERROR 1062 (23000): Duplicate entry '10' for key 'departments.PRIMARY'

Department 10 already exists, so a second row with the same ID is refused.

2. Foreign key pointing to nothing:

INSERT INTO employees VALUES (105, 'Sai', 40);
SQLite: FOREIGN KEY constraint failed
MySQL:  ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (...)

There is no department 40, so the database will not create an employee who belongs to it.

3. Deleting a parent that still has children:

DELETE FROM departments WHERE dept_id = 20;
SQLite: FOREIGN KEY constraint failed
MySQL:  ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (...)

Ravi still points to department 20. Deleting it would leave him linked to a department that no longer exists, an orphan row. Department 30 has no employees, so DELETE FROM departments WHERE dept_id = 30; works.

Common mistake: Testing foreign keys in SQLite and seeing no error. SQLite turns foreign key checks off by default for each connection, so a bad insert like (105, 'Sai', 40) is silently accepted. Run PRAGMA foreign_keys = ON; first. MySQL with the InnoDB engine, PostgreSQL, SQL Server and Oracle check foreign keys by default.

ON DELETE: choosing what happens to child rows

By default, the database blocks a parent delete when child rows exist, as above. You can choose a different rule when you create the foreign key:

Rule What happens when the parent row is deleted
Default (NO ACTION / RESTRICT) The delete is refused while children exist
ON DELETE CASCADE Child rows are deleted too
ON DELETE SET NULL The foreign key in child rows becomes NULL

For example:

FOREIGN KEY (dept_id) REFERENCES departments(dept_id) ON DELETE SET NULL

CASCADE is handy for things like order items that mean nothing without their order. Use it carefully: one delete can remove many rows across tables.

Composite keys and natural vs surrogate keys

A primary key can use more than one column. In a table of marks, one student has many subjects, and one subject has many students, but each student has only one mark per subject:

CREATE TABLE marks (
  roll_no INTEGER,
  subject VARCHAR(20),
  score INTEGER,
  PRIMARY KEY (roll_no, subject)
);

The pair (roll_no, subject) must be unique; each column alone can repeat. In such a table, roll_no is often also a foreign key to a students table, so one column can be part of the primary key and a foreign key at the same time.

Two more terms you may hear:

  • Natural key: a real-world value used as the key, such as an email address or PAN number.
  • Surrogate key: a made-up ID such as emp_id with AUTO_INCREMENT in MySQL. Most teams prefer surrogate keys, because real-world values can change.

Pro tip: Add an index on foreign key columns you join or filter on often. PostgreSQL and SQL Server do not create one for you, and joins on a large table without it can be slow. See SQL indexes explained.

Keys in SQL: the short family list

Key Meaning
Super key Any set of columns that uniquely identifies a row
Candidate key A minimal super key; a table may have several
Primary key The candidate key you choose as the main identity
Alternate key A candidate key not chosen as primary, often made UNIQUE
Composite key A key made of two or more columns
Foreign key A column that refers to a key in another table

For example, in a students table, both roll_no and email could identify a student. Both are candidate keys. If you choose roll_no as the primary key, email becomes an alternate key.

For freshers: how to answer in an interview

You can say this in about 30 seconds:

"A primary key uniquely identifies each row in a table. It cannot be NULL or repeat, and a table has one. A foreign key is a column in a child table that refers to the primary key of a parent table. It can repeat, can be NULL, and a table can have many. Primary keys give identity; foreign keys keep relationships valid by blocking orphan rows."

Then expect follow-ups on composite keys, ON DELETE CASCADE and unique vs primary key. Practise with SQL constraints interview questions, and learn how keys fit table design in database normalization and DBMS vs RDBMS. CodeBegun teaches SQL in the data analytics course, in Madhapur, Hyderabad and live online.

Interview note: A common trick is "Can a foreign key refer to its own table?" Yes. In an employees table, a manager_id column can be a foreign key to emp_id in the same table. This is called a self-referencing foreign key.

Frequently Asked Questions

Can a foreign key be NULL?
Yes, unless you add NOT NULL. A NULL foreign key means the row is not linked to anything yet, such as an employee who has not been given a department.
Can a foreign key have duplicate values?
Yes. Many child rows can point to the same parent. Many employees can belong to department 10, so 10 appears many times in the foreign key column.
Can a table have more than one primary key?
No. A table has only one primary key, but that key can be made of several columns, called a composite key. A table can have many foreign keys and many UNIQUE constraints.
Must a foreign key refer to a primary key?
It must refer to a column that is guaranteed unique in the parent table. Usually that is the primary key, but a column with a UNIQUE constraint also works in MySQL, PostgreSQL, SQL Server and Oracle.
What is the difference between a primary key and a unique key?
Both block duplicate values. A table has one primary key and its columns cannot be NULL. A table can have several unique keys, and most databases allow NULL in a unique column; how many NULLs are allowed varies by database.

Want to Build Your Career in Data Analytics with AI?

Join CodeBegun and train with working industry engineers — Check the Data Analyst training details

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 5 December 2026 LinkedIn

More comparisons

View all
Chat with us