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 thecustomerstable with anidcolumn as the primary key and anamecolumn with aNOT NULLconstraint.CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, FOREIGN KEY(customer_id) REFERENCES customers(id)): This creates theorderstable with anidcolumn as the primary key and acustomer_idcolumn with aNOT NULLconstraint. TheFOREIGN KEYclause adds a foreign key constraint to theorderstable that references theidcolumn of thecustomerstable.INSERT INTO customers (name) VALUES ('John Doe'): This inserts a row into thecustomerstable with thenamevalue ofJohn Doe.INSERT INTO orders (customer_id) VALUES (1): This inserts a row into theorderstable with thecustomer_idvalue of1.
Helpful links
More of Sqlite
- How do I troubleshoot a near syntax error when using SQLite?
- How can SQLite and ZFS be used together for software development?
- How do I use SQLite keywords to query a database?
- How do I use the SQLite ZIP VFS to compress a database?
- How do I call sqlitepcl.raw.setprovider() when using SQLite?
- How to configure SQLite with XAMPP on Windows?
- How do I use SQLite with Visual Studio?
- How do I use SQLite transactions?
- How do I write a SQLite query?
- How do I resolve an error "no such column" when using SQLite?
See more codes...