DEFERRABLE
DEFERRABLE is a constraint attribute in SQL that specifies that the enforcement of the constraint can be postponed until the end of a transaction. This enables a transaction to insert data to a database even though it initially violates a constraint, provided that the violation is corrected before the transaction commits. When a constraint is declared as DEFERRABLE, a temporary violation is allowed in a specific scope of the transaction, known as the deferrable time.
Example
Output
Explanation
In the above code, a circular self-referential constraint is implemented on the Employees
table, where supervisor_ID
references the ID
of the same table. The DEFERRABLE
keyword makes it possible to delay the checking of the constraint until the end of the transaction. By further specifying INITIALLY DEFERRED
, it enforces that the constraint checking will always be deferred till the transaction’s end. The data insertion doesn’t violate the foreign key constraint as the check is performed after both insertions are executed.
Example
Output
The above SQL command will create a test_table
if it doesn’t already exist.
Explanation
The keyword DEFERRABLE
means that the integrity checks for a foreign key constraint can be deferred until the end of the transaction. INITIALLY DEFERRED
means that in every transaction, the enforcement of the constraint is deferred by default.
This can be useful when the manager_id needs to reference a person_id that hasn’t been inserted yet. If the constraint was not deferrable, this process could fail due to the foreign key constraint. However, by making it deferrable, the check is delayed until the end of the transaction, allowing all the necessary inserts to happen first.