please have a look at the following table:
name | x | y
---------+-----+------
foo | 3 | 5
bar | 45 | 99
foobar | 88 |
barfoo | 0 | 45
I want to add a constraint CHECK ( y > x ), but this obviously will fail due it is violated by the row 'foobar'.
How do I create a constraint that says: check (y > x), but only if y not null?
Example - With INSERT Statement INSERT INTO contacts (first_name, last_name) SELECT first_name, last_name FROM employees WHERE employee_number IS NULL; This PostgreSQL IS NULL example will insert records into the contacts table where the employee_number contains a NULL value.
The CHECK constraint uses a Boolean expression to evaluate the values before they are inserted or updated to the column. If the values pass the check, PostgreSQL will insert or update these values to the column. Otherwise, PostgreSQL will reject the changes and issue a constraint violation error.
Here is an example of how to use the PostgreSQL IS NOT NULL condition in a SELECT statement: SELECT * FROM employees WHERE first_name IS NOT NULL; This PostgreSQL IS NOT NULL example will return all records from the employees table where the first_name does not contain a null value.
A NOT NULL constraint is a column constraint and can not be used as a table constraint. The reverse of NOT NULL constraint is NULL, but it is not necessary to mention NULL to create a table, the default is NULL, which does not mean that the column must contain NULL, it means that the column might contain NULL value.
In fact, you don't really need to do anything else. A check constraint is satisfied if the check expression evaluates to true or the null value.
Your constraint CHECK ( y > x ) would work as is in your scenario because the row foobar would not violate the constraint since it evaluates to null
You can put an IS NULL test into the CHECK expression, like this:
CREATE TABLE mytable (
name TEXT,
x INTEGER,
y INTEGER CHECK (y IS NULL OR y > x)
);
(tested on PostgreSQL 8.4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With