Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

**PostgreSQL Error 21000: What It Means & How to Fix It**

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step How to Fix
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The PostgreSQL error **21000 (cardinality violation)** occurs when a query’s execution plan assumes a specific number of rows but encounters a result set that doesn’t match expectations. This disrupts joins, aggregations, or subqueries by failing with "too few/too many rows" or "no rows returned." Unlike some errors, this one doesn’t block transactions outright—it just makes the query unusable until resolved. If left unresolved, it can cascade into performance issues or repeated failures.

What You'll Need

  • Access to PostgreSQL (local or remote) via psql, the command-line client, or a GUI tool like DBeaver, pgAdmin, or TablePlus.
  • The SQL query that triggers the error—identify the problematic join, subquery, or aggregate operation.
  • Basic knowledge of PostgreSQL indexes, query plan analysis, and how joins work (e.g., INNER JOIN vs. LEFT JOIN).
  • Optional: The execution plan output (from EXPLAIN or EXPLAIN ANALYZE) to pinpoint the violating operation.

Step-by-Step How to Fix

  1. Identify the query causing the error by running it in psql and capturing the exact statement. If you don’t have the query, reproduce the issue by running a similar one that *does* trigger the error (e.g., a misconfigured join or unfiltered aggregation). Example: SELECT COUNT(*) FROM orders WHERE customer_id IN (SELECT customer_id FROM inactive_customers) might return zero rows if no matches exist, causing cardinality issues.
  2. Generate and analyze the execution plan to spot the violating operation. Run: EXPLAIN (ANALYZE, VERBOSE) query_here; Scan for Nested Loop, Hash Join, or Sort operations with notes like: &l-> Result (actual time=1.23..1.45 rows=0 loops=1) or &l-> Limit (actual time=1.56..1.67 rows=0 loops=1). The actual rows count (often 0) confirms the cardinality mismatch.
  3. Fix the query by adjusting the join/subquery logic to handle missing rows:
    • For subqueries: Replace WHERE ... IN (...) with WHERE ... = ANY(...) or a JOIN ... ON with a default value (e.g., LEFT JOIN ... ON orders.customer_id IS NULL). Example fix: SELECT COUNT(*) FROM orders JOIN customers ON orders.customer_id = customers.id WHERE customers.is_active = TRUE; (This ensures at least one matching row exists per join condition.)
    • For aggregations: Use a COALESCE or NULLIF to force consistent row counts (e.g., GROUP BY ... HAVING COUNT(*) > 0). Example fix: GROUP BY user_id HAVING COUNT(*) > 0 skips user groups with zero records.
    • For joins with filters: Add LEFT JOIN to preserve all possible rows: Example fix: SELECT o.* FROM orders o LEFT JOIN inactive_customers ic ON o.customer_id = ic.id;
  4. Test the fix in a BEGIN/COMMIT block to avoid transaction conflicts: BEGIN; -- Run your fixed query here COMMIT; Verify the query now executes without the cardinality error.

Common Mistakes

  • Ignoring NULL values: Queries like WHERE a IN (SELECT b FROM table WHERE b IS NULL) fail because the subquery returns no rows. Use LEFT JOIN or IS NULL to handle NULLs: Fix: SELECT * FROM table t1 LEFT JOIN table t2 ON t1.id = t2.id AND t2.valid = TRUE;
  • Overusing EXISTS: While safe, EXISTS can sometimes behave unexpectedly in complex queries. Prefer JOIN ... ON for clarity and performance.
  • Assuming distinct counts: If you expect distinct rows but get duplicates, use DISTINCT or GROUP BY: Example: SELECT DISTINCT user_id FROM orders;
  • Not checking for empty result sets: A query returning zero rows might appear valid but trigger cardinality errors if the plan assumes rows exist. Use SELECT COUNT(*) to test early.

Tips

  • Use EXPLAIN ANALYZE wisely: While it’s powerful, running it on every query can slow down small operations. Reserve it for troubleshooting.
  • Optimize indexes: A missing index on a join column (e.g., CREATE INDEX idx_customer ON orders(customer_id)) can force expensive scans, increasing cardinality risks.
  • Test with synthetic data: Create temporary test tables with known row counts to isolate whether the issue is logic (query) or data (missing rows).
  • Watch for recursive queries: If using WITH RECURSIVE, ensure base cases cover all edge cases (e.g., zero rows).
  • Use pg_stat_statements for patterns: Enable in PostgreSQL to track queries causing cardinality errors: Setup: ALTER SYSTEM SET pg_stat_statements.track_ddl = on; SELECT * FROM pg_stat_statements; then identify problematic queries.

Troubleshooting

If the fix doesn’t work, try these troubleshooting steps in order:

  1. Verify the query structure: Run the query in a separate session or editor to confirm it’s syntactically correct. Paste it here to share if needed.
  2. Check for data corruption: Run VACUUM FULL to compact tables or ANALYZE to update statistics if the database appears "stuck" with stale row counts.
  3. Temporarily disable filters: Isolate the problematic clause by removing it one piece at a time (e.g., WHERE status = 'active'). If the error disappears, the filter is the culprit.
  4. Rewrite the query using a different approach. For example:
    • Replace JOIN ... ON ... = NULL with JOIN ... ON ... IS NULL.
    • Use FILTER clauses in window functions to avoid implicit aggregations.
  5. Recreate the issue with minimal data: Create a new table with a single row to test if the problem is data-dependent. For example: CREATE TABLE test_orders (id SERIAL, customer_id INT); INSERT INTO test_orders (customer_id) VALUES (1); Then run your original query. If it works here but fails on your data, the issue is likely data-related.
  6. Contact support: If the error persists and you’ve exhausted all logical fixes, check for:
    • PostgreSQL version bugs (e.g., 21000 was introduced in PostgreSQL 10; some edge cases exist in older versions).
    • Custom extensions or functions that might modify query plans.
    Provide the full query, execution plan, and database version (SELECT version();).

Frequently Asked Questions

Why does PostgreSQL assume a certain number of rows if the query says it should return zero?

PostgreSQL’s query optimizer uses statistics (row counts, join distributions) from ANALYZE or historical query results to generate efficient plans. If your query’s data doesn’t match expectations (e.g., a join expects 100 rows but finds 0), the optimizer fails with a cardinality violation. This happens most often with: - Subqueries that return no rows (e.g., WHERE ... IN (SELECT ... FROM table WHERE col IS NULL)). - Aggregations with GROUP BY columns missing data. - LEFT JOINs with filters that exclude all rows (e.g., LEFT JOIN ... ON t1.col = t2.col WHERE t2.col IS NULL).

How can I force PostgreSQL to ignore cardinality errors for a query that *should* return zero rows?

You can’t directly override cardinality checks, but you can redesign the query to avoid them: - Replace WHERE ... IN (...) with JOIN ... ON and handle NULLs explicitly: SELECT o.* FROM orders o LEFT JOIN customers c ON o.customer_id = c.id; - Use LEFT JOIN ... ON t1.col = t2.col AND t2.col IS NULL to preserve rows. - Wrap the query in a SELECT DISTINCT if duplicates are causing issues.

What’s the difference between a cardinality violation and a "no rows returned" error?

- **Cardinality violation (21000)**: The query planner expects a certain number of rows (e.g., 100) but encounters an unexpected count (e.g., 0 or 500). This is about *execution plans* and is often silent unless you run EXPLAIN. - **No rows returned**: The query *actually* returns zero rows, which is a separate error (e.g., due to a filter like WHERE x = 'never_exists'). Cardinality violations are silently ignored by the planner until you inspect the plan.

Can I use a different join type to avoid cardinality issues?

Yes! Replace problematic joins with these alternatives: - **INNER JOIN → LEFT JOIN**: Preserves all rows from the left table, even if no matches exist. SELECT o.* FROM orders o LEFT JOIN customers c ON o.customer_id = c.id; - **JOIN ... ON ... = NULL → JOIN ... ON ... IS NULL**: Explicitly handle NULLs. - **Semi-Joins → EXISTS**: Replace WHERE exists(...) with JOIN ... ON if the EXISTS clause is ambiguous.

What if the error persists after adjusting the query?

The issue might be: - **Data corruption**: Run VACUUM FULL to resolve metadata issues. - **Version-specific bug**: Check PostgreSQL’s release notes for known cardinality issues in your version. - **Custom extensions**: Some extensions (e.g., full-text search) modify query plans unpredictably. Test with a minimal reproducible case (e.g., a single-row table) to isolate the problem.

How do I prevent cardinality violations in the future?

1. Always run EXPLAIN (ANALYZE) before execution to spot plan issues. 2. Use pg_stat_statements to track patterns (e.g., queries returning zero rows too often). 3. Design queries to handle missing data: - Prefer LEFT JOIN over INNER JOIN. - Use COALESCE or NULLIF to avoid NULL-driven errors. - Test with edge cases (empty tables, NULL values) early in development.