Check constraints: Not null implied?

The following question was asked in a code review meeting this morning: Do check constraints imply not null? It was prompted by a column defined as not null that also had a check constraint to ensure the column only allowed a discreet set of values. Was the ‘not null’ part redundant?

Embarrassingly, I didn’t know the answer. My guess was that a check constraint such as

"column_name in ('val1','val2')"

would imply the column could not contain null values and so the ‘not null’ piece of the table ddl was redundant. Easy enough to find out.


CREATE TABLE TST_CHK (COL VARCHAR2(1), COL2 VARCHAR2(1));

ALTER TABLE TST_CHK ADD CONSTRAINT TST_CHK1 CHECK (COL2 IN ('A', 'B')) ENABLE;

INSERT INTO tst_chk(col, col2) VALUES ('T',NULL);
>1 row created.

INSERT INTO tst_chk(col, col2) VALUES ('T','C');
>INSERT INTO tst_chk(col, col2) VALUES ('T','C');
>ERROR at line 1:
>ORA-02290: check constraint (DB_ADMIN.TST_CHK1) violated

So, check constraints are only enforced when the column is actually populated with a value.

Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: