In SQLite3, foreign key constraints are not enforced by default. This behavior differs from most other relational database management systems (RDBMSs), leading to confusion among developers accustomed to robust constraint enforcement.
Consider the following example: we create two tables, Persons and Orders, with a foreign key constraint in Orders that references the primary key in Persons. Despite this constraint being defined, we can still insert rows into Orders without corresponding records in Persons.
In SQLite3 versions 3.x and below, foreign key constraints must be explicitly enabled using the following query every time you connect to the database:
PRAGMA foreign_keys = ON;
This is because SQLite3 maintains backward compatibility with its earlier version, SQLite2.x, which did not support foreign key constraints.
The decision to disable foreign key enforcement by default was primarily driven by SQLite's heritage as an embedded database for use in applications where performance was critical. Foreign key constraints can impact performance, especially in high-concurrency scenarios.
In SQLite4.x, foreign key constraints will be enabled by default. This change addresses the potential confusion and frustration caused by the current behavior.
In the context of the provided example, one should execute the PRAGMA foreign_keys = ON; statement to enable foreign key enforcement. After that, inserting records into Orders without corresponding records in Persons will result in an error, as expected.
The above is the detailed content of Why Doesn't SQLite3 Enforce Foreign Key Constraints by Default?. For more information, please follow other related articles on the PHP Chinese website!