SQL Query

PostgreSQL: SQL CASE WHEN Statement Examples

PostgreSQL guide: Add conditional logic to queries using CASE WHEN THEN ELSE END.

This guide is specifically for PostgreSQL syntax.

SQL CASE WHEN Statement Examples

Add conditional logic to queries using CASE WHEN THEN ELSE END.

Quick Answer

SELECT name, CASE WHEN salary > 50000 THEN 'High' ELSE 'Low' END as level FROM employees;

Explanation

CASE evaluates conditions in order and returns the result when a condition is true. ELSE handles unmatched cases. Always end with END.

Query Variants

Simple

SELECT name, CASE WHEN salary > 100000 THEN 'Executive' WHEN salary > 50000 THEN 'Senior' ELSE 'Junior' END as level FROM employees;

In Aggregate

SELECT department, SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) as male_count, SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) as female_count FROM employees GROUP BY department;

In Orderby

SELECT * FROM tasks ORDER BY CASE priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END;

Pro Tips

  • Conditions are evaluated in order
  • ELSE is optional but recommended
  • Can be used in SELECT, WHERE, ORDER BY

Related SQL Queries

Continue learning with more SQL query examples:


PostgreSQL-Specific Notes

This page covers PostgreSQL syntax. Other databases may have different syntax for similar operations.

Related Content

Try it yourself

Practice this query in our interactive SQL sandbox.