Sei sulla pagina 1di 1

28 Chapter 1: Creating

<table_constraint> ::= <table_check_constraint>


| <primary_key_table_constraint>
| <foreign_key_table_constraint>
| <unique_table_constraint>

1.13.1 Table CHECK Constraint


<table_check_constraint> ::= [ <constraint_prefix> ] CHECK
"(" <boolean_expression> ")"
Unlike a column CHECK constraint, a table CHECK constraint can refer to
more than one column in the current row. Here is an example where all the col-
umns must have ascending values:
CREATE TABLE t (
c1 INTEGER,
c2 INTEGER,
c3 INTEGER,
CONSTRAINT "0 < c1 < c2 < c3"
CHECK ( 0 < c1 AND c1 < c2 AND c2 < c3 ) );

INSERT t VALUES ( 1, 2, 3 ); -- OK
INSERT t VALUES ( 2, 2, 2 ); -- fails
The second INSERT fails with this message: Constraint '0 < c1 < c2 < c3' vio-
lated: Invalid value for column 'c2' in table 't'.

1.13.2 PRIMARY KEY Table Constraint


A PRIMARY KEY table constraint must include a list of one or more column
names that make up the primary key. None of these columns can hold a NULL
value, and their combined values must be unique for every row.
<primary_key_table_constraint> ::= [ <constraint_prefix> ] PRIMARY KEY
[ <clustering> ]
"(" <column_name_list> ")"
<column_name_list> ::= <column_name> { "," <column_name> }
Primary keys consisting of more than one column are often called composite
primary keys. Here is an example of an audit trail table that can contain multi-
ple copies of the same row from another table, with a date/time column ensuring
that each copy has a unique primary key:
CREATE TABLE audit_office (
copied TIMESTAMP DEFAULT TIMESTAMP,
office_code VARCHAR ( 10 ),
country_code VARCHAR ( 2 ),
PRIMARY KEY ( copied, office_code ) );

Tip: Use DEFAULT TIMESTAMP instead of DEFAULT CURRENT TIMESTAMP if


you want different values assigned no matter how fast rows are inserted. The
DEFAULT_TIMESTAMP_INCREMENT option ensures each value is at least 1
microsecond apart, but it applies only to DEFAULT TIMESTAMP, not DEFAULT
CURRENT TIMESTAMP.

The unique index automatically created on the primary key columns may be
defined as CLUSTERED or NONCLUSTERED, with NONCLUSTERED
being the default. For more information about clustered indexes, see Section
10.7, CREATE INDEX.

Potrebbero piacerti anche