CREATE TABLE Products
(SKU INT NOT NULL PRIMARY KEY,
ProductType CHAR(1) NOT NULL
CHECK (ProductType IN ('B','C','D' /* Book, CD or DVD */)),
Title VARCHAR(50) NOT NULL,
UNIQUE (SKU,ProductType));
CREATE TABLE Books
(SKU INT NOT NULL PRIMARY KEY,
ProductType CHAR(1) DEFAULT 'B' NOT NULL, CHECK (ProductType ='B'),
Pages SMALLINT NOT NULL,
FOREIGN KEY (SKU,ProductType) REFERENCES Products (SKU,ProductType));
CREATE TABLE CDs
(SKU INT NOT NULL PRIMARY KEY,
ProductType CHAR(1) DEFAULT 'C' NOT NULL, CHECK (ProductType ='C'),
Tracks SMALLINT NOT NULL,
FOREIGN KEY (SKU,ProductType) REFERENCES Products (SKU,ProductType));
CREATE TABLE DVDs
(SKU INT NOT NULL PRIMARY KEY,
ProductType CHAR(1) DEFAULT 'D' NOT NULL, CHECK (ProductType ='D'),
Duration SMALLINT NOT NULL,
FOREIGN KEY (SKU,ProductType) REFERENCES Products (SKU,ProductType));
That’s it. The disjoint requirement is always enforced by the combination of the compound foreign key constraints
and check constraints. Although it’s extremely simple I think this is worth documenting here because I have never
seen such a solution mentioned in print. I don't claim any originality for the above and I know of others who have
used it. If anyone is aware of a good reference that describes the same technique then I’d be grateful to hear
about it so that I can attribute a source in future.
One other tiny point of interest. A colleague of mine once objected to this design because he said that the table
I've called Products violated Boyce-Codd Normal Form. I am confident that he was wrong however - there is no
violation of BCNF. In fact this schema comfortably satisfies 5NF. For the moment I’ll leave further analysis open
to anyone who wants to comment on it here...
--
See: Halpin - Information Modeling and Relational Databases; Pascal -
Practical Issues in Database Management; Date - An Introduction to
Database Systems.
Published 08 January 2007 22:35 by David.Portas
Filed under: SQL, Data Modelling
In the final paragraph above I
was wrong to ignore the
dependency {}->{ProductType}
in the Books, CDs, DVDs tables.
At the time I didn’t recognise
that this dependency on the
empty set would be a violation
of 2NF.
DP, 2016