PostgreSQL Constraints

Constraint enforces a restriction on data to be stored in a column. If a user attempts to store data in a column that would violate a constraint, an error will be raised.

In PostgreSQL, constraints can be defined in two ways:

  1. Constraints can be defined as part of the definition of an individual column. They are called Inline Constraints. A column can have multiple constraints.
  2. Constraints can be specified as part of the table definition.

Not Null Constraint:

The NOT NULL constraint restricts the NULL value in the column.

Unique Constraint

Unique constraint enforces unique values for a column or group of columns across the whole table.

Primary Key Constraint

Primary key is a column or group of columns that uniquely identify a row in a table.

It is a combination of NOT NULL constraint and UNIQUE constraint.

Foreign Key Constraint

The foreign key defines a relationship between the two tables and enforces referential integrity in PostgreSQL. A Foreign key is a column or group of columns in one table that references one or more columns from another table.

Check constraint

Check constraint is a constraint that allows specifying the conditions that the values of columns must meet.

Learn about the NOT NULL constraint in the next chapter.