Home >Database >Mysql Tutorial >How Does Deferral Timing Affect Unique/Primary Key Constraint Enforcement in PostgreSQL?
Deferring Unique/Primary Key Constraints: Investigating Deferral Timing
In PostgreSQL, unique and primary key constraints can be defined as either deferrable or not deferrable. Deferring constraint checks offers greater flexibility, allowing data modifications to occur before the constraint is enforced.
Enforcement Timing
When a constraint is marked as deferrable, its enforcement timing depends on its initial setting (IMMEDIATE or DEFERRED) and any subsequent changes using SET CONSTRAINTS. Here's the summary:
Example Analysis
Let's examine the given query:
UPDATE tbl SET id = t_old.id FROM tbl t_old WHERE (t.id, t_old.id) IN ((1,2), (2,1));
This UPDATE operates on multiple rows, potentially violating the unique primary key constraint. However, it succeeds because the constraint is defined as DEFERABLE INITIALLY IMMEDIATE. Per the above rules, this means the constraint check occurs after the statement has completed, allowing the changes to be applied.
CTE Behavior
Data-modifying CTEs, as seen in the example, behave similarly. Despite the order of updates being unpredictable within the CTE, the constraint check is still applied after the entire CTE has executed.
Multiple UPDATE Statements
When multiple UPDATE statements are executed within a single transaction, constraint checking depends on whether SET CONSTRAINTS is used. Without SET CONSTRAINTS, the checks occur after each statement, which could result in unique violations, as expected.
Unique/Primary Key Distinction
It's important to note that unique and primary key constraints receive special treatment in PostgreSQL. Not deferrable unique/primary key constraints are checked after each command, but PostgreSQL advises defining them as deferrable with INITIALLY IMMEDIATE for standard-compliant behavior.
Conclusion
While the behavior of deferred unique/primary key constraints may differ from expectations in certain scenarios, it's not necessarily a bug. Deferring constraint checks offers flexibility in data modification, and understanding their enforcement timing is crucial for optimizing performance and avoiding unexpected errors.
The above is the detailed content of How Does Deferral Timing Affect Unique/Primary Key Constraint Enforcement in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!