Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgres: constraint check and null values

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?

like image 984
sloth Avatar asked Jul 25 '09 10:07

sloth


People also ask

How do you check the value is null or not in PostgreSQL?

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.

What does the check constraint do in PostgreSQL?

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.

How do I deal with not null in PostgreSQL?

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.

Is null and is not null in PostgreSQL?

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.


2 Answers

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

like image 188
Jordi Cabot Avatar answered Sep 21 '22 04:09

Jordi Cabot


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)

like image 26
ollyc Avatar answered Sep 19 '22 04:09

ollyc