CASE Statements: The IF-THEN of SQL
It's **Day 77**, and we're learning how to build our own logic into queries using the `CASE` statement.
What is a CASE Statement?
It's the SQL version of an "If-Else" block. It allows you to create new values based on existing data.
Real-World Example: Fixing Country Names
SELECT
name,
CASE
WHEN country = 'USA' THEN 'United States'
WHEN country = 'US' THEN 'United States'
WHEN country = 'U.K.' THEN 'United Kingdom'
ELSE country -- Keep the original if it doesn't match
END AS clean_country
FROM users;
Creating Categories
PMs often ask for data to be "Bucketed."
SELECT
product_name,
price,
CASE
WHEN price < 50 THEN 'Budget'
WHEN price BETWEEN 50 AND 200 THEN 'Mid-Range'
ELSE 'Premium'
END AS price_tier
FROM products;
Why it's critical
`CASE` statements allow you to normalize data *at the query level* without waiting for a database migration. It's the fastest way to fix a report that's broken by messy input.
Your Task for Today
Create a `CASE` statement that turns a numerical `status_code` (1, 2, 3) into readable text (Active, Pending, Deleted).
*Day 78: Handling Hidden Spaces—TRIM, LTRIM, RTRIM.*