How to Use CASE Statements in SQL Server

Last updated July 25, 2026 · By the SaturnSQL team

CASE WHEN condition THEN value ... ELSE fallback END returns the first matching branch; without ELSE, non-matching rows return NULL. Use it in SELECT, WHERE, ORDER BY, and inside aggregates.

SELECT id, amount,
  CASE
    WHEN amount >= 100 THEN 'large'
    WHEN amount >= 20  THEN 'medium'
    ELSE 'small'
  END AS order_size
FROM orders;

Conditional aggregation

SELECT customer_id,
       SUM(CASE WHEN status = 'refunded' THEN amount ELSE 0 END) AS refunded_total,
       COUNT(CASE WHEN status = 'shipped' THEN 1 END) AS shipped_orders
FROM orders
GROUP BY customer_id;

Run this in SaturnSQL

SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.

Try it free

Related SQL Server guides

© 2026 Panda Capital Oy Ab. All rights reserved.