Sub topic 21
CREATE TABLE and constraints
This chapter assumes you know what a relation, a tuple and a key are, and that you can read a simple SELECT. It covers how SQL declares tables and how constraints enforce the integrity rules from the relational model. GATE questions on this topic usually ask what happens to the rows of a table after an insert, update or delete.
From schema to CREATE TABLE
A relation schema such as Student(sid, sname, age) becomes a table definition. Each column gets a name and a data type, which plays the role of the domain. Constraints are added to the columns or to the table as a whole.
CREATE TABLE Student (
sid INT PRIMARY KEY,
sname VARCHAR(50) NOT NULL,
age INT CHECK (age >= 0),
email VARCHAR(80) UNIQUE
);
CREATE TABLE Course (
cid INT PRIMARY KEY,
cname VARCHAR(50) NOT NULL UNIQUE
);A constraint written beside one column is a column constraint. A constraint that lists several columns, or that sits after all the columns, is a table constraint. A composite key can only be written as a table constraint.
The main constraint types
| Constraint | What it enforces | NULL behaviour |
|---|---|---|
| NOT NULL | The column must have a value. | Rejects NULL. |
| UNIQUE | No two rows may agree on the listed columns. This declares a candidate key. | Allows NULL. Several NULLs are allowed in most systems, because NULL = NULL is not true. |
| PRIMARY KEY | UNIQUE plus NOT NULL. A table has at most one. | Rejects NULL in every key column. |
| FOREIGN KEY | Each non-NULL value must appear in the referenced key. | A NULL foreign key value is not checked. |
| CHECK | A condition on the row must not be false. | Passes when the condition is UNKNOWN. |
The last row of the NULL column matters. CHECK rejects a row only when the condition evaluates to FALSE. If age is NULL, the condition age >= 0 is UNKNOWN, so the row is accepted. This follows from the three-valued logic covered in the NULL chapter.
Keys in SQL
PRIMARY KEY and UNIQUE correspond to the key notions from the relational model.
- A UNIQUE constraint declares a candidate key.
- PRIMARY KEY marks the one candidate key chosen as primary.
- Any superset of a declared key is automatically a superkey, and SQL does not need to state it.
A table may have many UNIQUE constraints but only one PRIMARY KEY.
Foreign keys and referential integrity
A foreign key says that values in the child table must match a key value in the parent table. The referenced column must be a primary key or have a UNIQUE constraint.
CREATE TABLE Enrolled (
sid INT,
cid INT,
PRIMARY KEY (sid, cid),
FOREIGN KEY (sid) REFERENCES Student(sid) ON DELETE CASCADE,
FOREIGN KEY (cid) REFERENCES Course(cid) ON DELETE CASCADE
);Here Enrolled is the child (referencing) table. Student and Course are parents (referenced tables). The composite primary key (sid, cid) stops the same student from enrolling in the same course twice.
Which operations can violate the constraint
Referential integrity can break in four ways.
| Operation | Table | Can it violate the foreign key? |
|---|---|---|
| Insert | Child | Yes, if the new value has no matching parent. |
| Update of the foreign key column | Child | Yes, for the same reason. |
| Delete | Parent | Yes, if child rows still refer to the row. |
| Update of the referenced key | Parent | Yes, if child rows still refer to the old value. |
| Insert | Parent | No. |
| Delete | Child | No. |
GATE often asks exactly this: which operations on which table can cause a violation. Inserting into the parent and deleting from the child are always safe.
Referential actions
When a parent row is deleted or its key is updated, the ON DELETE and ON UPDATE clauses decide what happens to the child rows.
| Action | Effect on child rows |
|---|---|
| NO ACTION (default) | The operation is rejected if child rows exist. |
| RESTRICT | Like NO ACTION. It is rejected immediately and is not deferred. |
| CASCADE | The same change is applied to the child rows. A delete removes them. An update rewrites the foreign key value. |
| SET NULL | The foreign key columns in the child rows become NULL. Those columns must allow NULL. |
| SET DEFAULT | The foreign key columns take their default value, which must itself reference an existing parent row. |
Cascading can chain. If Enrolled were itself referenced by a Grade table with ON DELETE CASCADE, deleting one student would also delete grades.
A worked example
Take these tables and rows.
CREATE TABLE Dept (
did INT PRIMARY KEY,
dname VARCHAR(30)
);
CREATE TABLE Emp (
eid INT PRIMARY KEY,
did INT,
FOREIGN KEY (did) REFERENCES Dept(did) ON DELETE SET NULL
);
INSERT INTO Dept VALUES (1, 'Sales'), (2, 'HR');
INSERT INTO Emp VALUES (10, 1), (11, 1), (12, 2), (13, NULL);Now run the following statements in order.
DELETE FROM Dept WHERE did = 1;
INSERT INTO Emp VALUES (14, 3);
INSERT INTO Emp VALUES (15, NULL);- The delete removes Sales. Employees 10 and 11 pointed to it, so SET NULL gives them did = NULL.
- The first insert fails. Department 3 does not exist, so the foreign key is violated.
- The second insert succeeds. A NULL foreign key is not checked.
After these statements Emp holds employees 10, 11, 13 and 15 with did NULL, and employee 12 with did 2.
Common errors and gotchas
- Treating UNIQUE as if it excluded NULL. A UNIQUE column can hold NULL, and most systems allow several NULLs in it.
- Assuming CHECK rejects UNKNOWN. It does not. Add NOT NULL when a missing value must also be rejected.
- Using SET NULL on a column that is NOT NULL or part of the primary key. The definition is invalid or the action fails at run time.
- Referencing a column that is not a key. A foreign key must point to a PRIMARY KEY or UNIQUE column set.
- Forgetting that a composite foreign key matches as a whole. With the default simple matching, a row with a NULL in any one of its foreign key columns is not checked at all.
- Believing that a foreign key must have the same column name as the key. Only the types must be compatible. The names can differ.
- Expecting CASCADE to be limited to one level. Cascades follow every chain of foreign keys that also use CASCADE.
Counting rows after constraints
Constraint questions often combine with counting. Two rules cover most of them.
- A PRIMARY KEY on k columns means the table never contains two rows with the same values on those columns. A table with a single-column key on a domain of n values has at most n rows.
- A foreign key with ON DELETE CASCADE can shrink the child table by more than one row for each parent row deleted, since every child row that refers to the parent is removed.
For example, if Enrolled has 5 rows for student 7 and you delete student 7 from Student, all 5 rows disappear. With NO ACTION the delete is rejected and nothing changes.
Exercise
Table Emp(eid, did) has a foreign key did referencing Dept(did) with ON DELETE CASCADE. Dept holds did values 1, 2, 3. Emp holds (10, 1), (11, 1), (12, 2), (13, NULL). You run DELETE FROM Dept WHERE did = 1. How many rows does Emp contain afterward, and which rows are they?
Show answer
Emp contains 2 rows. CASCADE removes the rows (10, 1) and (11, 1), because both refer to department 1. The rows (12, 2) and (13, NULL) remain. The NULL row never referred to any department.
Exercise
Which of these operations can never violate referential integrity: insert into the parent, delete from the parent, insert into the child, delete from the child? Give the reason for each safe one.
Show answer
Insert into the parent and delete from the child can never violate it. A new parent row adds a key value that nothing refers to yet. Removing a child row removes a reference, so no child is left without a parent. Delete from the parent and insert into the child can violate it.
Exercise
A column age has CHECK (age BETWEEN 0 AND 120) and no NOT NULL. Can you insert a row with age NULL?
Show answer
Yes. The condition evaluates to UNKNOWN for NULL, and CHECK rejects a row only when the condition is FALSE. To forbid NULL, add NOT NULL to the column.