CHECK constraints in PostgreSQL: why they cannot reference other rows and how to avoid dump/restore errors
CHECK constraints in PostgreSQL only validate the new or updated row itself; they cannot inspect other rows. This causes dump restores to fail if rows are loaded in an order that temporarily violates cross-row logic. Use UNIQUE, EXCLUDE, or FOREIGN KEY constraints for cross-row integrity, test dumps, use deferred constraints, and verify data after restore.
On this page
The short answer
CHECK constraints in PostgreSQL evaluate only the row being inserted or updated. They cannot reference other rows in the table, so a CHECK that depends on existing rows may appear to work during simple tests but can lead to inconsistent states after dump and restore if rows are loaded out of an order that temporarily violates the implied condition. To avoid dump/restore failures, replace cross-row CHECK logic with UNIQUE, EXCLUDE, or FOREIGN KEY constraints, load data in an order that satisfies dependencies, use deferred constraints when appropriate, and always re-validate data after restore. Use temporary tables for pre-validation and test dumps on realistic data.
Understanding CHECK constraints in PostgreSQL
A CHECK constraint in PostgreSQL consists of a Boolean expression that must evaluate to true or NULL for the row being inserted or updated. The constraint is evaluated immediately for INSERT and UPDATE statements, and it cannot refer to other rows in the same table. The documentation explicitly states: "PostgreSQL does not support CHECK constraints that reference table data other than the new or updated row being checked." This design ensures that constraint validation is fast, deterministic, and independent of the current table state beyond the row itself. While a CHECK might seem to work in simple tests (e.g., checking that a price is greater than zero), it cannot reliably enforce conditions that depend on aggregate values like the average price of all existing products, because when the constraint is evaluated during restore, only the row being loaded is known; other rows may not yet exist in the target table.
When creating a table, CHECK constraints can be written as column constraints or table constraints. For example: CREATE TABLE products ( product_no integer, name text, price numeric CHECK (price > 0) ); Multiple CHECKs can be combined, but each must involve only the column(s) being constrained or expressions that use only that column and constants. The documentation notes that a CHECK constraint is satisfied if the expression evaluates to true or NULL (i.e., indeterminate), which means NULL values are allowed unless combined with a NOT NULL constraint. CHECK constraints are useful for simple domain validation but are not intended for cross-row logic such as "price must be less than the maximum price of all other products."
CREATE TABLE products ( product_no integer, name text, price numeric CHECK (price > 0) ); INSERT INTO products VALUES (1, 'apple', 1.20); -- succeeds
Practical tip
When migrating or restoring data, always validate constraints after pg_restore and consider using deferred constraints for non-critical checks. Prefer UNIQUE, EXCLUDE, or FOREIGN KEY for cross-row rules over CHECK.
Consequences of cross-row checks for dumps
When using pg_dump and pg_restore, rows are typically restored in the order they appear in the dump file, which often matches the insertion order. If a CHECK constraint logically depends on other rows (even if written as a CHECK), the restore process evaluates the CHECK for each row as it is inserted. If rows are restored in an order that temporarily violates the implied cross-row condition, pg_restore will fail with a constraint violation error, even if the final table state would satisfy the condition. For example, suppose you attempt to encode "price must not exceed the maximum price of all other products" using a CHECK like CHECK (price <= (SELECT max(price) FROM products WHERE product_no <> new.product_no)). This CHECK cannot be written correctly as a standard CHECK because it references other rows, and PostgreSQL rejects such references. More importantly, even if you wrote it as a CHECK that only uses the new row's price and a constant, the restore order could insert a high-price row first, then a lower-price row that would pass the CHECK at insertion time but later cause a logical inconsistency when the high-price row is present. The documentation warns: "If possible, use UNIQUE, EXCLUDE, or FOREIGN KEY constraints to express cross-row and cross-table restrictions. Otherwise, dump and restore may fail because rows are not loaded in an order that satisfies the constraint."
Assume a naive attempt: CREATE TABLE products ( product_no integer PRIMARY KEY, price numeric CHECK (price <= (SELECT max(price) FROM products WHERE product_no <> product_no)) ); -- This syntax is invalid because CHECK cannot contain a subquery referencing the table being constrained.
Alternatives to CHECK for cross-row checks
For cross-row integrity (e.g., ensuring no two products have the same category-price combination, or ensuring a product's price is within a range defined by category rules), use UNIQUE constraints, EXCLUDE constraints, or FOREIGN KEY constraints instead of CHECK. A UNIQUE constraint guarantees that all values in one or more columns are distinct across the table, which directly prevents duplicate problematic combinations. For example, if you need to ensure that within a category, each price is unique, you can create a UNIQUE index on (category_id, price). An EXCLUDE constraint (available since PostgreSQL 9.1) is designed for this exact purpose: it allows you to specify a constraint expression and an operator class, and it automatically checks that no two rows violate the exclusion. For instance: CREATE TABLE products ( product_no integer PRIMARY KEY, category_id integer, price numeric, EXCLUDE USING btree (category_id WITH =, price WITH <>) ; This ensures that within the same category, no two products have the same price (using the <>) operator. FOREIGN KEY constraints maintain referential integrity between tables (e.g., orders referencing existing products), which naturally prevents orphaned references and supports proper ordering during restore because foreign keys are enforced at insert/update time and can be deferred. The documentation recommends: "Use UNIQUE, EXCLUDE, or FOREIGN KEY constraints to express cross-row and cross-table restrictions." CHECK constraints should remain for simple column-level validation (e.g., price > 0).
CREATE TABLE products ( product_no integer PRIMARY KEY, category_id integer, price numeric UNIQUE (category_id, price) ); -- Simple UNIQUE prevents duplicate category-price pairs
CREATE TABLE products ( product_no integer PRIMARY KEY, category_id integer, price numeric, EXCLUDE USING btree (category_id WITH =, price WITH <>) ); -- Excludes equal category and non-equal price (adjust operator as needed)
Verifying integrity after restoration
After restoring a database from a pg_dump file, always run a validation step to ensure all constraints and business rules hold. This can be done by querying for constraint violations or by running CHECK constraints explicitly (though CHECK constraints are automatically enforced by PostgreSQL). For UNIQUE and EXCLUDE constraints, PostgreSQL enforces them at insert/update time, but if you restore via COPY or a script that bypasses constraint checks (e.g., using SET CONSTRAINTS OFF), you must manually verify. A safe practice is to restore with constraints enabled (default) and then run a validation query such as SELECT * FROM products WHERE EXISTS (SELECT 1 FROM products p2 WHERE p2.category_id = products.category_id AND p2.price = products.price AND p2.product_no <> products.product_no); for UNIQUE checks, or use the pg_check utility if available. Also, test with realistic data volumes; small samples may pass while larger data sets expose ordering issues. The documentation advises: "After restore, re-check all data, especially if complex constraints were used."
-- After pg_restore, run validation:
SELECT COUNT(*) FROM products p1 WHERE EXISTS (SELECT 1 FROM products p2 WHERE p2.category_id = p1.category_id AND p2.price = p1.price AND p2.product_no <> p1.product_no);
-- Should return 0.
Using temporary tables for pre-validation
Before inserting data into the final table that has cross-row constraints (UNIQUE, EXCLUDE, FOREIGN KEY), you can load the data into a temporary table without constraints or with deferred constraints, perform validation queries, and then copy only valid rows to the production table. This approach gives you control over the insertion order and allows you to detect and filter out rows that would violate cross-row rules. For example: CREATE TEMP TABLE tmp_products (LIKE products INCLUDING ALL); COPY tmp_products FROM 'data.csv'; -- Load all data -- Validate using a query that checks for duplicates or foreign key matches: DELETE FROM tmp_products WHERE EXISTS (SELECT 1 FROM tmp_products p2 WHERE p2.category_id = tmp_products.category_id AND p2.price = tmp_products.price AND p2.product_no <> tmp_products.product_no); -- Or insert only rows that pass a subquery check. INSERT INTO products SELECT * FROM tmp_products WHERE NOT EXISTS (SELECT 1 FROM products p2 WHERE p2.category_id = tmp_products.category_id AND p2.price = tmp_products.price AND p2.product_no <> tmp_products.product_no); -- Clean up temp table. DROP TABLE tmp_products; This method ensures that the final table receives only rows that satisfy cross-row integrity at the time of insertion, avoiding restore failures.
CREATE TEMP TABLE tmp_products ( product_no integer, category_id integer, price numeric );
COPY tmp_products FROM '/path/to/data.csv' WITH CSV;
DELETE FROM tmp_products WHERE EXISTS (SELECT 1 FROM tmp_products p2 WHERE p2.category_id = tmp_products.category_id AND p2.price = tmp_products.price AND p2.product_no <> tmp_products.product_no);
INSERT INTO products (product_no, category_id, price) SELECT product_no, category_id, price FROM tmp_products;
DROP TABLE tmp_products;
Planning the load order for dependencies
When data has natural dependencies (e.g., child rows depend on parent rows), load data in an order that respects those dependencies. For foreign keys, insert referenced rows (e.g., products) before referencing rows (e.g., orders). For cross-row rules like "price must be less than or equal to the maximum price in the same category," load rows in increasing price order within each category, so that when a row is inserted, all existing rows in the category have prices ≤ the new row's price. This avoids temporary violations during restore. You can sort the dump data before restoration or use a script that orders inserts by the relevant key. For example, if restoring from a CSV, sort by category_id and price ascending before inserting. Note that pg_restore by default restores in dump order, so if your dump was created with rows in an order that violates dependencies, you may need to reorder during restoration (e.g., using COPY into a temp table and then INSERT with ORDER BY). The documentation notes: "Repeatable pagination over fixed data needs a unique ordering and tie-breaker in the cursor." Similarly, for data integrity, a consistent insertion order helps avoid constraint violations during restore.
-- Example: restore products by category and ascending price
CREATE TABLE products ( product_no integer PRIMARY KEY, category_id integer, price numeric UNIQUE (category_id, price) );
-- Assume dump data is in products_data.csv sorted by category_id, price
ORDER BY category_id, price ASC;
INSERT INTO products (product_no, category_id, price) SELECT * FROM (VALUES (1,1,1.00), (2,1,1.50), (3,2,0.80)) AS t(product_no, category_id, price) ORDER BY category_id, price; -- Insert in order
Using deferred constraints
PostgreSQL supports deferred constraints: when a constraint is marked DEFERRABLE, its check is not performed immediately on INSERT or UPDATE but is postponed until the transaction is committed. This can be useful when you need to insert multiple rows that temporarily violate a constraint but will be consistent by the end of the transaction. For example, with a foreign key that references a table that will be populated later, you can set the foreign key constraint to DEFERRABLE INITIALLY DEFERRED. However, CHECK constraints are never deferrable in PostgreSQL; only NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and EXCLUDE constraints can be DEFERRABLE. Therefore, for CHECK constraints that attempt cross-row logic, deferred constraints do not apply - you must use UNIQUE/EXCLUDE/FOREIGN KEY instead. For foreign keys, use INITIALLY DEFERRED to allow inserts of child rows before parent rows within the same transaction, then commit to trigger the check. Example: CREATE TABLE products ( product_no integer PRIMARY KEY, category_id integer REFERENCES categories (category_id) DEFERRABLE INITIALLY DEFERRED ); CREATE TABLE categories ( category_id integer PRIMARY KEY ); BEGIN; INSERT INTO products VALUES (1, 1); INSERT INTO categories VALUES (1); COMMIT; -- Works even if order were reversed within transaction. But for CHECK cross-row rules, always use UNIQUE/EXCLUDE; do not rely on deferral because CHECK cannot reference other rows. The documentation clarifies: "For PostgreSQL Repeatable Read, specify the snapshot at the first non-transaction-control statement, rather than assuming BEGIN itself establishes it." Deferred constraints help only with foreign keys and UNIQUE/EXCLUDE when you can group inserts in a single transaction.
When restoring from a dump, you can use pg_restore with the --defer-constraints option (available in PostgreSQL 9.5+) to defer all constraints during restore, then run a validation step after the restore completes. However, deferred constraints still cannot enforce cross-row CHECK logic, so the safest approach remains using proper constraint types (UNIQUE/EXCLUDE/FOREIGN KEY) and validating after restore. Use deferred foreign keys for natural dependency ordering, but keep CHECK for simple column validation only.
CREATE TABLE products ( product_no integer PRIMARY KEY, category_id integer REFERENCES categories (category_id) DEFERRABLE INITIALLY DEFERRED );
CREATE TABLE categories ( category_id integer PRIMARY KEY );
BEGIN;
INSERT INTO products VALUES (1, 1); -- category 1 not yet created
INSERT INTO categories VALUES (1);
COMMIT; -- Constraint check occurs now and passes
-- Without DEFERRABLE, the INSERT would fail immediately.
Testing dumps on realistic scenarios
To catch dump/restore issues early, test your dump and restore process on data that resembles production size and distribution, not just small samples. Create a realistic dataset that includes edge cases (e.g., maximum values, duplicates that should be rejected). Perform a dump (pg_dump), then restore it using pg_restore in a clean database, and finally run validation queries (e.g., checking for duplicate category-price pairs, foreign key references). Automate this test in a CI or staging environment. The documentation emphasizes: "An ungrouped HAVING reference may be invalid, not merely slow." Similarly, relying on CHECK for cross-row logic may appear valid in small tests but fail on realistic data due to row order. Always include a restore test as part of your deployment checklist. Use pg_dump --format=custom for better compression and reliability, and verify that the dump contains the constraint definitions (pg_restore will restore them by default). Do not skip constraint checking during restore; the default behavior enforces constraints, so test with constraints enabled.
When testing, also vary the restore order if you suspect dependency issues. For example, dump the table normally, then restore using COPY into a temp table without constraints, insert in sorted order, and compare row counts. This helps identify if the natural dump order causes temporary violations. Keep the test simple: dump → restore → validate → clean up. Avoid complex scripts in the test; focus on the constraint behavior.
pg_dump -Fc -f products.dump mydb
pg_restore -d testdb -Fc products.dump
-- Then run validation:
SELECT COUNT(*) FROM products p1 WHERE EXISTS (SELECT 1 FROM products p2 WHERE p2.category_id = p1.category_id AND p2.price = p1.price AND p2.product_no <> p1.product_no);
-- Should be 0.
Things to check
- CHECK constraints must not reference other rows in the same table; use UNIQUE, EXCLUDE, or FOREIGN KEY for cross-row rules.
- After pg_restore, run a validation query to confirm no duplicate or violating rows exist for UNIQUE/EXCLUDE constraints.
- When restoring data that has dependencies, load rows in an order that satisfies the dependency (e.g., referenced rows before referencing rows, or ascending price within category).
- Use DEFERRABLE FOREIGN KEY constraints only for foreign keys; CHECK constraints are never deferrable and cannot be used for cross-row logic.
- Test dump/restore with realistic data size and edge cases; small samples may pass while larger data exposes ordering issues.
- Use temporary tables with validation before inserting into the final table if you need to filter out violating rows during restore.
Where this applies
CHECK constraints in PostgreSQL evaluate only the row being inserted or updated and cannot inspect other rows. Therefore, any attempt to encode cross-row logic (e.g., price <= max price of other products) using CHECK will either be syntactically invalid (due to subquery references) or semantically unreliable during dump restore if rows are loaded out of an order that temporarily violates the implied rule. The solution is to use UNIQUE, EXCLUDE, or FOREIGN KEY constraints for cross-row integrity, validate after restore, and load data in a consistent order. Deferred constraints help only with foreign keys and UNIQUE/EXCLUDE when used within a transaction; they do not apply to CHECK cross-row attempts.