SQL IIF function
Returns one of two values depending on a condition: a CASE with exactly two branches. It is not standard SQL, so it exists on only some engines.
- Категория
- Условные конструкции
- Returns
type of the chosen branch- In this category
- 4 of 43
Синтаксис
IIF(condition, true_value, false_value)
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Да | Supported under this name. |
| PostgreSQL | Not built in | no IIF; use CASE WHEN ... THEN ... ELSE ... END |
| MySQL | Different name or syntax | IF(condition, t, f) is the equivalent; there is no IIF |
| SQLite | Да | Supported under this name. |
| Oracle | Not built in | no IIF; CASE or DECODE |
Примеры
SQL Server
SELECT IIF(amount > 1000, 'big', 'small') AS size FROM orders;
SQLite
SELECT IIF(amount > 1000, 'big', 'small') AS size FROM orders;
MySQL
SELECT IF(amount > 1000, 'big', 'small') AS size FROM orders;
Полезно знать
- SQL Server rewrites IIF into a CASE expression, so the same type rules apply: IIF(cond, 1, 'x') is an int expression and fails at run time on rows where 'x' is chosen.
- SQLite added IIF in 3.32. From 3.48 it also accepts the name IF and a two-argument form, and from 3.49 any number of condition/value pairs with an optional default.
- MySQL's IF() function is different from the IF statement in stored procedures; the function form works anywhere an expression does.
- A NULL condition counts as false: IIF(NULL, 'yes', 'no') returns 'no'.
Questions about IIF / IF
Does PostgreSQL have IIF?
No. Write CASE WHEN cond THEN a ELSE b END. For the common NULL case, COALESCE and NULLIF cover it in fewer characters.
Is IIF the same as IF?
Same job, different names: SQL Server and SQLite say IIF, MySQL says IF. All three take (condition, true value, false value).
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Conditional expressions: CASE, IIF, IF and DECODE Dialect comparison
- Add a foreign key if it does not exist Snippet
- Rename a column if it exists Snippet
- Add a column if it does not exist Snippet
- Mask payment card numbers in SQL (show last 4) Snippet
Cheat sheets for the engines that have it: SQL Server, MySQL, SQLite.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.