Hello!

This lecture is a bit of an extra. It's not something we use in the applications we build in this course, but it can be useful to know about, and it's relatively straightforward.

Check constraints allow PostgreSQL (and it isn't supported in many other RDBMS's) to ensure that a value in a certain column satisfies a condition. You can also use check constraints table-wide, for example to calculate a computation of multiple column values and ensure they together satisfy a condition.

For one column:


CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0)
);


For several columns:


CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0),
    discounted_price numeric CHECK (discounted_price > 0),
    CHECK (price > discounted_price)
);


When you try to insert or update a row, the check constraints will validate the new data. Other database systems like MySQL don't support check constraints, but it is a feature of PostgreSQL!

Happy coding!

Jose