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 generate a UUID in SQLite?
- How can SQLite and ZFS be used together for software development?
- 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 do I install and use SQLite on Ubuntu?
- How can I store JSON data in a SQLite column?
- How do I use an enum data type with SQLite?
- How do I use the SQLite zfill function?
- How do I show the databases in SQLite?
- How to configure SQLite with XAMPP on Windows?
See more codes...