sqliteHow do I use foreign keys in SQLite?
In SQLite, foreign keys are used to link two tables together. A foreign key is a column or a group of columns in a table that points to the primary key of another table.
For example, the following code creates two tables: customers
and orders
, and adds a foreign key constraint to orders
that references customers
:
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
FOREIGN KEY(customer_id) REFERENCES customers(id)
);
To insert data into the tables, we can use the following code:
INSERT INTO customers (name) VALUES ('John Doe');
INSERT INTO orders (customer_id) VALUES (1);
The foreign key constraint ensures that the customer_id
in the orders
table is a valid id
from the customers
table.
Code explanation
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL)
: This creates thecustomers
table with anid
column as the primary key and aname
column with aNOT NULL
constraint.CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, FOREIGN KEY(customer_id) REFERENCES customers(id))
: This creates theorders
table with anid
column as the primary key and acustomer_id
column with aNOT NULL
constraint. TheFOREIGN KEY
clause adds a foreign key constraint to theorders
table that references theid
column of thecustomers
table.INSERT INTO customers (name) VALUES ('John Doe')
: This inserts a row into thecustomers
table with thename
value ofJohn Doe
.INSERT INTO orders (customer_id) VALUES (1)
: This inserts a row into theorders
table with thecustomer_id
value of1
.
Helpful links
More of Sqlite
- How do I use SQLite to retrieve data from a specific year?
- How do I use the SQLite zfill function?
- How to configure SQLite with XAMPP on Windows?
- How can I use SQLite with Xamarin?
- How can SQLite and ZFS be used together for software development?
- How do I use SQLite with Visual Studio?
- How do I extract the year from a datetime value in SQLite?
- How do I use the SQLite VARCHAR data type?
- How can I use SQLite in a C# project?
- How can I use SQLite to query for records between two specific dates?
See more codes...