Databases & SQL Master Course — 064. Composite Primary and Foreign Keys
Lesson 064 Composite Primary and Foreign Keys
Prerequisites and objectives
You can define required values, uniqueness, and row checks. You will now model an identity whose scope spans two columns, reference that complete identity from a child table, and test combinations that contain individually familiar values but do not identify an existing parent.
Create the practice fixture
Use a fresh disposable SQLite database. Enable foreign keys before starting any transaction, then verify the setting. Warehouse N and warehouse S both use order number ten. Order numbers are unique only inside a warehouse. A line number is unique only inside its warehouse order. Every mutation below ends with rollback.
PRAGMA foreign_keys=ON;
CREATE TABLE warehouse_orders (
warehouse_code TEXT NOT NULL,
order_no INTEGER NOT NULL,
destination TEXT NOT NULL,
PRIMARY KEY(warehouse_code,order_no)
);
CREATE TABLE order_lines (
warehouse_code TEXT NOT NULL,
order_no INTEGER NOT NULL,
line_no INTEGER NOT NULL,
item TEXT NOT NULL,
PRIMARY KEY(warehouse_code,order_no,line_no),
FOREIGN KEY(warehouse_code,order_no)
REFERENCES warehouse_orders(warehouse_code,order_no)
);
INSERT INTO warehouse_orders VALUES
('N',10,'North desk'),('S',10,'South desk'),('N',11,'West desk');
INSERT INTO order_lines VALUES ('N',10,1,'Notebook');
PRAGMA foreign_keys;
State the scope of identity
The phrase order ten is ambiguous in this model. It might mean North’s order or South’s order. The complete identity is the ordered pair of warehouse code and order number. A child line must retain both values or use some separately declared unique identifier that represents the same parent.
The parent primary key enforces uniqueness of the pair. The child primary key adds line number, allowing several lines for one order while prohibiting two line-one records for that same order. Explicit NOT NULL declarations keep every identity component present and avoid SQLite’s historical nullable-primary-key behavior in ordinary rowid tables.
BEGIN;
INSERT INTO order_lines VALUES ('S',10,1,'Pen');
INSERT INTO order_lines VALUES ('N',10,2,'Atlas');
SELECT warehouse_code,order_no,line_no,item FROM order_lines ORDER BY warehouse_code,order_no,line_no;
ROLLBACK;
South order ten can have line one even though North order ten already has line one. North can also add line two. These are three distinct complete keys. An accidental UNIQUE constraint on line_no alone would reject valid lines and impose a different business rule.
Reference the pair as one relationship
The table-level foreign key lists two child columns and maps them, in order, to two parent columns. SQLite must find a parent row with that complete combination. Separate foreign keys on warehouse and order number would not express this relationship, even if each component happened to exist somewhere.
For example, S exists and order eleven exists, but S order eleven does not. The composite reference must reject that combination. This counterexample is more revealing than testing a completely unknown warehouse because it catches the common mistake of validating components independently.

Keep queries aligned with the same key
Joins must use the complete parent identity too. Joining only on order number would match North line one to both North and South order ten, duplicating the result and attaching a wrong destination. A correct foreign key does not automatically repair a query that omits part of its join condition.
Column order matters in the declaration because it defines the child-to-parent correspondence. Clear matching names make that mapping easier to review. Parent columns must form an eligible primary or unique key with appropriate comparison rules. A foreign key is not a general query that searches for any vaguely similar parent row.
Decide whether partial missing keys are allowed
SQLite considers a composite child foreign key satisfied without a parent lookup if any child key component is NULL. That can be appropriate for a deliberately optional relationship, but it is usually wrong for a required order line. Our NOT NULL declarations prohibit incomplete identities before that escape can occur.
Foreign-key enforcement is a connection-level setting in SQLite, so every application connection needs the intended configuration. Turning it on midway through an active transaction is not the correct setup pattern. These examples enable it before the fixture is created and confirm the returned value is one.
Four worked exercises
Exercise 1
Try a line for South order eleven, whose individual values both appear in the parent table.
Worked solution
BEGIN;
INSERT INTO order_lines VALUES ('S',11,1,'Marker');
SELECT COUNT(*) FROM order_lines;
ROLLBACK;
The full pair has no parent row, so insertion fails. Existence of S in one row and eleven in another is insufficient. This is the defining test for a composite reference rather than two unrelated component checks.
Exercise 2
Try repeating line one for North order ten.
Worked solution
BEGIN;
INSERT INTO order_lines VALUES ('N',10,1,'Another item');
SELECT item FROM order_lines;
ROLLBACK;
The complete child primary key conflicts. A line number identifies a position within an order, not merely an item description. If two distinct items are intended, assign separate legitimate line numbers.
Exercise 3
Join the existing line to its correct destination using the full parent key.
Worked solution
SELECT l.item,o.destination FROM order_lines AS l JOIN warehouse_orders AS o ON o.warehouse_code=l.warehouse_code AND o.order_no=l.order_no;
Both equality predicates are necessary under this model. The result contains one line and the North destination. The schema establishes the relationship, while the query must still express that relationship accurately.
Exercise 4
Try inserting a line with a missing warehouse component.
Worked solution
BEGIN;
INSERT INTO order_lines VALUES (NULL,10,2,'Pen');
SELECT COUNT(*) FROM order_lines;
ROLLBACK;
The explicit required-value rule rejects the incomplete identity. Without it, SQLite’s composite foreign-key NULL behavior could allow a row that does not identify any parent order. Requiredness and referential existence solve separate problems.
Knowledge check
Question 1
What identifies a parent order here?
- Warehouse code together with order number
- Order number alone
- Destination text alone
- Any line number
Answer and explanation
A. Order numbering is scoped to a warehouse, so both components are required.
Question 2
Why does S plus eleven fail?
- S is absent from every parent row
- Eleven is absent from every parent row
- Composite keys prohibit repeated numbers anywhere
- No parent has that complete combination
Answer and explanation
D. Known component values do not prove the combined parent exists.
Question 3
Why declare every child key component NOT NULL?
- To require every parent order to be referenced
- To prohibit incomplete required identities
- To forbid orders with more than one line
- To make order numbers unique across all warehouses
Answer and explanation
B. Requiredness closes the partial-NULL gap for this mandatory relationship.
Question 4
Which join matches the declared relationship?
- Equality on warehouse and order number
- Equality on order number only
- Equality on warehouse only
- A cross join followed by DISTINCT
Answer and explanation
A. The query needs the same complete identity as the foreign key.
Question 5
When should foreign_keys be enabled?
- Only after the first failing insert
- Only after starting the transaction that performs the writes
- On the connection before the transaction begins
- After COMMIT without checking the result
Answer and explanation
C. Establish and verify the connection setting before relying on enforcement.
Pitfalls and summary
Do not split a composite identity into unrelated checks or omit part of it from a join. State the scope of each number, require all mandatory key components, and test a nonexistent combination of otherwise valid values. Composite keys are manageable when every schema declaration and query preserves the same identity contract.
SQLite behavior and references
Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.
Primary references
- SQLite foreign keys: Composite references, enforcement, and referential actions
- SQLite CREATE TABLE: Declared keys and nullability