PostgreSQL Error 20000 Case Not Found: How to Fix
In this article
PostgreSQL error 20000, 'case not found', occurs when a CASE expression in SQL does not match any of its WHEN conditions and lacks an ELSE clause. This error stops query execution because PostgreSQL requires every CASE block to have a defined outcome for all possible inputs. The fix is simple: always include an ELSE clause, even if it returns NULL or a default value. This ensures the expression never leaves a value undefined.
What You'll Need
- Access to a PostgreSQL database (version 9.0 or later)
- SQL client or tool (like psql, pgAdmin, DBeaver, or any interface that runs SQL)
- Permission to run SELECT, UPDATE, or INSERT statements on the affected tables
- The exact SQL query that triggered the error
Step-by-Step
- Locate the CASE expression in your SQL query that is causing the error. Look for any block starting with CASE and ending with END, especially within SELECT, UPDATE, or WHERE clauses.
- Review all WHEN conditions within the CASE block. Each WHEN must have a condition (e.g., WHEN status = 'active' THEN 1) followed by a THEN result. If a value is provided that doesn’t match any WHEN, and there’s no ELSE, the error triggers.
- Identify the data type of the column or expression being evaluated. For example, if you’re evaluating a VARCHAR column like 'status', ensure your WHEN conditions cover all possible values that could exist in that column, including NULL, empty strings, or unexpected entries like 'inactive', 'pending', or 'archived'.
- Add an ELSE clause at the end of the CASE block. For example: ELSE NULL or ELSE 'unknown' or ELSE 0. The value must match the data type of your THEN results. If your THEN clauses return integers, ELSE must return an integer. If they return text, ELSE must return text.
- Test the updated query with sample data. Run it on a small subset of records first, using a LIMIT clause if needed. For example: SELECT id, CASE WHEN status = 'active' THEN 1 WHEN status = 'pending' THEN 2 ELSE 0 END AS status_code FROM orders LIMIT 10;
- If the query runs successfully, apply it to your full dataset. If you’re updating records, use the CASE expression in an UPDATE statement: UPDATE orders SET priority = CASE WHEN priority IS NULL THEN 'medium' ELSE priority END WHERE priority NOT IN ('high', 'low', 'medium');
- Verify the results. Check that no rows are returning NULL unexpectedly unless that was your intent. Use COUNT(*) WHERE status_code IS NULL to confirm no unintended gaps exist.
- Deploy the corrected query to production only after testing in a staging environment. Always backup the table before running UPDATE queries with CASE expressions on live data.
Common Mistakes
- Assuming that NULL is automatically handled by CASE — it isn’t. You must explicitly write WHEN column IS NULL THEN ...
- Using different data types in THEN clauses (e.g., one returns text, another returns integer). PostgreSQL will throw a type mismatch error before the case not found error, but if resolved incorrectly, you may still miss the ELSE clause.
- Forgetting to include ELSE in dynamic queries generated by code (e.g., Python or Node.js). The CASE logic might work for 95% of cases but fail on edge data.
- Testing only with clean data. If your source data contains typos (e.g., 'Active' instead of 'active'), your WHEN conditions won’t match, and without ELSE, the error appears.
- Using CASE in a WHERE clause without an ELSE — this causes the condition to evaluate to NULL, which is treated as false, and may silently exclude rows. Always use ELSE in WHERE conditions too.
Tips
- Always write the ELSE clause first in your mind before writing the WHEN conditions. Think: "What happens if none of these match?"
- Use CASE with EXISTS or IN clauses when possible. For example, instead of multiple WHEN status = 'x' THEN y, use WHEN status IN ('x', 'y', 'z') THEN value.
- Log unexpected values by wrapping your CASE in a subquery and selecting the original column alongside the result. This helps identify source data issues: SELECT original_status, CASE WHEN ... ELSE 'unknown' END AS mapped_status FROM table WHERE original_status NOT IN ('known_value1', 'known_value2');
- Use COALESCE() as an alternative for simple NULL fallbacks, but remember it doesn’t handle non-NULL unmatched values — CASE is still needed for complex logic.
- Document your CASE statements with comments in production code. Explain why each WHEN condition exists and what the ELSE value represents.
- Use pg_statements or logging to capture the full SQL text of failed queries. This helps trace which query triggered the error in applications with many dynamic SQL fragments.
Troubleshooting
If the error persists after adding an ELSE clause, check the following:
- Ensure the ELSE clause is placed after all WHEN conditions and before END. A misplaced ELSE inside a WHEN block will cause a syntax error, not the case not found error.
- Verify the data type of the ELSE value matches all THEN values. If one THEN returns a DATE and another returns TEXT, the entire CASE expression must resolve to one type. Use CAST() if needed: CAST('default' AS TEXT).
- Check for nested CASE expressions. If a CASE block is inside another, each inner CASE must also have its own ELSE. One missing ELSE in a nested block can cause the outer error.
- Review the source data. Run SELECT DISTINCT column_name FROM table_name WHERE column_name IS NOT NULL ORDER BY column_name to see all actual values. You may be missing a condition for a value like 'N/A', '0', or 'true'.
- If using a view or function, recompile it after making changes. ALTER VIEW or CREATE OR REPLACE FUNCTION to ensure the new logic is loaded.
- Check for collation or case sensitivity issues. If your data has mixed case (e.g., 'Active' vs 'active'), use UPPER() or LOWER() in the WHEN condition: WHEN UPPER(status) = 'ACTIVE' THEN 1.
- Test the query in psql directly, outside of any application layer. This eliminates the possibility that a framework or ORM is modifying your SQL.
- If you're using a third-party tool (like Tableau or Power BI), check its SQL generation settings. Some tools auto-generate CASE expressions without ELSE clauses and may need manual override.
Frequently Asked Questions
Why does PostgreSQL throw this error instead of returning NULL?
PostgreSQL enforces explicit handling of all possible outcomes in CASE expressions to prevent silent data loss. Returning NULL by default could mask logic errors. Requiring ELSE forces developers to consciously decide what to do with unexpected values.
Can I use COALESCE instead of CASE to avoid this error?
Only for NULL handling. COALESCE() replaces NULL with a default, but it cannot evaluate multiple conditions like CASE. If you need to map 'A' to 1, 'B' to 2, and anything else to 0, you still need CASE with ELSE.
Does this error occur in stored procedures or functions?
Yes. Any PL/pgSQL function containing a CASE expression without ELSE will trigger error 20000 when executed with unmatched input. Always include ELSE in functions too.
Can this error be silenced or disabled?
No. It is a deliberate design choice in PostgreSQL to prevent ambiguous logic. There is no setting, parameter, or configuration to suppress this error. The only fix is correcting the SQL.
Does this error happen on all PostgreSQL versions?
Yes. It has been consistent since at least version 8.4 and remains in current versions (15, 16, 17). This is not a bug — it's standard behavior.
What if my CASE is in a JOIN condition?
The same rule applies. If the CASE in a JOIN ON clause has unmatched values and no ELSE, the join may fail or return unexpected results. Always add ELSE NULL or ELSE FALSE to ensure predictable behavior.