Database / SQLite Interview questions
What is a FOREIGN KEY in SQLite and how do you enable it?
A FOREIGN KEY constraint links a column in one table to a primary/unique key in another,
ensuring referential integrity — you can't insert a row referencing a value that doesn't exist in the
referenced table.
CREATE TABLE order_item ( id INTEGER PRIMARY KEY, person_id INTEGER, FOREIGN KEY (person_id) REFERENCES person(id) );
Notably, SQLite parses foreign key constraints but doesn't actually enforce them by default, for historical backward-compatibility reasons — you must explicitly turn enforcement on per connection with:
PRAGMA foreign_keys = ON;
This is a common surprise for developers coming from other databases where foreign keys are always enforced: forgetting this pragma means orphaned references can silently be inserted with no error at all.
More Related questions...