Docs
Docs/Advanced SQL/CASE Expressions

CASE Expressions

Add conditional logic to queries

CASE expressions add if-then-else logic to your SQL queries.

Simple CASE

-- Map values
SELECT 
    name,
    status,
    CASE status
        WHEN 'A' THEN 'Active'
        WHEN 'I' THEN 'Inactive'
        WHEN 'P' THEN 'Pending'
        ELSE 'Unknown'
    END AS status_label
FROM users;

Searched CASE

-- Conditional logic
SELECT 
    name,
    total,
    CASE
        WHEN total >= 1000 THEN 'Premium'
        WHEN total >= 500 THEN 'Standard'
        WHEN total >= 100 THEN 'Basic'
        ELSE 'Minimal'
    END AS tier
FROM orders;

CASE in Aggregations

-- Pivot-style counting
SELECT 
    COUNT(*) AS total,
    COUNT(CASE WHEN status = 'active' THEN 1 END) AS active,
    COUNT(CASE WHEN status = 'inactive' THEN 1 END) AS inactive,
    SUM(CASE WHEN status = 'active' THEN total ELSE 0 END) AS active_revenue
FROM orders;

CASE in ORDER BY

-- Custom sort order
SELECT * FROM tasks
ORDER BY 
    CASE priority
        WHEN 'urgent' THEN 1
        WHEN 'high' THEN 2
        WHEN 'medium' THEN 3
        WHEN 'low' THEN 4
        ELSE 5
    END;

Need help?

Join our Discord community for support and discussions.

Join Discord