SQLite Constraints
A constraint is a rule used in a database table to restrict data, helping to ensure the integrity, consistency, and reliability of the data.
For example, constraints can require that an employee's name is not empty, an email is not duplicated, a salary is greater than zero, or that a field must reference a record that exists in another table.
SQLite supports a variety of constraints; common ones include:
- **NOT NULL:** restricts a column from storing NULL values.
- **DEFAULT:** uses a default value when a column value is not specified during insertion.
- **UNIQUE:** requires values in the specified column or column combination to remain unique.
- **PRIMARY KEY:** defines a primary key for the records in a table.
- **CHECK:** requires data to satisfy a specified conditional expression.
- **FOREIGN KEY:** establishes a reference relationship between tables, maintaining referential integrity.
Constraints are usually defined when executing CREATE TABLE table creation, and can also be adjusted through corresponding table structure modification operations.
Basic Syntax of SQLite Constraints
SQLite supports column-level constraints and table-level constraints.
Column-Level Constraintswritten directly after the column definition, for example:
CREATE TABLE COMPANY (
ID INTEGER PRIMARY KEY,
NAME TEXT NOT NULL,
AGE INTEGER CHECK (AGE >= 18),
SALARY REAL DEFAULT 50000.00
);
Table-Level Constraintswritten after all column definitions, usually used when multiple columns participate in a constraint together.
CREATE TABLE EMPLOYEE (
ID INTEGER PRIMARY KEY,
NAME TEXT NOT NULL,
DEPARTMENT TEXT NOT NULL,
EMPLOYEE_NO TEXT NOT NULL,
UNIQUE (DEPARTMENT, EMPLOYEE_NO)
);
The above UNIQUE (DEPARTMENT, EMPLOYEE_NO) requires that the combination of department and employee number cannot be duplicated.
It should be noted that in SQLite, NOT NULL can only be declared as a column constraint, while UNIQUE、CHECK and PRIMARY KEY etc. can be written at column level or table level depending on the use.
NOT NULL Constraint
By default, ordinary columns in an SQLite table are allowed to store NULL。
If a column must be provided with a valid value, you can use the NOT NULL constraint.
NULL represents a missing or unknown value, and is not equal to the number 0, nor to an empty string ''。
Example
Now create a COMPANY table that requires the employee name and age to be not empty.
Example
CREATE
TABLE
COMPANY
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
AGE
INTEGER
NOT
NULL
,
ADDRESS TEXT
,
SALARY
REAL
)
;
Insert normal data:
INSERT INTO COMPANY (NAME, AGE, ADDRESS, SALARY)
VALUES ('Zhang San', 28, 'Beijing', 60000);
After a successful insertion, you can query with the following statement:
SELECT * FROM COMPANY;
Query result:
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 1 | Zhang San | 28 | Beijing | 60000.0 |
If you try to insert a record NAME is NULL like this:
INSERT INTO COMPANY (NAME, AGE)
VALUES (NULL, 25);
SQLite will reject the operation, with an error message similar to:
NOT NULL constraint failed: COMPANY.NAME
Note:NOT NULL can only prevent NULL, not empty strings.
For example, the following statement will not fail because of NOT NULL :
INSERT INTO COMPANY (NAME, AGE)
VALUES ('', 25);
If you also require the name not to be an empty string, you can combine it with the CHECK constraint to enforce the restriction.
The DEFAULT Constraint
DEFAULT used to specify the default value of a column.
When INSERT INTO When the statement does not provide a value for a column, SQLite uses that column's default value.
Example
Now create the COMPANY table and set the SALARY default value to 50000.00。
Example
CREATE
TABLE
COMPANY
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
AGE
INTEGER
NOT
NULL
,
ADDRESS TEXT
,
SALARY
REAL
DEFAULT
50000.00
)
;
Insert data without specifying the salary:
INSERT INTO COMPANY (NAME, AGE)
VALUES ('Li Si', 30);
SELECT ID, NAME, SALARY FROM COMPANY;
Query result:
| ID | NAME | SALARY |
|---|---|---|
| 1 | Li Si | 50000.0 |
Note thatNot providing a column value and explicitly providing NULL are two different situations。
For example:
INSERT INTO COMPANY (NAME, AGE, SALARY)
VALUES ('Wang Wu', 26, NULL);
This statement explicitly sets the salary to NULL, so the default value will not be used 50000.00。
If the salary is not allowed to be NULL, you can combine:
SALARY REAL NOT NULL DEFAULT 50000.00
Using a Date as the Default Value
SQLite also supports CURRENT_DATE、CURRENT_TIME and CURRENT_TIMESTAMP and other default values.
CREATE TABLE LOGS (
ID INTEGER PRIMARY KEY,
MESSAGE TEXT NOT NULL,
CREATED_AT TEXT DEFAULT CURRENT_TIMESTAMP
);
When inserting a log, you do not need to manually specify the creation time:
INSERT INTO LOGS (MESSAGE)
VALUES ('User logged in');
CURRENT_TIMESTAMP which usually generates UTC time in the format YYYY-MM-DD HH:MM:SS。
UNIQUE Constraint
UNIQUE The constraint is used to ensure that a specified column or combination of columns does not contain duplicate values.
For example, in an employee table, you can require email addresses to remain unique.
Example
Example
CREATE
TABLE
COMPANY
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
EMAIL TEXT
UNIQUE
,
AGE
INTEGER
,
SALARY
REAL
DEFAULT
50000.00
)
;
Insert the first record:
INSERT INTO COMPANY (NAME, EMAIL)
VALUES ('Zhang San', 'zhang@example.com');
Insert the same email again:
INSERT INTO COMPANY (NAME, EMAIL)
VALUES ('Li Si', 'zhang@example.com');
The second insertion will fail, with an error message similar to:
UNIQUE constraint failed: COMPANY.EMAIL
UNIQUE Allows Multiple NULLs
SQLite's UNIQUE The constraint allows multiple NULL values, because in the uniqueness check, NULLs are considered distinct from each other.
For example:
INSERT INTO COMPANY (NAME, EMAIL)
VALUES ('Wang Wu', NULL);
INSERT INTO COMPANY (NAME, EMAIL)
VALUES ('Zhao Liu', NULL);
Both of the above records can be inserted successfully.
If you want the email to be neither empty nor duplicated, you can use:
EMAIL TEXT NOT NULL UNIQUE
Composite Unique Constraint
If you need to ensure that a combination of columns is not duplicated, you can use a table-level UNIQUE constraint.
Example
CREATE
TABLE
EMPLOYEE
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
DEPARTMENT TEXT
NOT
NULL
,
EMPLOYEE_NO TEXT
NOT
NULL
,
UNIQUE
(
DEPARTMENT
,
EMPLOYEE_NO
)
)
;
This means that within the same department there cannot be duplicate employee numbers, but different departments can use the same employee number.
If the columns in the combination allow NULL, you need to additionally consider SQLite's uniqueness rules for NULL. When the business requires the complete combination to be unique, you should usually also declare NOT NULL。
The PRIMARY KEY Constraint
PRIMARY KEY used to specify the primary key of a table, usually to uniquely identify each record.
A table can define at most one primary key, but a primary key can consist of one or more columns.
In SQLite, primary keys have some implementation details that require special attention.
INTEGER PRIMARY KEY
For ordinary SQLite rowid tables, if a column is declared as INTEGER PRIMARY KEY, that column usually becomes the table's rowid alias.
For example:
Example
CREATE
TABLE
COMPANY
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
AGE
INTEGER
NOT
NULL
)
;
INSERT
INTO
COMPANY
(
NAME
,
AGE
)
VALUES
(
'Zhang San'
,
28
)
;
INSERT
INTO
COMPANY
(
NAME
,
AGE
)
VALUES
(
'Li Si'
,
30
)
;
SELECT
FROM
COMPANY;
Query result:
| ID | NAME | AGE |
|---|---|---|
| 1 | Zhang San | 28 |
| 2 | Li Si | 30 |
Since no explicit IDis specified, SQLite automatically chooses a suitable integer primary key value for the record.
The automatic generation here does not mean it must increase consecutively, nor does it guarantee that deleted numbers will never be reused.
The Difference Between INT PRIMARY KEY and INTEGER PRIMARY KEY
In SQLite,INT PRIMARY KEY and INTEGER PRIMARY KEY are not exactly the same.
| Definition | Main Features |
|---|---|
ID INTEGER PRIMARY KEY |
in an ordinary rowid table, it is usually an alias for rowid and can automatically generate integer primary key values |
ID INT PRIMARY KEY |
is usually treated as an ordinary primary key constraint and does not become an alias for rowid |
Therefore, if you want to use the common automatic integer primary key in an ordinary SQLite rowid table, it is usually recommended:
ID INTEGER PRIMARY KEY
The Special Case Where SQLite Primary Keys Allow NULL
According to the SQL standard, primary key columns should not allow NULL.
However, for compatibility with earlier versions, SQLite retains a special behavior: in ordinary rowid tables, certain non- INTEGER PRIMARY KEY primary key columns may allow NULL.
For example:
CREATE TABLE TEST_PK (
ID INT PRIMARY KEY,
NAME TEXT
);
INSERT INTO TEST_PK (ID, NAME)
VALUES (NULL, 'Test');
In an ordinary SQLite rowid table, the above insertion can succeed.
The following cases do not apply this lenient rule:
- The primary key column is declared with
NOT NULL。 - uses a type that follows special rules
INTEGER PRIMARY KEY。 - The table uses
WITHOUT ROWID。 - The table uses
STRICTmode.
Therefore, when creating an ordinary non-integer primary key, if the primary key must not be empty, it is recommended to explicitly add NOT NULL。
Composite Primary Key
A primary key can also consist of multiple columns; such a key is called a composite primary key.
Example
CREATE
TABLE
ORDER_ITEMS
(
ORDER_ID
INTEGER
NOT
NULL
,
PRODUCT_ID
INTEGER
NOT
NULL
,
QUANTITY
INTEGER
NOT
NULL
DEFAULT
1
,
PRIMARY
KEY
(
ORDER_ID
,
PRODUCT_ID
)
)
;
This table allows an order to contain multiple products, but the same order cannot have duplicate product number combinations.
Here, both primary key columns are explicitly declared with NOT NULL, to avoid SQLite's ordinary rowid table NULL compatibility behavior from affecting data integrity.
CHECK Constraint
CHECK The constraint is used to restrict data to satisfy a specified conditional expression.
For example, you can require that an employee's age is not less than 18 and that the salary is greater than zero.
Example
Example
CREATE
TABLE
COMPANY
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
AGE
INTEGER
NOT
NULL
CHECK
(
AGE
=
18
)
,
ADDRESS TEXT
,
SALARY
REAL
NOT
NULL
CHECK
(
SALARY
0
)
)
;
Insert normal data:
INSERT INTO COMPANY (NAME, AGE, SALARY)
VALUES ('Zhang San', 28, 60000);
If you try to insert a negative salary:
INSERT INTO COMPANY (NAME, AGE, SALARY)
VALUES ('Li Si', 30, -1000);
an error similar to the following will be produced:
CHECK constraint failed: SALARY > 0
CHECK and NULL
This is a detail in SQLite that is easy to overlook.
SQLite's CHECK A constraint violation is determined only when the expression evaluates to zero. If the result is non-zero or NULL, the check passes.
For example:
CREATE TABLE PRODUCTS (
ID INTEGER PRIMARY KEY,
PRICE REAL CHECK (PRICE > 0)
);
Because PRICE Without declaring NOT NULL, the following statement can succeed:
INSERT INTO PRODUCTS (PRICE)
VALUES (NULL);
If the business requires that the price must exist and be greater than zero, you should use:
PRICE REAL NOT NULL CHECK (PRICE > 0)
Table-Level CHECK Constraints
CHECK can also be used to validate the relationship between multiple columns.
Example
CREATE
TABLE
PROJECTS
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
START_DATE TEXT
NOT
NULL
,
END_DATE TEXT
NOT
NULL
,
CHECK
(
END_DATE
=
START_DATE
)
)
;
Here it is assumed that dates are stored in a fixed YYYY-MM-DD format.
Through a table-level CHECK, you can require that the end date is not earlier than the start date.
**Note:** This constraint only compares string sizes and does not verify whether the date itself is valid. In real business scenarios, you should also check the format and validity of the input date.
The FOREIGN KEY Constraint
FOREIGN KEY used to establish reference relationships between different tables.
For example, the department number in the employee table should reference a department that actually exists in the department table.
Enabling Foreign Key Checks
Whether SQLite's foreign key constraints are enforced depends on the foreign_keys setting in the database connection and the SQLite build configuration.
To avoid relying on default settings, it is recommended to explicitly execute the following in every database connection that requires foreign key checks:
PRAGMA foreign_keys = ON;
You can check whether it is enabled with the following statement:
PRAGMA foreign_keys;
If 1is returned, it means the current connection has foreign key constraint checks enabled.
**Note:** Do not try to switch PRAGMA foreign_keysin a transaction that has already started, because the setting will not take effect immediately.
Example
Example
PRAGMA foreign_keys
=
ON
;
-- Department table
CREATE
TABLE
DEPARTMENTS
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
UNIQUE
)
;
-- Employee table
CREATE
TABLE
EMPLOYEES
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
DEPARTMENT_ID
INTEGER
,
FOREIGN
KEY
(
DEPARTMENT_ID
)
REFERENCES
DEPARTMENTS
(
ID
)
)
;
-- Insert departments
INSERT
INTO
DEPARTMENTS
(
ID
,
NAME
)
VALUES
(
1
,
'Technology'
)
;
-- Insert employees
INSERT
INTO
EMPLOYEES
(
NAME
,
DEPARTMENT_ID
)
VALUES
(
'Zhang San'
,
1
)
;
The above insertion can succeed because the department with number 1 exists.
If you try to insert a department number that does not exist:
INSERT INTO EMPLOYEES (NAME, DEPARTMENT_ID)
VALUES ('Li Si', 999);
After enabling foreign key checks, SQLite will reject the operation:
FOREIGN KEY constraint failed
Foreign Key Delete Rules
SQLite can use ON DELETE to configure how a parent record is handled when it is deleted.
| Rule | Description |
|---|---|
NO ACTION |
Default behavior; decides whether to reject operations that violate the reference relationship based on when constraint checks occur |
RESTRICT |
When trying to delete or modify a referenced key, reject the operation if related child records exist |
CASCADE |
When a parent record is deleted, automatically delete related child records |
SET NULL |
Set the foreign key of related child records to NULL |
SET DEFAULT |
Set the foreign key of related child records to a default value, which must still satisfy the foreign key constraint |
For example:
FOREIGN KEY (DEPARTMENT_ID)
REFERENCES DEPARTMENTS(ID)
ON DELETE CASCADE
Use ON DELETE CASCADE , when a department record is deleted, employee records associated with that department are automatically deleted as well.
Therefore, in actual development, you should choose an appropriate delete rule based on business needs to avoid accidentally deleting related data.
Combining Multiple Constraints
In real projects, a table usually uses multiple constraints at the same time.
Now create a relatively complete employee table, including primary key, not null, unique, default, check, and foreign key constraints.
Example
PRAGMA foreign_keys
=
ON
;
CREATE
TABLE
DEPARTMENTS
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
UNIQUE
)
;
CREATE
TABLE
COMPANY
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
EMAIL TEXT
NOT
NULL
UNIQUE
,
AGE
INTEGER
NOT
NULL
CHECK
(
AGE
=
18
)
,
SALARY
REAL
NOT
NULL
DEFAULT
50000.00
CHECK
(
SALARY
0
)
,
DEPARTMENT_ID
INTEGER
,
FOREIGN
KEY
(
DEPARTMENT_ID
)
REFERENCES
DEPARTMENTS
(
ID
)
)
;
INSERT
INTO
DEPARTMENTS
(
ID
,
NAME
)
VALUES
(
1
,
'Technology'
)
;
INSERT
INTO
COMPANY
(
NAME
,
,
AGE
,
DEPARTMENT_ID
)
VALUES
(
'Zhang San'
,
'zhang@example.com'
,
28
,
1
)
;
SELECT
FROM
COMPANY;
After a successful run, the employee table contains the following data:
| ID | NAME | AGE | SALARY | DEPARTMENT_ID | |
|---|---|---|---|---|---|
| 1 | Zhang San | zhang@example.com | 28 | 50000.0 | 1 |
This table guarantees at the same time:
- Each record has a unique integer primary key.
- The employee name cannot be empty.
- The employee email cannot be empty and cannot be duplicated.
- The employee age is not less than 18.
- The employee salary is greater than zero, defaulting to 50000.00 when not specified.
- If the department number is not NULL, it must reference an existing department.
Deleting or Modifying Constraints
SQLite's support for ALTER TABLE differs from databases such as MySQL and PostgreSQL.
You cannot directly use the following syntax to delete a constraint:
-- SQLite does not support this generic syntax
ALTER TABLE COMPANY
DROP CONSTRAINT constraint_name;
Similar DROP PRIMARY KEY、DROP FOREIGN KEY and other syntax cannot be copied directly from other databases.
For most constraint modifications, the general approach in SQLite iscreate a new table, copy the data, drop the old table, and rename the new table。
Example: Removing a UNIQUE Constraint
Assume the existing employee table is defined as follows:
CREATE TABLE COMPANY (
ID INTEGER PRIMARY KEY,
NAME TEXT NOT NULL,
EMAIL TEXT UNIQUE
);
INSERT INTO COMPANY (ID, NAME, EMAIL)
VALUES (1, 'Zhang San', 'zhang@example.com');
Now we want to cancel the EMAIL column's unique constraint so that different employees can use the same email.
Since SQLite cannot directly use DROP CONSTRAINT to delete this constraint, you can create a new table that does not include UNIQUE and migrate the original data.
Example
-- Simplified example: suitable for a standalone table with no related foreign keys,
-- triggers, views, or additional indexes
BEGIN
TRANSACTION
;
-- 1. Create a new table, removing the UNIQUE constraint on EMAIL
CREATE
TABLE
COMPANY_NEW
(
ID
INTEGER
PRIMARY
KEY
,
NAME TEXT
NOT
NULL
,
EMAIL TEXT
)
;
-- 2. Copy the original table data
INSERT
INTO
COMPANY_NEW
(
ID
,
NAME
,
)
SELECT
ID
,
NAME
,
FROM
COMPANY;
-- 3. Drop the old table
DROP
TABLE
COMPANY;
-- 4. Rename the new table back to the original name
ALTER
TABLE
COMPANY_NEW
RENAME
TO
COMPANY;
COMMIT;
After completion,EMAIL the column no longer has a unique constraint.
For example:
INSERT INTO COMPANY (NAME, EMAIL)
VALUES ('Li Si', 'zhang@example.com');
In the standalone table example above, this statement can now be executed successfully.
**Important:** The above SQL is a simplified example, suitable only for simple tables with no other dependent objects.
If the actual database has foreign keys, triggers, views, or custom indexes, you must first check and save the definitions of these objects and recreate them correctly after the migration; you also need to verify data integrity.
For complex table structure changes involving foreign keys, follow the complete table rebuild procedure recommended by SQLite, including handling foreign key settings before the transaction begins, recreating related objects, and executing PRAGMA foreign_key_check。
Adding Constraints
SQLite supports using ALTER TABLE ... ADD COLUMN to add new columns and, where allowed, specify constraints for the new columns.
For example:
ALTER TABLE COMPANY
ADD COLUMN STATUS TEXT NOT NULL DEFAULT 'active';
This adds a STATUS column whose default value is 'active'。
Note that SQLite has limitations on constraints for newly added columns. For example, when adding a NOT NULL column to a table with existing data, you usually need to provide a non-NULL default value.
If you need to add or remove UNIQUE、PRIMARY KEY and other constraints on an existing column, you usually need to choose a table rebuild approach based on the specific SQLite version and table structure.
Achieving Uniqueness Through a Unique Index
If you only want to add a uniqueness restriction to an existing column, you can also use a standalone unique index.
CREATE UNIQUE INDEX idx_company_email
ON COMPANY(EMAIL);
After successful creation,EMAIL non-NULL values in the column must remain unique.
If the existing data contains duplicate non-NULL emails, creating the unique index will fail.
For a standalone unique index created through CREATE UNIQUE INDEX , you can use:
DROP INDEX idx_company_email;
to delete the index.
However, if the unique index was automatically created by the UNIQUE or PRIMARY KEY constraint in the table definition, you cannot simply use DROP INDEX to delete the corresponding constraint.
Constraint Conflict Handling
When inserted or updated data violates a constraint, SQLite usually rejects the operation and returns an error.
For some constraint conflicts, you can use ON CONFLICT or related statements to choose how to handle them.
Common conflict handling methods are as follows:
| Handling Method | Purpose |
|---|---|
ABORT |
Default handling: undo the changes already made by the current statement and report an error |
IGNORE |
For applicable constraint conflicts, skip the conflicting row and continue |
REPLACE |
For applicable UNIQUE or PRIMARY KEY conflicts, delete the conflicting old record and then perform the insert or update |
FAIL |
Report the constraint error, but keep the changes already completed by the current statement before the error occurred |
ROLLBACK |
When an applicable constraint conflict occurs in a transaction, roll back the entire transaction |
Example: INSERT OR IGNORE
Assume there is a table with unique emails:
CREATE TABLE USERS (
ID INTEGER PRIMARY KEY,
EMAIL TEXT NOT NULL UNIQUE
);
INSERT INTO USERS (EMAIL)
VALUES ('admin@example.com');
If you insert the same email again:
INSERT OR IGNORE INTO USERS (EMAIL)
VALUES ('admin@example.com');
For this uniqueness conflict, SQLite skips the insertion instead of returning a normal UNIQUE constraint error.
Note:IGNORE It does not ignore all errors. For example, a foreign key constraint conflict may still cause the operation to fail.
In addition,REPLACE It does not simply update an existing row. It may delete the conflicting record and insert a new one, so you should understand the impact on related data and triggers before using it.
Viewing Constraints in a Table
SQLite can learn about the current table definition and constraint information by querying the table structure and related PRAGMA commands.
Viewing the Table Creation Statement
SELECT sql
FROM sqlite_schema
WHERE type = 'table'
AND name = 'COMPANY';
Through the original CREATE TABLE statement, you can view the PRIMARY KEY、UNIQUE、CHECK and other constraints defined in the table.
Viewing Column Information
PRAGMA table_info('COMPANY');
This command can show column names, declared types, whether marked as not null, default values, primary key information, and so on.
Viewing Index Information
PRAGMA index_list('COMPANY');
You can view the indexes associated with a table, including the related indexes used to maintain uniqueness constraints.
Viewing Foreign Key Constraints
PRAGMA foreign_key_list('COMPANY');
This command can show the foreign keys defined in a table and their reference relationships.
You can also use:
PRAGMA foreign_key_check;
to check whether there are records in the database that violate foreign key constraints.
Common questions
1. What is the difference between NOT NULL and UNIQUE?
NOT NULL requires that a column cannot be NULL, but allows duplicate values.
UNIQUE requires that values cannot be duplicated, but in SQLite multiple NULLs are usually allowed.
If neither NULL nor duplicates are allowed, you can combine:
EMAIL TEXT NOT NULL UNIQUE
2. Why can CHECK (PRICE > 0) still allow inserting NULL?
Because when PRICE is NULL, the expression PRICE > 0 also evaluates to NULL.
SQLite's CHECK Failure is determined only when the expression evaluates to zero, so NULL passes the check.
should use:
PRICE REAL NOT NULL CHECK (PRICE > 0)
3. Why does SQLite's primary key sometimes allow NULL?
This is a compatibility behavior left over from earlier versions of SQLite, mainly occurring in ordinary rowid tables with non-special integer primary keys.
In actual development, it is recommended to use INTEGER PRIMARY KEY, or to explicitly declare NOT NULL。
4. Why does executing DROP CONSTRAINT produce an error?
Because SQLite does not support the general ALTER TABLE ... DROP CONSTRAINT syntax.
You need to use supported table structure modification operations or rebuild the table, depending on the constraint type and SQLite version.
5. Why isn't illegal data blocked after defining a FOREIGN KEY?
You should first check whether foreign key checks are enabled for the current database connection:
PRAGMA foreign_keys;
If not enabled, execute outside of a transaction:
PRAGMA foreign_keys = ON;
Note that foreign key settings usually need to be handled separately in each database connection.
Summary
SQLite constraints are used to ensure that data in the database conforms to specified rules and are an important part of database design.
The uses of common constraints are as follows:
| Constraint | Main Use |
|---|---|
| NOT NULL | Prevent a column from storing NULL |
| DEFAULT | Provide a default value |
| UNIQUE | Ensure the uniqueness of a column or column combination |
| PRIMARY KEY | Define a primary key to identify records in a table |
| CHECK | Verify that data satisfies conditions |
| FOREIGN KEY | Maintain reference relationships between tables |
When using SQLite constraints, you need to pay special attention to the following three aspects:
- SQLite's handling of NULL, primary keys, and data types differs from some other databases.
- For foreign key constraints, you need to confirm that foreign key checks are enabled for the current connection.
- Modifying existing constraints cannot directly copy the DROP CONSTRAINT syntax of other databases; complex scenarios usually require rebuilding the table.
When creating database tables, reasonably combining these constraints can detect records that do not conform to the rules during data writing, reducing errors in later data processing.
Reference documentation: