What is a foreign key?
A foreign key is a column that points to the primary key of another table, linking related rows together.
Drafted with AI from official documentation. Scripts were run in a test environment and repository links verified. Awaiting a human check. Did it work for you? Last edited Outdated?
A foreign key is a column whose values must match a primary key in another table. If an orders table has a customer_id column, each value must be a real customer. It is a reference like a footnote number: the footnote only makes sense if the numbered note actually exists at the bottom of the page.
Foreign keys are what make a relational database relational. They let you JOIN orders with customers, and they protect data: the database refuses to insert an order for customer 999 if no such customer exists, and can delete or block related rows when the parent goes away (ON DELETE CASCADE). Diagrams of tables and their foreign keys are called ER diagrams.
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_id INT REFERENCES customers (id)
);
See also: What is a primary key? and What is SQL?
Did this work for you?
No votes yet. Be the first.
If it did not work, the report form below tells the editors what went wrong.
See also
- 0068 SQL joins explained: INNER, LEFT and finding rows with no match A join combines rows from two tables using a matching condition. INNER JOIN keeps only matches, LEFT JOIN keeps every row from… Intermediate · Explains an idea · Any system Article Joins 15 Oct 2026
- 0077 SQL cheat sheet: a runnable reference for everyday queries One SQL file that builds a tiny database and demonstrates filtering, sorting, grouping, joins, CASE, CTEs, window functions, safe updates and indexes.… Beginner · Cheat sheet · Any system Script Joins · Queries 15 Oct 2026
- 0260 Design and build a library database in SQLite: tables, keys, joins, reports and backups Model books, members and loans, create tables with keys and constraints, load sample data, write join and aggregate reports, add indexes checked… Beginner · Guided project · Any system Article Joins · Queries 15 Oct 2026
History
Every saved edit is kept. The plot on the sleeve draws one line per edit. Open any edit to see exactly what changed.
- Dominik +811 chars