PostgreSQL Constraints
PostgreSQL constraints are used to specify the rules for data in a table.
If there is data behavior that violates a constraint, the behavior is terminated by the constraint.
Constraints can be specified when creating a table (via the CREATE TABLE statement) or after the table is created (via the ALTER TABLE statement).
Constraints ensure the accuracy and reliability of data in the database.
Constraints can be column-level or table-level. Column-level constraints apply only to a column, while table-level constraints apply to the entire table.
The following are commonly used constraints in PostgreSQL.
- NOT NULL: Indicates that a column cannot store NULL values.
- UNIQUE: Ensures that all values in a column are unique.
- PRIMARY Key: A combination of NOT NULL and UNIQUE. Ensures that a column (or a combination of two or more columns) has a unique identifier, making it easier and faster to find a specific record in the table.
- FOREIGN Key: Ensures referential integrity so that data in one table matches values in another table.
- CHECK: Ensures that values in a column satisfy a specified condition.
- EXCLUSION: An exclusion constraint, ensuring that if any two rows are compared on the specified columns or expressions using the specified operators, at least one of the operator comparisons returns false or a null value.
NOT NULL Constraint
By default, a column can hold NULL values. If you do not want a column to have NULL values, you need to define this constraint on the column, specifying that NULL values are not allowed.
NULL is different from having no data; it represents unknown data.
Example
The following example creates a new table called COMPANY1 with 5 fields, of which three — ID, NAME, and AGE — are set not to accept null values:
CREATE TABLE COMPANY1(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
UNIQUE Constraint
The UNIQUE constraint can make a column unique, avoiding duplicate values in the same column.
Example
The following example creates a new table called COMPANY3 with 5 fields, of which AGE is set to UNIQUE, so you cannot add two records with the same age:
CREATE TABLE COMPANY3(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR(50),
SALARY REAL DEFAULT 50000.00
);
PRIMARY KEY
PRIMARY KEY is very important when designing a database.
PRIMARY KEY is called the primary key; it is the unique identifier for each record in a data table.
There may be multiple columns set to UNIQUE, but only one column in a table can be set as PRIMARY KEY.
We can use the primary key to reference rows in the table, and we can also create relationships between tables by setting the primary key as a foreign key in another table.
A primary key is a combination of a not-null constraint and a unique constraint.
A table can have only one primary key, which can consist of one or more fields; when multiple fields serve as the primary key, they are called a composite key.
If a table defines a primary key on any field(s), then no two records can have the same values on those fields.
Example
Next we create the COMAPNY4 table, with ID as the primary key:
CREATE TABLE COMPANY4(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
FOREIGN KEY Constraint
FOREIGN KEY, the foreign key constraint, specifies that values in a column (or group of columns) must match values appearing in a row of another table.
Usually a FOREIGN KEY in one table points to a UNIQUE KEY (the key of a unique constraint) in another table, thereby maintaining referential integrity between the two related tables.
Example
The following example creates a COMPANY6 table and adds 5 fields:
CREATE TABLE COMPANY6(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
The following example creates a DEPARTMENT1 table with 3 fields; EMP_ID is the foreign key referencing the ID of COMPANY6:
CREATE TABLE DEPARTMENT1(
ID INT PRIMARY KEY NOT NULL,
DEPT CHAR(50) NOT NULL,
EMP_ID INT references COMPANY6(ID)
);
CHECK Constraint
The CHECK constraint ensures that all values in a column satisfy a certain condition, i.e., a check is performed when a record is entered. If the condition evaluates to false, the record violates the constraint and cannot be entered into the table.
Example
For example, the following example creates a new table COMPANY5 with five columns. Here we add a CHECK to the SALARY column, so the salary cannot be zero:
CREATE TABLE COMPANY5(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL CHECK(SALARY > 0)
);
EXCLUSION Constraint
The EXCLUSION constraint ensures that if any two rows are compared on the specified columns or expressions using the specified operators, at least one of the operator comparisons returns false or null.
Example
The following example creates a COMPANY7 table with 5 fields and uses an EXCLUDE constraint.
CREATE TABLE COMPANY7(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT,
AGE INT ,
ADDRESS CHAR(50),
SALARY REAL,
EXCLUDE USING gist
(NAME WITH =, -- 如果满足 NAME 相同,AGE 不相同则不允许插入,否则允许插入
AGE WITH <>) -- 其比较的结果是如果整个表达式返回 true,则不允许插入,否则允许
);
Here, USING gist is a type of index used for construction and execution.
You need to run the CREATE EXTENSION btree_gist command once for each database; this installs the btree_gist extension, which defines EXCLUDE constraints for purely scalar data types.
Since we have enforced that ages must be the same, let's see this in action by inserting records into the table:
INSERT INTO COMPANY7 VALUES(1, 'Paul', 32, 'California', 20000.00 );
INSERT INTO COMPANY7 VALUES(2, 'Paul', 32, 'Texas', 20000.00 );
-- The NAME of this data record is the same as the first record, and the AGE is also the same as the first record, so it meets the insertion condition
INSERT INTO COMPANY7 VALUES(3, 'Allen', 42, 'California', 20000.00 );
-- This data has the same NAME as the data above, but a different AGE, so insertion is not allowed
The first two are added successfully to the COMPANY7 table, but the third one reports an error:
ERROR: conflicting key value violates exclusion constraint "company7_name_age_excl"
DETAIL: Key (name, age)=(Paul, 42) conflicts with existing key (name, age)=(Paul, 32).
Dropping Constraints
To drop a constraint you must know its name; if you already know the name, dropping it is simple. If you don't know the name, you need to find the system-generated name; use \d table_name to find this information.
The general syntax is as follows:
ALTER TABLE table_name DROP CONSTRAINT some_name;