PostgreSQL CASE Expression
PostgreSQL CASE Expression
The CASE expression in PostgreSQL is used to add conditional logic inside SQL queries.
It works like if–else statements in programming languages.
1️⃣ CASE Expression Syntax
Simple CASE
Searched CASE (Most Common)
2️⃣ Simple CASE Example
3️⃣ Searched CASE Example
✔ Most widely used form.
4️⃣ CASE in WHERE Clause
✔ Filters rows conditionally.
5️⃣ CASE in ORDER BY
Custom sorting:
6️⃣ CASE with Aggregate Functions
7️⃣ CASE in UPDATE
8️⃣ CASE in JOIN Conditions
9️⃣ Nested CASE
✔ Avoid deep nesting when possible.
🔟 CASE vs IF
PostgreSQL does not support IF in SQL queries.
✔ Use CASE instead.
1️⃣1️⃣ Common Mistakes
❌ Forgetting END
❌ Mixing data types in THEN results
❌ Missing ELSE (returns NULL)
1️⃣2️⃣ Best Practices
✔ Always include ELSE
✔ Keep CASE logic readable
✔ Prefer searched CASE for complex logic
✔ Avoid CASE in JOIN when possible (performance)
