Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Conditional Not Null Constraint


I am curious to know is it possible to create a conditional not null constraint in sql? In otherwords is it possible to create a constraint such that a column B can be null as long column A contains lets say 'NEW' but if the contents of column A changes to something else then column B is no longer allowed to be null?
And to extend on that, it is then possible to make it so that column B must be null or empty as long as column A says 'NEW'?
Thanks All :D

like image 379
Heinrich Avatar asked Apr 23 '12 01:04

Heinrich


People also ask

IS NOT NULL condition in SQL?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

What is the rule of not null constraint?

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

Is is not NULL and != The same in SQL?

<> is Standard SQL-92; != is its equivalent. Both evaluate for values, which NULL is not -- NULL is a placeholder to say there is the absence of a value.


1 Answers

This is perfectly fine for CONSTRAINT CHECK. Just do this:

Requirement:

is it possible to create a constraint such that a column B can be null as long column A contains lets say 'NEW' but if the contents of column A changes to something else then column B is no longer allowed to be null?

Note the phrase: column B can be null

Solution:

create table tbl (     A varchar(10) not null,     B varchar(10),      constraint uk_tbl check     (       A = 'NEW' -- B can be null or not null: no need to add AND here       OR (A <> 'NEW' AND B IS NOT NULL)     ) ); 

You can simplify it further:

create table tbl (     A varchar(10) not null,     B varchar(10),      constraint uk_tbl check     (       A = 'NEW'        OR B IS NOT NULL     ) ); 

Requirement mutually incompatible to requirement above:

And to extend on that, it is then possible to make it so that column B must be null or empty as long as column A says 'NEW'?

Note the phrase: column B must be null

create table tbl (     A varchar(10) not null,     B varchar(10),      constraint uk_tbl check     (       (A = 'NEW' AND B IS NULL)       OR A <> 'NEW'     ) ); 

Could be simplified with this, simpler but might not be as readable as above though:

create table tbl (     A varchar(10) not null,     B varchar(10),      constraint uk_tbl check     (       A <> 'NEW'       OR B IS NULL     ) ); 
like image 188
Michael Buen Avatar answered Sep 22 '22 22:09

Michael Buen