Unique Constraint
The UNIQUE
constraint ensures that an attributes value is unique within its column.
When inserting a row it checks if the value is already in the table.
It the value exists it rejects the change and issues an error.
Syntax
CREATE TABLE <table-name> (
<column-name> <column-type>,
<column-name> <column-type>,
...
);
Example
CREATE TABLE Companies (
name TEXT PRIMARY KEY,
type TEXT UNIQUE,
founded INT,
hq TEXT,
stock_symbol VARCHAR(5) UNIQUE
);
Primary vs. Unique keys
- There can be only one
PRIMARY KEY
for a relation, but severalUNIQUE
attributes. - No attribute of a
PRIMARY KEY
can ever beNULL
in any tuple.- But attributes declared
UNIQUE
may have NULL’s, and there may be several tuples withNULL
.
- But attributes declared