What is a CASE expression and how would you use it inside a SELECT or ORDER BY clause?

Last updated 3 July 2026

A CASE expression is SQL's inline if/then/else: it evaluates conditions in order and returns the first matching result. It's an expression, not a statement, so it can appear anywhere a value is expected.

  • Two forms:

    • Searched: CASE WHEN condition THEN ... ELSE ... END, each branch a full boolean test.

    • Simple: CASE expr WHEN value THEN ... END, compares one expression to values.

  • In SELECT: Derive labels/buckets or do conditional aggregation like SUM(CASE WHEN ... THEN 1 ELSE 0 END).

  • In ORDER BY: Impose custom sort priority, e.g. push a status to the top regardless of alphabetical order.

  • Returns NULL if no branch matches and no ELSE is given.

[lang:sql] SELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END AS grade FROM students ORDER BY CASE WHEN status = 'active' THEN 0 ELSE 1 END, name;

  • https://dev.to/ranggakd/comparing-if-iif-and-case-1dg1
  • https://www.postgresql.org/docs/current/functions-conditional.html
  • https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-ver17
  • https://hyring.com/jobseeker-toolkit/interview-questions/technical/sql
  • https://learn.microsoft.com/it-it/sql/t-sql/language-elements/case-transact-sql?view=sql-server-ver17
  • https://www.stratascratch.com/blog/a-comprehensive-guide-to-case-when-statements-in-sql
  • https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver17
  • https://www.youtube.com/watch?v=Y9DgMIaK2Cs
All SQL interview questions