SQL
Foreign Key Constraints
A `FOREIGN KEY` is a column (or set of columns) that references another table's primary key. Foreign keys check referential integrity, i.e., the referred primary key must exist in the other table upon insertion.  
```sql
CREATE TABLE t1 (id INTEGER PRIMARY KEY, j VARCHAR);
CREATE TABLE t2 (
id INTEGER PRIMARY KEY,
t1_id INTEGER,
FOREIGN KEY (t1_id) REFERENCES t1 (id)
);
```  
Example:  
```sql
INSERT INTO t1 VALUES (1, 'a');
INSERT INTO t2 VALUES (1, 1);
INSERT INTO t2 VALUES (2, 2);
```  
```console
Error: Constraint Error: Violates foreign key constraint because key "id: 2" does not exist in the referenced table
```  
Foreign keys can be defined on composite primary keys:  
```sql
CREATE TABLE t3 (id INTEGER, j VARCHAR, PRIMARY KEY (id, j));
CREATE TABLE t4 (
id INTEGER PRIMARY KEY, t3_id INTEGER, t3_j VARCHAR,
FOREIGN KEY (t3_id, t3_j) REFERENCES t3(id, j)
);
```  
Example:  
```sql
INSERT INTO t3 VALUES (1, 'a');
INSERT INTO t4 VALUES (1, 1, 'a');
INSERT INTO t4 VALUES (2, 1, 'b');
```  
```console
Error: Constraint Error: Violates foreign key constraint because key "id: 1, j: b" does not exist in the referenced table
```  
Foreign keys can also be defined on unique columns:  
```sql
CREATE TABLE t5 (id INTEGER UNIQUE, j VARCHAR);
CREATE TABLE t6 (
id INTEGER PRIMARY KEY,
t5_id INTEGER,
FOREIGN KEY (t5_id) REFERENCES t5(id)
);
```  
#### Limitations {#docs:sql:statements:create_table::limitations}  
Foreign keys have the following limitations.  
Foreign keys with cascading deletes (` FOREIGN KEY ... REFERENCES ... ON DELETE CASCADE`) are not supported.  
Inserting into tables with self-referencing foreign keys is currently not supported and will result in the following error:  
```console
Constraint Error: Violates foreign key constraint because key "..." does not exist in the referenced table.
```