Ask The Oracle Expert: Questions & Answers

CHECK constraints

CHECK constraints

By  Rudy Limeback, SQL Consultant, r937.com

SearchOracle.com

How can I create a constraint to not allow a date prior to 1 Jan 2007 to be entered?
This is accomplished with a CHECK constraint. Here's an example:

create table documents
( id    integer     not null primary key 
, title varchar(99) not null
, added date        not null
, constraint only_new_ones 
     check ( added >= '2007-01-01' )         
);

The CHECK constraint should always be given a descriptive name, because this helps identify the source of the error when the constraint is violated. The constraint name is optional, but the difference is between getting an error message that looks like this:

INSERT statement terminated. CHECK constraint "CK__documents__added__73852659" was violated.

and one that looks like this:

INSERT statement terminated. CHECK constraint "only_new_ones" was violated.

Use a constraint name that describes the constraint accurately.