Example 1
Create orders table with a foreign key to customers
Both inserts reference valid customer IDs (1 and 2), so they succeed. If you tried INSERT INTO orders VALUES (3, 99, 200) — referencing customer 99 which does not exist — the engine would raise a foreign key violation error. SQLite silently allows this violation unless PRAGMA foreign_keys = ON was set earlier in the same connection.
CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(100));
INSERT INTO
customers
VALUES
(1, 'Alice'),
(2, 'Bob');CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
total INT,
CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id)
);
INSERT INTO
orders
VALUES
(1, 1, 150),
(2, 2, 80);
SELECT
o.id,
c.name,
o.total
FROM
orders o
JOIN customers c ON c.id = o.customer_id
ORDER BY
o.id;| id | name | total |
|---|---|---|
| 1 | Alice | 150 |
| 2 | Bob | 80 |
Foreign key syntax is identical across all engines. SQLite requires the PRAGMA to enable enforcement.