constraint
Constraints are applied to the rules on the data in the table column, the type data table limits. There is a constraint ensures accuracy and reliability data in the database.
Constraint can be a column or table level, column-level constraints applied to a single column, table-level constraints applied to the entire data table.
SQLite common constraints:
- NOT NULL constraints: Make sure that a column can not have NULL values.
- DEFAULT constraint: when a column value is not inserted, provide default values for that column.
- UNIQUE constraint: to ensure that all values in a column are different.
- PRIMARY KEY constraints: data that uniquely identifies a database table.
- FOREIGN KEY constraint: a table pointing FOREIGN KEY PRIMARY KEY in another table.
- CHECK constraint: to ensure that all values satisfy certain conditions in a column.
NOT NULL constraints
By default, the column can hold NULL values. If you do not want a column has a NULL value, you need to define this constraint on the column designated NULL values are not allowed on this column.
NULL and no data is not the same, it represents the unknown data.
-- 实例
CREATE TABLE link_men (
ID INT PRIMARY KEY NOT NULL;
NAME TEXT NOT NULL
)
DEFAULT constraint
DEFAULT constraint in the INSERT INTO statement does not provide a specific value for the column to provide a default value.
-- 实例
CREATE TABLE link_men(
ID INT PRIMARY KEY NOT NULL;
NAME TEXT NOT NULL;
ADDRESS TEXT NOT NULL;
SALARY REAL DEFAULT 8000.00
)
UNIQUE constraint
UNIQUE constraint prevents the presence of two records with the same value in a particular column.
-- 实例
CREATE TABLE link_men(
ID INT PRIMARY KEY NOT NULL;
NAME TEXT NOT NULL;
AGE INT NOT NULL UNIQUE;
ADDRESS TEXT;
SALARY REAL DEFAULT 8000.00
)
PRIMAY KEY constraint
PRIMARY KEY constraint uniquely identifies each record in the database table.
Primary keys must contain unique values.
Primary key column can not contain a NULL value.
Each table should have a primary key, and each table can have only one primary key.
-- 实例
CREATE TABLE link_men(
ID INT PRIMARY KEY NOT NULL;
NAME TEXT NOT NULL;
AGE INT NOT NULL UNIQUE;
ADDRESS TEXT;
SALARY , REAL DEFAULT 8000.00
)
FOREIGN KEY constraint
A table pointing FOREIGN KEY PRIMARY KEY in another table.
-- 实例
CREATE TABLE link_men (
ID INT PRIMARY KEY NOT NULL;
NAME TEXT NOT NULL;
AGE INT NOT NULL UNIQUE;
ADDRESS TEXT;
SALARY REAL DEFAULT 8000.00;
FOREIGN KEY (P_ID) REFERENCES persons(P_ID);
)
CHECK constraints
CHECK constraints enable input a record you want to check the condition values. If the condition is false, the record violates the constraint, and can not be entered into the table.
CREATE TABLE link_men(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS TEXT,
SALARY REAL CHECK(SALARY > 0)
);