Español Practice SQL

SQL CASE WHEN and COALESCE

CASE is SQL’s if this, then that. COALESCE fills empty values.

SQL skills · Functions

Practice this nowLearn it step by step

Free. No sign up. Your progress stays in this browser.

What you will learn

CASE creates a new value for each row based on rules you write. It works in SELECT, WHERE, ORDER BY and GROUP BY.

COALESCE returns the first value that is not NULL, which is perfect for blank cells in a report.

The basics

CASE is how SQL says if this, then that. It creates a value per row.

SELECT customer_name, amount,
  CASE WHEN amount >= 10000 THEN 'Large'
       WHEN amount >= 2000 THEN 'Medium'
       ELSE 'Small' END AS size
FROM invoices

The database checks the WHEN lines from top to bottom and stops at the first true one, so put the highest band first. Without ELSE, rows that match nothing get NULL.

COALESCE

SELECT customer_name, COALESCE(paid_date, 'Not paid') AS paid
FROM invoices

COALESCE returns the first value that is not NULL. SQL Server also has ISNULL, Oracle and Snowflake have NVL; COALESCE works everywhere.

Worked examples

Example 1

Label invoices by size.

SELECT customer, amount,
  CASE WHEN amount >= 10000 THEN 'Large'
       WHEN amount >= 2000 THEN 'Medium'
       ELSE 'Small' END AS size
FROM invoices

The first true WHEN wins.

Example 2

Show “Not paid” instead of an empty date.

SELECT customer, COALESCE(paid_date, 'Not paid') AS paid
FROM invoices

COALESCE works in every database.

Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.

Try a task

Common mistakes

  • Checking the smallest band first, so every row lands there.
  • Forgetting ELSE and getting NULL for rows that match nothing.
  • Forgetting END.

Where you will use it at work

  • Finance: aging buckets for overdue invoices.
  • Support: SLA met or missed.
  • Marketing: campaigns above or below target.

Questions people ask

Can CASE return numbers?

Yes. SUM(CASE WHEN status = 'Won' THEN 1 ELSE 0 END) counts won deals.

COALESCE or ISNULL or NVL?

COALESCE works everywhere. ISNULL is SQL Server, NVL is Oracle and Snowflake.

Does CASE work in GROUP BY?

Yes. Group by the CASE expression to count per label.

Ready to write it yourself?

Practice CASE and COALESCE

Further reading

Related guides