Deferred Foreign Key Constraints
Defer constraint checking to transaction commit for circular references and batch operations.
-- Create tables with deferrable constraints
CREATE TABLE departments (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
manager_id INT
);
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
department_id INT NOT NULL
REFERENCES departments(id)
DEFERRABLE INITIALLY DEFERRED
);
ALTER TABLE departments
ADD CONSTRAINT fk_manager
FOREIGN KEY (manager_id) REFERENCES employees(id)
DEFERRABLE INITIALLY DEFERRED;
-- Now we can insert both in one transaction
BEGIN;
INSERT INTO departments (id, name, manager_id) VALUES (1, 'Engineering', 1);
INSERT INTO employees (id, name, department_id) VALUES (1, 'Alice', 1);
COMMIT; -- Constraints checked hereUse Cases
- Circular references
- Bulk data loading
- Schema migrations
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Optimistic Locking with Version Column
Prevent lost updates in concurrent environments using a version column for optimistic concurrency control.
Row-Level Security Policies
Enforce data access rules at the database level with PostgreSQL Row-Level Security policies.
Table Partitioning by Range
Partition large tables by date range for faster queries and easier data lifecycle management.
JSONB Query and Indexing Patterns
Query, filter, and index JSONB columns in PostgreSQL for flexible document-style data storage.