Data types and expressions
CASE expressions
Choose a result value from ordered conditions without changing stored rows.
Lesson 21 of 84
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Beginner
On this page4 sections
This lesson uses the unmodified DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Choose a result value from ordered conditions without changing stored rows.
Run the example
sql
SELECT OrderID, OrderStatus,
CASE WHEN OrderStatus IN (N'Shipped', N'Completed')
THEN N'Final' ELSE N'Open' END AS StatusGroup
FROM dbo.Orders
WHERE OrderID <= 4
ORDER BY OrderID;Read it step by step
- WHERE restricts the example to four known orders.
- CASE tests the final statuses first; ELSE labels every other status Open.
- CASE returns a value per row. It does not update OrderStatus.
Check the result
| OrderID | OrderStatus | StatusGroup |
|---|---|---|
| 1 | Cancelled | Open |
| 2 | Pending | Open |
| 3 | Shipped | Final |
| 4 | Completed | Final |
The result includes all four selected orders in OrderID order.
Practice
Label Products 1, 2, and 4 as Premium when ListPrice is at least 100, otherwise Standard.
Check your answer and expected result
Reveal answer
sql
SELECT ProductID, ListPrice,
CASE WHEN ListPrice >= 100 THEN N'Premium'
ELSE N'Standard' END AS PriceBand
FROM dbo.Products
WHERE ProductID IN (1, 2, 4)
ORDER BY ProductID;| ProductID | ListPrice | PriceBand |
|---|---|---|
| 1 | 39.00 | Standard |
| 2 | 129.00 | Premium |
| 4 | 8.50 | Standard |
Only ProductID 2 is Premium in this three-product sample.
Your progress
Reveal the check answer or reach the end to complete this lesson.