Vous êtes sur la page 1sur 1

Chapter 1: Creating 23

Here is an example of a table used to record when the schema for a data-
base was first created; the CHECK constraint ensures that only one row can
ever exist in this table:
CREATE TABLE schema_created (
pkey INTEGER NOT NULL DEFAULT 1 CHECK ( pkey = 1 ),
created TIMESTAMP NOT NULL DEFAULT CURRENT TIMESTAMP,
PRIMARY KEY ( pkey ) );

INSERT schema_created VALUES ( DEFAULT, DEFAULT );


Here is an example of a CHECK constraint that makes sure new values are
always increasing:
CREATE TABLE t (
c1 INTEGER CHECK ( c1 > ( SELECT MAX ( c1 ) FROM t ) ) );

INSERT t VALUES ( 3 ); -- OK
INSERT t VALUES ( 4 ); -- OK
INSERT t VALUES ( 1 ); -- Fails
CHECK constraints only fail when they return FALSE. Both TRUE and
UNKNOWN values are treated as success. Thats why the first INSERT works
in the example above the table t is empty, SELECT MAX ( c1 ) FROM t
returns NULL, and the CHECK constraint returns UNKNOWN.
The second INSERT works because 4 is greater than 3 so the CHECK con-
straint is TRUE.
The third INSERT fails because 1 is less than 4, the new maximum value.
An error message is produced: Constraint 'ASA92' violated: Invalid value for
column 'c1' in table 't'. The 'ASA92' is the automatically generated name
assigned to this CHECK constraint because no constraint name was specified in
the CREATE TABLE.
You can make these error messages more meaningful by assigning your
own constraint names:
CREATE TABLE t (
c1 INTEGER CONSTRAINT "c1 must increase in value"
CHECK ( c1 > ( SELECT MAX ( c1 ) FROM t ) ) );
Now the error message will look like Constraint 'c1 must increase in value'
violated: Invalid value for column 'c1' in table 't'.

Tip: Every name and identifier in SQL Anywhere can be up to 128 characters
in length, and you can use long phrases with spaces and special characters if
you surround the name in double quotes or square brackets.

1.10.3 PRIMARY KEY Column Constraint


A PRIMARY KEY column constraint specifies that this column may contain
only non-NULL values that are all different from one another. A unique index is
automatically created for every PRIMARY KEY constraint so you dont have to
define one yourself. This index may be defined as CLUSTERED or
NONCLUSTERED, with NONCLUSTERED being the default. For more infor-
mation about clustered indexes, see Section 10.7, CREATE INDEX.
Every table should have a primary key. They are invaluable for defining
hierarchical and other relationships among different tables, and they are very
important for performance.

Vous aimerez peut-être aussi