SQLite Constraints
What are Constraints?
Constraints are rules for the data in a table. If a statement breaks a rule, SQLite stops the statement with an error, and the data is not changed.
You write the constraints when you create the table:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
...
);
SQLite Constraints
| Constraint | Rule |
|---|---|
| NOT NULL | The column cannot have a NULL value |
| UNIQUE | All the values in the column are different |
| PRIMARY KEY | Each record has a unique key |
| FOREIGN KEY | A value must exist in another table |
| CHECK | The values must meet a condition |
| DEFAULT | A value to use when no value is given |
Example
Example
Create a table with several constraints:
CREATE TABLE IF NOT EXISTS Persons (
PersonID INTEGER PRIMARY KEY,
LastName TEXT NOT NULL,
FirstName TEXT,
Age INTEGER CHECK (Age >= 18),
City TEXT DEFAULT 'Oslo'
);
Try it Yourself »
Note: SQLite cannot add constraints to an existing table with ALTER TABLE. Plan the constraints when you create the table.