Primary and unique key constraints defined as DEFERRED / DEFERRABLE and INITIALLY IMMEDIATE enforce uniqueness at specific points during transaction execution.
1. Update Statements Modifying Multiple Rows:
UPDATE statements modifying multiple rows involving primary key swaps succeed even with INITIALLY IMMEDIATE constraints, as the constraint check is deferred until after the statement.
2. Data Modifying CTEs:
Data modifying CTEs behave similarly, except for conflicting updates, which fail due to a non-deferred primary key violation.
3. Multiple UPDATE Statements in a Transaction:
Without SET CONSTRAINTS, multiple UPDATE statements within a transaction that violate unique constraints will fail, as the check is performed after each statement.
Note: UNIQUE and PRIMARY KEY constraints are treated specially, and non-deferred constraints are checked immediately after every row modification.
To achieve standard-compliant behavior, DEFERRABLE constraints should be declared as INITIALLY IMMEDIATE, but not deferred. This may compromise performance compared to immediate uniqueness checking.
DEFERRABLE constraints cannot be used for FOREIGN KEY references, as referenced columns must be non-deferrable unique or primary key constraints.
The above is the detailed content of How Do Deferred and Immediate Constraints Affect Primary and Unique Key Enforcement in Database Transactions?. For more information, please follow other related articles on the PHP Chinese website!