SQL reference

IF in SQL: IIF, IF() and CASE

In Excel, you'd reach for
fx=IF(test, value_if_true, value_if_false)

Standard SQL has no IF function inside a query. It has CASE WHEN, which does the same job and works in every database. Several databases add a shortcut that reads exactly like Excel's IF:

  • IIF(test, yes, no) in SQL Server and SQLite
  • IF(test, yes, no) in MySQL and BigQuery
  • Postgres and most others: use CASE WHEN

Syntax

IIF(condition, value_if_true, value_if_false)
-- works everywhere:
CASE WHEN condition THEN value_if_true ELSE value_if_false END
Try itEdit the query, then Run
namecountrymarket
Kavya HaddadUnited Statesdomestic
Ben KimIndiainternational
Kavya KimIndiainternational
Nikhil TanakaNigeriainternational
Elena NguyenUnited Kingdominternational
Leo GarciaNigeriainternational
Tara AliGermanyinternational
Quinn LopezUnited Statesdomestic
Sam OkaforBrazilinternational
Ben SmithUnited Statesdomestic

10 rows

The same thing with CASE, which you can paste into any database:

CASE WHEN country = 'United States' THEN 'domestic' ELSE 'international' END

You'll also see IF ... ELSE blocks in SQL Server scripts and stored procedures. Those control which statements run; they don't build a column, so for reports you want IIF or CASE.

Your turn

For each subscription show id and a column status that says 'cancelled' when cancelled_at has a value, otherwise 'active'.

This page on one card

IF in SQL: IIF, IF() and CASE: the Excel way (=IF(test) and the SQL query, side by side
IF in SQL: IIF, IF() and CASE, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows