SQL CASE

If-then-else logic in queries.

✍️ 3 exercises + code challenge in this lesson

The CASE expression returns a value based on conditions, like if/else:

CASE
  WHEN condition1 THEN result1
  WHEN condition2 THEN result2
  ELSE result
END

It can be used in SELECT, ORDER BY, UPDATE and inside aggregate functions.

Key Takeaways: SQL CASE

Mastering SQL CASE helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

SQL CASE Code Example

SQL
SELECT ProductName, Price,
  CASE
    WHEN Price >= 50000 THEN 'Premium'
    WHEN Price >= 5000  THEN 'Standard'
    ELSE 'Budget'
  END AS PriceBand,
  CASE WHEN Stock = 0 THEN 'Out of stock' ELSE 'Available' END AS Availability
FROM Products
ORDER BY Price DESC;
Free sign-in required · Google login available

SQL CASE Practice Exercises

Check what you learned in “SQL CASE”.

/ 3 solved
Fill in the blank

Finish the CASE expression.

CASE WHEN Stock = 0 THEN 'Out' ELSE 'In stock' 
✓ Correct! Not quite. Try again.
Multiple choice

What does CASE return when no WHEN matches and there is no ELSE?

✓ Correct! Not quite. Try again.
Code challenge

Select ProductName and a column Size that is 'Big' when Price >= 50000, otherwise 'Small', for ProductID 1 to 3, sorted by ProductID.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services