IF in SQL
The IF function returns one value when a condition is true and another when it is false; SQL uses a CASE expression.
The Excel version
=IF(C2>=1000, "Large", IF(C2>=100, "Medium", "Small"))The SQL equivalent
This example assumes: sales(id bigint, region text, amount numeric, sale_date date). It is written in PostgreSQL syntax, and your table and column names will differ from these.
SELECT id,
amount,
CASE
WHEN amount >= 1000 THEN 'Large'
WHEN amount >= 100 THEN 'Medium'
ELSE 'Small'
END AS size_band
FROM sales
ORDER BY id;How it works
- Each WHEN is a condition checked in order; the first one that is true decides the result.
- ELSE is the final value, like the last argument of the innermost IF.
- Nested IFs become a flat list of WHEN lines, which is easier to read and extend.
Where the results differ from Excel
- CASE stops at the first true condition, like nested IFs, so the order of the WHENs matters.
- A missing ELSE returns null rather than FALSE or an empty cell.
- A null amount never satisfies amount >= 1000, so it falls to ELSE; test for IS NULL first if blanks need their own label.
Skip the query: ask in plain English
If you would rather not write SQL, type the question. SchemaChat turns it into SQL against your connected database or uploaded file, runs it, and shows the SQL and the figures it used so you can check the answer before you share it. Check that the result matches how your spreadsheet defines the number.
- Label each sale as Large, Medium or Small.
- How many sales fall into each size band?