SQL IF function
MySQL's inline conditional expression: two values, one condition.
- 類別
- 條件
- Returns
type of then_val or else_val- In this category
- 10 of 43
語法
IF(cond, then_val, else_val) | IIF(cond, then_val, else_val)
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Different name or syntax | no IF(); IIF since SQL Server 2012 |
| PostgreSQL | Not built in | no IF; use CASE WHEN |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | IIF since 3.32; IF() as an alias since 3.48 |
| Oracle | Not built in | no IF; use CASE (or DECODE) |
範例
MySQL
SELECT IF(paid = 1, 'paid', 'due') FROM invoices;
SQL Server
SELECT IIF(paid = 1, 'paid', 'due') FROM invoices;
SQLite
SELECT IIF(total > 100, 'big', 'small') FROM orders;
小知識
- A NULL condition behaves like false: the else branch runs, silently, so a missing flag looks the same as a negative one.
- Only the chosen branch is evaluated, unlike Oracle's NVL.
- SQL Server rewrites IIF(cond, a, b) into CASE WHEN cond THEN a ELSE b END, so the two behave identically, including the result type.
Questions about IF
IF vs CASE WHEN?
Same semantics for the two-branch case; CASE is standard, nests readably and works on all five engines.
What happens when the condition is NULL?
The else branch runs; NULL is neither true nor true-ish.
Does PostgreSQL have IF()?
No, use CASE; IF is PL/pgSQL procedure syntax, not an expression.
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
- Conditional counts (COUNT IF) Snippet
- CREATE TABLE IF NOT EXISTS variants Snippet
- Conditional sums (SUM IF) Snippet
- Add a foreign key if it does not exist Snippet
- Rename a column if it exists 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.