PostgreSQL – Check Constraint

A check constraint is a type of constraint that allows you to define a condition that must be true for every row in a table. The check constraint can be used to enforce rules on columns, such as limiting the values that can be entered in a particular column or ensuring that certain columns are always populated with valid data.

To create a check constraint in PostgreSQL, you can use the following syntax:

ALTER TABLE table_name
ADD CONSTRAINT constraint_name CHECK (condition);

where table_name is the name of the table you want to add the constraint to,

constraint_name is a name of the constraint, and

condition is the condition that must be true for every row in the table.

Example, let’s say you have a table called employees want to add a check constraint to ensure that the salary column contains only positive values.

ALTER TABLE employees
ADD CONSTRAINT positive_salary CHECK (salary > 0);

Above sql will create a check constraint named positive_salary to ensure that the salary column contains only positive values. If you attempt to insert or update a row that violates this constraint, it will result in an error.

You can also create a check constraint during table creation by including the constraint in the column definition as shown below:

CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(50),
    salary INTEGER CHECK (salary > 0)
);

Above sql creates a table called employees with columns for id, name, and salary. The salary column has a check constraint that ensures it contains only positive values.

Similar Posts