Sub topic 9
Integrity Constraints: Domain, Entity, and Referential
This chapter assumes you know what a relation, tuple, attribute, and domain are, and that you can tell a superkey from a candidate key and a primary key. It also assumes you can read basic CREATE TABLE statements. Referential actions get their own chapter. Here we cover the constraint types and how a database enforces them.
What an integrity constraint is
An integrity constraint is a rule that every legal database state must satisfy. The DBMS checks the rule when data changes. It rejects any INSERT, UPDATE, or DELETE that would leave the database in an illegal state.
GATE CS usually names four kinds of constraint:
| Constraint | What it restricts | Typical SQL |
|---|---|---|
| Domain | The values one attribute may hold | Data type, `NOT NULL`, `CHECK`, `DEFAULT` |
| Key | No two tuples agree on the key attributes | `UNIQUE`, `PRIMARY KEY` |
| Entity integrity | The primary key is never null | `PRIMARY KEY` |
| Referential integrity | A foreign key matches an existing key or is null | `FOREIGN KEY ... REFERENCES` |
Domain constraints
A domain constraint says each attribute value must come from the attribute's domain, and the value must be atomic. The domain is set by the data type and narrowed by extra rules.
- A data type such as
INTorVARCHAR(50)rejects values of the wrong kind. NOT NULLforbids the null value.CHECK (condition)accepts a row only if the condition is not false.DEFAULT valuesupplies a value when none is given.
A CHECK condition that evaluates to unknown passes. This is a common trap. If salary is null, then salary > 0 is unknown, so the row is accepted. To forbid nulls, add NOT NULL as well.
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50) NOT NULL,
salary NUMERIC(10,2) CHECK (salary > 0)
);Key constraints
A key constraint says that no two tuples in a relation may have the same values for the key attributes. Every relation has at least one candidate key, because the set of all attributes is a superkey and a relation is a set of distinct tuples. UNIQUE declares a candidate key. PRIMARY KEY declares the chosen one.
UNIQUE columns may hold nulls in standard SQL. Two null values are not treated as equal, so several rows with a null in a UNIQUE column are allowed. Some products differ here, so check your DBMS before relying on this.
Entity integrity
The entity integrity rule says no attribute of a primary key may be null in any tuple. The reason is that the primary key identifies a tuple. A tuple with a null key part cannot be told apart from other tuples reliably.
In SQL, PRIMARY KEY implies NOT NULL on every column of the key, including each column of a composite key. A candidate key declared with UNIQUE is not covered by this rule.
Referential integrity
Referential integrity connects two relations. Let R1 have a foreign key FK that refers to the primary key PK of R2. The rule is:
- Each non-null value of
FKin a tuple ofR1must equal thePKvalue of some tuple inR2. FKmay be null, unless it is also declaredNOT NULLor is part of a primary key.
R1 is the referencing (child) relation. R2 is the referenced (parent) relation. The two attributes must have compatible domains. The foreign key does not have to share a name with the key it references. A relation can reference itself, as in a manager_id column that points to emp_id in the same table.
CREATE TABLE department (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50) NOT NULL,
salary NUMERIC(10,2) CHECK (salary > 0),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES department(dept_id)
ON DELETE SET NULL
ON UPDATE CASCADE
);Here employee.dept_id is the foreign key. An employee row with dept_id = NULL is legal. A row with dept_id = 99 is legal only if a department with dept_id = 99 exists.
Which operations can violate which constraint
GATE questions often ask which operation can break which rule. The table below shows this for a parent relation R2 and a child relation R1.
| Operation | Domain | Key | Entity | Referential |
|---|---|---|---|---|
| Insert into `R1` (child) | Possible | Possible | Possible | Possible: no matching parent |
| Insert into `R2` (parent) | Possible | Possible | Possible | Cannot violate |
| Delete from `R1` (child) | Cannot violate | Cannot violate | Cannot violate | Cannot violate |
| Delete from `R2` (parent) | Cannot violate | Cannot violate | Cannot violate | Possible: orphaned children |
| Update a non-key attribute | Possible | Cannot violate | Cannot violate | Cannot violate |
| Update the primary key of `R2` | Possible | Possible | Possible | Possible: orphaned children |
| Update the foreign key of `R1` | Possible | Cannot violate | Cannot violate | Possible: no matching parent |
The pattern is simple. Inserting into a child and deleting from a parent are the two operations that threaten referential integrity. Deleting from a child never causes a violation.
What happens when a parent row is deleted
When a delete or key update on the parent would orphan child rows, the DBMS takes one of several actions, chosen in the foreign key definition.
RESTRICTorNO ACTIONrejects the operation.CASCADEapplies the same delete or update to the matching child rows.SET NULLsets the child foreign key to null. This needs a nullable foreign key.
The default is NO ACTION. The next chapter covers these actions in detail.
Edge cases to remember
- A foreign key may reference a candidate key declared
UNIQUE, not only the primary key. Many systems also require the referenced columns to be unique. - A composite foreign key must match a whole composite key. Under the default matching rule in SQL, if any column of a composite foreign key is null, the row is not checked against the parent.
- A foreign key that is part of a primary key cannot be null. For example,
dependent(emp_id, dependent_name)referencesemployeeand cannot have a nullemp_id. - Self-referencing tables make deletion order matter. Deleting a manager row can orphan subordinates unless an action is chosen.
- Constraint checks run per statement by default. A
DEFERRABLEconstraint lets a transaction postpone the check until commit. This helps when two tables reference each other.
Worked example
Consider these relations. The primary keys are underlined in the textbook form. Here they are dept_id and emp_id.
department(dept_id, dept_name)
(10, Sales), (20, HR)
employee(emp_id, emp_name, dept_id)
(1, Asha, 10), (2, Ravi, 20), (3, Meena, NULL)Test each statement against employee.dept_id referencing department.dept_id:
INSERT INTO employee VALUES (4, 'Kiran', 30)is rejected. No department hasdept_id = 30.INSERT INTO employee VALUES (5, 'Dev', NULL)is accepted. A null foreign key is allowed.INSERT INTO employee VALUES (NULL, 'Zed', 10)is rejected by entity integrity, becauseemp_idis the primary key.INSERT INTO employee VALUES (1, 'Neha', 20)is rejected by the key constraint, becauseemp_id = 1already exists.DELETE FROM department WHERE dept_id = 10is rejected underNO ACTION, because Asha refers to it. UnderON DELETE SET NULL, it succeeds and Asha'sdept_idbecomes null.
Common errors
- Saying a foreign key must not be null. It may be null unless declared otherwise.
- Saying a foreign key must be unique in the child table. Many children can share one parent.
- Saying deleting a child row can violate referential integrity. It cannot.
- Confusing key and entity integrity. Key integrity is uniqueness. Entity integrity is non-null primary keys.
- Assuming
CHECKrejects nulls.
Exercise
Relation R1(A, B) has primary key A, and B is a foreign key referencing R2(C), where C is the primary key of R2. Which single operation can violate referential integrity: (a) deleting a tuple from R1, (b) inserting a tuple into R2, (c) deleting a tuple from R2, (d) updating A in R1 to a new unused value?
Show answer
Only (c). Deleting a tuple from R2 can leave tuples in R1 whose B value no longer matches any C. Deleting from the child R1 removes references, so it is safe. Inserting into the parent R2 adds a possible match and cannot orphan anything. Updating A changes only the primary key of the child, which is not a foreign key, so it cannot break referential integrity (it could break key or entity integrity if the new value were a duplicate or null).
Exercise
A table T(X, Y) has CHECK (Y > 10) and Y is declared without NOT NULL. Is the row (1, NULL) accepted? Why?
Show answer
Yes. The condition NULL > 10 evaluates to unknown, and a CHECK constraint rejects a row only when its condition is false. To reject the row, declare Y NOT NULL.
Exercise
Table enroll(student_id, course_id, grade) has primary key (student_id, course_id). Both student_id and course_id are foreign keys. Can a row have course_id = NULL to mean "not yet assigned"?
Show answer
No. course_id is part of the primary key, so entity integrity forbids a null in it, even though a plain foreign key column could be null.