sloth
sloth

Reputation: 101162

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?

Upvotes: 25

Views: 14766

Answers (2)

Jordi Cabot
Jordi Cabot

Reputation: 8238

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

Upvotes: 41

ollyc
ollyc

Reputation: 6123

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)

Upvotes: 3

Related Questions