Check Constraint - (PostgreSQL Constraints)
In PostgreSQL, a check constraint is a type of constraint that allows you to specify a condition that must be true for each row in a table. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of the check constraint in PostgreSQL.
Syntax
CREATE TABLE table_name (
column1 datatype [ CONSTRAINT constraint_name ] [column1_constraint],
column2 datatype [ CONSTRAINT constraint_name ] [column2_constraint],
...
CONSTRAINT constraint_name CHECK (condition)
);
table_name
: The name of the table to create.column1
,column2
, ... : The name of each column in the table.datatype
: The data type of each column.constraint_name
: The name for the constraint.column1_constraint
,column2_constraint
, ...: Constraints for each column.condition
: The condition that must be true for each row in the table.
Example
Let's take a look at an example of using the check constraint in PostgreSQL.
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name VARCHAR(50),
age INT,
salary MONEY CHECK (salary > 1)
);
In this example, we created a table named "employees" with four columns: "id", "name", "age", and "salary". We added a check constraint to the "salary" column to ensure that it is greater than 1.
Explanation
A check constraint in PostgreSQL allows you to specify a condition that must be true for each row in a table. When you insert or update a row, PostgreSQL checks to see if the condition is true before allowing the insert or update to proceed.
In the above example, we created a table named "employees" with four columns: "id", "name", "age", and "salary". We specified a check constraint on the "salary" column that ensures that the value of the "salary" column is greater than 1.
Use
The check constraint is a useful way to ensure that data in a table meets certain requirements. For example, you could use a check constraint to ensure that a date column contains only dates in a certain range, or that a numeric column is positive.
Important Points
- Check constraints can be added to new or existing tables.
- Check constraints can be added to individual columns or to an entire table.
- Check constraints can reference other columns in the same table.
- Check constraints can be disabled or enabled using the ALTER TABLE statement.
Summary
In this tutorial, we discussed the check constraint in PostgreSQL. We covered the syntax, example, output, explanation, use, and important points of the check constraint. With this knowledge, you can now use the check constraint to ensure that data in a table meets certain requirements in your PostgreSQL database.