sqliteHow do I use the SQLite on delete cascade command?
The SQLite ON DELETE CASCADE
command allows a user to delete related records from other tables when the record in the parent table is deleted. This command is useful for maintaining referential integrity in a database.
Example code
CREATE TABLE IF NOT EXISTS parent_table (
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE IF NOT EXISTS child_table (
id INTEGER PRIMARY KEY,
parent_id INTEGER,
FOREIGN KEY(parent_id) REFERENCES parent_table(id) ON DELETE CASCADE
);
When a record in the parent table is deleted, the corresponding records in the child table will also be deleted.
Code explanation
CREATE TABLE
: creates a new table in the databaseINTEGER PRIMARY KEY
: defines the primary key for the table, which is used to uniquely identify each recordFOREIGN KEY
: defines a foreign key, which is used to reference a record in another tableREFERENCES
: specifies the table and column that the foreign key referencesON DELETE CASCADE
: specifies that the related records in the child table should be deleted when the record in the parent table is deleted
Helpful links
More of Sqlite
- How do I use the SQLite ZIP VFS to compress a database?
- How do I use SQLite to retrieve data from a specific year?
- How can SQLite and ZFS be used together for software development?
- How do I use SQLite with Zephyr?
- How do I extract the year from a datetime value in SQLite?
- How do I use the SQLite zfill function?
- How can I use SQLite to query for records between two specific dates?
- How do I use the SQLite YEAR function?
- How can I use SQLite with Python?
- How do I call sqlitepcl.raw.setprovider() when using SQLite?
See more codes...