database – Fixed column value (= null) depending on the value of another column

Question:

The tablename table has type and arg columns. It is necessary to introduce a restriction according to which, with type = 1 , always arg = null .

How can this be organized in PostgreSQL? Version 9.5.2.

It is possible to implement this at the application level, but it is required, namely, at the DBMS level. So that she does not allow to break this rule.

Answer:

ALTER TABLE test 
ADD CONSTRAINT null_arg 
CHECK ((type = 1 AND arg IS NULL) OR type <> 1)
Scroll to Top