1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL Primary Key vs Foreign Key: Differences and Examples

A primary key names each row. A foreign key points to a row in another table. This guide on primary key vs foreign key shows both in runnable SQL, with a comparison table and the mistakes that corrupt data.

8 min read
Primary key vs foreign key in SQL: differences, examples and comparison table

Key takeaways

  • A primary key uniquely identifies a row in its own table and can never be NULL.
  • A foreign key links a row to a parent row in another table and may be NULL.
  • A table has one primary key (possibly several columns) but can have many foreign keys.
  • Always test the failure cases: duplicate keys, orphan rows and delete rules.

Open any database and you will see two kinds of columns doing quiet but critical work. One decides which row is which. The other decides which rows belong together. The primary key vs foreign key question is really about those two jobs.

Mix them up and you get duplicate customers, orders that point to nobody and reports that no one trusts. Get them right and the database protects your data for you.

Below you will find short definitions, a side-by-side table and a small script you can run in any SQL tool. If joins are new to you, read SQL joins explained next, because keys are what make joins possible.

Primary key vs foreign key, part one: the primary key

A primary key is a column, or a set of columns, whose value is different for every row in a table. It is how the database, and your code, finds exactly one row. According to the PostgreSQL constraints documentation, a primary key is the combination of a unique constraint and a not-null constraint, and the database creates a unique index for it automatically.

  • Values must be unique.
  • Values cannot be NULL.
  • A table can have only one primary key, but it may span more than one column (a composite key).
  • Good keys rarely change. An auto-generated id is the usual choice.

Primary key vs foreign key, part two: the foreign key

A foreign key is a column in one table (the child) whose values must match a key in another table (the parent). It is the database’s way of saying “this order must belong to a real customer”. The rule is called referential integrity.

  • Values may repeat. Many orders can belong to one customer.
  • Values may be NULL, which means “no parent yet”, unless you add NOT NULL.
  • A table can have several foreign keys.
  • It normally points to a primary key, though most databases also allow a column with a unique constraint.

Primary key vs foreign key: comparison table

Feature Primary key Foreign key
Purpose Identify a row Link rows across tables
Uniqueness Always unique Duplicates allowed
NULL values Not allowed Allowed unless NOT NULL is added
Per table Exactly one Zero, one or many
Integrity type Entity integrity Referential integrity
Automatic index Yes, in the major databases Depends on the database
Can it be the other? Yes, a primary key column can also be a foreign key (one-to-one tables) Yes, as above

A runnable primary key vs foreign key example

This script works in SQLite, PostgreSQL and MySQL with minor changes. We model customers and their orders.

CREATE TABLE customers (
  customer_id INTEGER PRIMARY KEY,
  email       VARCHAR(120) NOT NULL UNIQUE
);

CREATE TABLE orders (
  order_id    INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL,
  total       DECIMAL(10,2) NOT NULL,
  FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);

INSERT INTO customers VALUES (1, 'asha@example.com'), (2, 'ben@example.com');
INSERT INTO orders VALUES (100, 1, 49.90), (101, 1, 12.00), (102, 2, 30.00);

Here customer_id in customers is the primary key. The same name in orders is the foreign key. Now try to break the rules:

-- duplicate primary key: rejected
INSERT INTO customers VALUES (1, 'copy@example.com');

-- orphan row, no customer 99: rejected
INSERT INTO orders VALUES (103, 99, 5.00);

-- valid join using the key pair
SELECT c.email, o.order_id, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id;

SQLite note: foreign key checks are off by default in SQLite. Run PRAGMA foreign_keys = ON; on every connection, as the SQLite foreign key documentation explains, or the orphan insert above will quietly succeed.

What happens when the parent row is deleted?

You choose the behaviour when you create the foreign key. The standard options are:

Rule Effect when a customer is deleted
RESTRICT / NO ACTION Delete is blocked while orders exist
CASCADE The customer’s orders are deleted too
SET NULL Orders stay, with customer_id set to NULL
SET DEFAULT Orders get the column’s default (not supported everywhere)
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
  ON DELETE RESTRICT ON UPDATE CASCADE

Use CASCADE with care. It is convenient for child data that has no meaning alone, such as order lines, and dangerous for financial history.

Indexing: the part beginners miss

Performance is where the primary key vs foreign key gap shows most clearly.

The primary key gets an index automatically. Foreign key columns do not always. PostgreSQL does not create one for the referencing column, so joins and parent deletes can become slow on large tables unless you add it yourself. MySQL’s InnoDB requires an index on the foreign key columns and creates one if missing. Check your own database’s documentation before you assume.

CREATE INDEX idx_orders_customer ON orders (customer_id);

For more on grouping the joined rows afterwards, see SQL GROUP BY and HAVING explained.

How testers check keys

Testers meet the primary key vs foreign key rules every time they validate data, because broken keys cause the nastiest bugs.

Constraints are business rules, so they deserve tests. A short checklist for any new table:

  • Insert a duplicate primary key and expect an error.
  • Insert NULL into the primary key and expect an error.
  • Insert a child row with a missing parent and expect an error.
  • Delete a parent that has children and confirm the rule you chose (block, cascade or set null).
  • Run an orphan check on existing data:
SELECT o.order_id
FROM orders o
LEFT JOIN customers c ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL;

An empty result means no orphans. Our SQL tutorial for beginners covers the statements used here from scratch.

Common primary key vs foreign key mistakes

  • Using a mutable value as the primary key, such as an email address that users can change.
  • Skipping foreign keys “for speed” and relying on application code. One bug later you have orphan rows.
  • Forgetting the index on the foreign key column.
  • Cascading deletes everywhere, which can wipe out far more data than intended.
  • Assuming SQLite enforces foreign keys without enabling the pragma.

Final thoughts

The primary key vs foreign key rule of thumb is simple: the primary key says who a row is, and the foreign key says who it belongs to. Define both when you create the tables, pick delete rules on purpose, index the foreign key and write tests for the failure cases.

Frequently asked questions

What is the main difference in primary key vs foreign key?

A primary key uniquely identifies each row in its own table. A foreign key refers to a key in another table and links the two.

Can a foreign key be NULL?

Yes. A foreign key column accepts NULL unless you declare it NOT NULL, and NULL means the row has no parent.

Can a table have more than one foreign key?

Yes. A table can reference many parent tables, but it can have only one primary key.

Can a column be both a primary key and a foreign key?

Yes. This is common in one-to-one tables, where the child table reuses the parent id as its own primary key.

Does a foreign key create an index automatically?

It depends. PostgreSQL does not index the referencing column, while MySQL InnoDB requires and creates one. Add an index yourself when in doubt.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →