Constraints
In SQL, constraints can be specified for tables. Constraints enforce certain properties over data that is inserted into a table. Constraints can be specified along with the schema of the table as part of the CREATE TABLE statement. Constraints can also be added to an existing table with the ALTER TABLE statement: ADD CONSTRAINT for CHECK, UNIQUE, PRIMARY KEY and FOREIGN KEY constraints, and ALTER COLUMN ... SET NOT NULL.
Syntax
Check Constraint
Check constraints allow you to specify an arbitrary Boolean expression. Any columns that do not satisfy this expression violate the constraint. For example, we could enforce that the name column does not contain spaces using the following CHECK constraint.
CREATE TABLE students (name VARCHAR CHECK (NOT contains(name, ' ')));
INSERT INTO students VALUES ('this name contains spaces');db error: ERROR: CHECK constraint failed on table (varies)
Not Null Constraint
A not-null constraint specifies that the column cannot contain any NULL values. By default, all columns in tables are nullable. Adding NOT NULL to a column definition enforces that a column cannot contain NULL values.
CREATE TABLE students (name VARCHAR NOT NULL);
INSERT INTO students VALUES (NULL);db error: ERROR: NOT NULL constraint failed: (varies)
Primary Key and Unique Constraint
Primary key or unique constraints define a column, or set of columns, that are a unique identifier for a row in the table. The constraint enforces that the specified columns are unique within a table, i.e., that at most one row contains the given values for the set of columns.
CREATE TABLE students (id INTEGER PRIMARY KEY, name VARCHAR);
INSERT INTO students VALUES (1, 'Student 1');
INSERT INTO students VALUES (1, 'Student 2');db error: ERROR: duplicate key value violates unique constraint "students_pkey" DETAIL: Key (id)=(1) already exists.
CREATE TABLE students (id INTEGER, name VARCHAR, PRIMARY KEY (id, name));
INSERT INTO students VALUES (1, 'Student 1');
INSERT INTO students VALUES (1, 'Student 2');
INSERT INTO students VALUES (1, 'Student 1');db error: ERROR: duplicate key value violates unique constraint "students_pkey" DETAIL: Key (id, name)=(1, Student 1) already exists.
Primary key constraints and unique constraints are identical except for two points:
- A table can only have one primary key constraint defined, but many unique constraints
- A primary key constraint also enforces the keys to not be
NULL.
CREATE TABLE students (id INTEGER PRIMARY KEY, name VARCHAR, email VARCHAR UNIQUE);
INSERT INTO students VALUES (1, 'Student 1', 'student1@uni.com');
INSERT INTO students VALUES (2, 'Student 2', 'student1@uni.com');db error: ERROR: duplicate key value violates unique constraint "students_email_key" DETAIL: Key (email)=(student1@uni.com) already exists.
INSERT INTO students (id, name) VALUES (3, 'Student 3');
INSERT INTO students (name, email) VALUES ('Student 3', 'student3@uni.com');db error: ERROR: NOT NULL constraint failed: (varies)
You can also define a uniqueness constraint on multiple columns:
CREATE TABLE integers (i INTEGER, j INTEGER, k INTEGER, UNIQUE (i, j));
INSERT INTO integers VALUES (1, 2, 3);
INSERT INTO integers VALUES (1, 4, 5);
INSERT INTO integers VALUES (1, 2, 5);db error: ERROR: duplicate key value violates unique constraint "integers_i_j_key" DETAIL: Key (i, j)=(1, 2) already exists.
Deferred Checking
A primary key or unique constraint is checked by every statement that changes the table. Write DEFERRED after PRIMARY KEY or UNIQUE to check it when the transaction commits instead: in between, the transaction may hold duplicate keys, and the commit fails if any are left. IMMEDIATE, the default, can be written out the same way. The PostgreSQL forms DEFERRABLE, INITIALLY DEFERRED and SET CONSTRAINTS are not supported.
CREATE TABLE accounts (id INTEGER PRIMARY KEY DEFERRED, name VARCHAR);
INSERT INTO accounts VALUES (1, 'a'), (2, 'b');
BEGIN;
INSERT INTO accounts VALUES (2, 'c');
UPDATE accounts SET id = 3 WHERE name = 'c';
COMMIT;
BEGIN;
INSERT INTO accounts VALUES (3, 'd');
COMMIT;
SELECT id, name FROM accounts ORDER BY id;db error: ERROR: duplicate key value violates unique constraint "accounts_pkey" DETAIL: Key (id)=(3) already exists. id | name ----+------ 1 | a 2 | b 3 | c
The constraint_check_mode column of sdb_constraints() shows which of the two a constraint was declared with, and DEFAULT when it names neither:
CREATE TABLE members ( id INTEGER PRIMARY KEY DEFERRED, email VARCHAR UNIQUE, nickname VARCHAR UNIQUE IMMEDIATE);
SELECT constraint_type, constraint_column_names, constraint_check_modeFROM sdb_constraints()WHERE database_name = current_database() AND table_name = 'members' AND constraint_type IN ('PRIMARY KEY', 'UNIQUE')ORDER BY constraint_index; constraint_type | constraint_column_names | constraint_check_mode
-----------------+-------------------------+-----------------------
PRIMARY KEY | {id} | DEFERRED
UNIQUE | {email} | DEFAULT
UNIQUE | {nickname} | IMMEDIATEForeign Keys
Foreign keys define a column, or set of columns, that refer to a primary key or unique constraint from another table. The constraint enforces that the key exists in the other table.
CREATE TABLE students (id INTEGER PRIMARY KEY, name VARCHAR);
CREATE TABLE subjects (id INTEGER PRIMARY KEY, name VARCHAR);
CREATE TABLE exams ( exam_id INTEGER PRIMARY KEY, subject_id INTEGER REFERENCES subjects(id), student_id INTEGER REFERENCES students(id), grade INTEGER);
INSERT INTO students VALUES (1, 'Student 1');
INSERT INTO subjects VALUES (1, 'CS 101');
INSERT INTO exams VALUES (1, 1, 1, 10);
INSERT INTO exams VALUES (2, 1, 2, 10);db error: ERROR: insert or update on table "exams" violates foreign key constraint "exams_student_id_fkey" DETAIL: Key (student_id)=(2) is not present in table "students".
Deleting or updating a row whose key is still referenced fails with update or delete on table "⟨table⟩" violates foreign key constraint "⟨name⟩" on table "⟨referencing table⟩". Referential actions such as ON DELETE CASCADE are not supported; see Foreign Key Constraints.