Understanding SQL Server Case Expression with Example

Add conditional, if-else style logic directly inside your SQL queries.

The CASE expression is SQL Server's way of writing conditional logic inside a query — similar to an if-else statement in programming languages. It's one of the most useful tools for turning raw column values into readable, categorized output.

Simple CASE Expression

Compares one expression against a list of possible values:

SELECT product_name,
  CASE category_id
    WHEN 1 THEN 'Electronics'
    WHEN 2 THEN 'Clothing'
    ELSE 'Other'
  END AS category_name
FROM products;

Searched CASE Expression

Evaluates a set of boolean conditions, giving you more flexibility than the simple form:

SELECT student_name, marks,
  CASE
    WHEN marks >= 90 THEN 'A Grade'
    WHEN marks >= 75 THEN 'B Grade'
    WHEN marks >= 50 THEN 'C Grade'
    ELSE 'Needs Improvement'
  END AS grade
FROM student_results;

Using CASE Inside ORDER BY

SELECT * FROM employees
ORDER BY
  CASE WHEN department = 'Sales' THEN 0 ELSE 1 END, name;
💡 Tip: A CASE expression always returns a single value — you can use it inside SELECT, WHERE, ORDER BY, and even GROUP BY clauses.

Common Use Cases

  • Converting numeric codes into readable labels
  • Building custom sort orders
  • Creating pivot-style summaries alongside SUM() or COUNT()

Once you're comfortable with CASE, you can express business rules directly in SQL — no need to push that logic into the application layer.

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with Uncodemy's Data Analytics Course.

Explore Data Analytics Course →