Back to results for “Fundamentals”
SQL Server › T-SQL Fundamentals & Syntax

How do CASE expressions work in T-SQL, and how can they be used to implement conditional logic directly within a SELECT statement?

Advanced

Answer

A CASE expression evaluates one or more conditions in order and returns a corresponding value for the first matching condition, or a default value if none match, letting you implement conditional logic like categorizing values or transforming data directly within a query, without needing separate application code or complex branching statements.
SELECT OrderId, Amount,
  CASE
    WHEN Amount > 1000 THEN 'High Value'
    WHEN Amount > 100 THEN 'Medium Value'
    ELSE 'Low Value'
  END AS OrderCategory
FROM Orders;
Real-world example A sales report categorizes each order as high, medium, or low value directly within the query using a CASE expression, avoiding the need to perform this categorization logic separately in the application code.

Common follow-ups: What is the difference between a simple CASE expression and a searched CASE expression?;Can a CASE expression be used inside a WHERE clause?