intended to have only one row because its keys don’t enforce that single row
constraint
2
.
What’s needed is an empty key: {}, which will have the effect of
constraining data in the table to no more than one row. The concept of an
empty key needs some more explanation, but first let’s sees how to
implement it in SQL. Unfortunately SQL doesn’t allow the column list of a
PRIMARY KEY or UNIQUE key constraint to be empty. The following is
not valid syntax:
ALTER TABLE Comp ADD CONSTRAINT X PRIMARY KEY ( );
There is a workaround however. We define a column as unique and then add
a check constraint to restrict that column to a single value. The effect is to
limit the table to at-most one row.
CREATE TABLE Comp
(X SMALLINT NOT NULL DEFAULT (1) CHECK (X=1) UNIQUE,
CompanyName VARCHAR(128) NOT NULL,
CompanyNumber VARCHAR(8) NOT NULL);
Explanation: X is required to be unique and because X is also required to be
1 there can only be one X and only one row in this table. Incidentally, this
technique generalises as well. By making the CHECK constraint <= some
number, N, instead of = 1 it is possible to limit the table to N rows.
The workaround of using the “X” column is the most widely supported
method of implementing the key in SQL. Other alternatives are also possible
without adding a “dummy” column to the table. For example by using a
subquery in a CHECK constraint or database ASSERTION.
ALTER TABLE Comp ADD CONSTRAINT X
CHECK ( ( SELECT COUNT(*) FROM Comp) = 1 );
Unfortunately, the necessary syntax for CHECK or CREATE ASSERTION
is not always supported by SQL implementations. Proprietary and vendor-
specific code may be required instead, which is something beyond the scope
of this paper.
Zero Degree Keys
Notice that in the CREATE TABLE statement for the Comp table I’ve used
a UNIQUE constraint on the X column rather than a PRIMARY KEY
constraint - even though the practical effect of using PRIMARY KEY would
have been the same. The reason for using UNIQUE instead of PRIMARY
KEY is that X is not the primary key of Comp. X is a proper superkey,
meaning that it contains more attributes than the key. As already mentioned
the key is actually the empty set: {}. In fact {} is the only possible key for a
singleton table.
A key is a minimal set of attributes that is unique across all possible values
of a relation variable. “Minimal” means that if any attribute is removed from
2. Despite its obvious weakness I
have seen examples of this
flawed implementation in print,
online and in practice. For
example, see Database Design
for Smarties by R. J. Muller, pub.
Morgan Kaufmann, 1999, page
281.