How to add a check constraint to an existing table in PostgreSQL
To add a check constraint to an existing table in PostgreSQL you use the ALTER TABLE command.
## Step 1: Use the ALTER TABLE command
Use this command:
ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK(what_to_check);
For example, if you have a table called "products" and you wanted to make sure that the price column cannot be negative, you could do this:
ALTER TABLE products ADD CONSTRAINT price_not_negative CHECK (price >= 0);
The constraint can have more than one check. For example, you could make sure the price was greater than zero but less than 100:
ALTER TABLE products ADD CONSTRAINT valid_price_range CHECK(price > 0 AND price < 100);
Support the author
This author accepts donations via the services listed below. Your donation will help them continue to create great content!
* Lernabit doesn't take any of the money from your donation, but the donation services or payment processors might take a fee. These trademarks are the property of their respective owners.