SQL NVL2 function
Returns the second argument when the first is not NULL, the third when it is.
- Categoria
- Condicional
- Returns
type of r1 or r2- In this category
- 8 of 43
Sintaxe
NVL2(expr, r1, r2)
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Not built in | No built-in equivalent. |
| PostgreSQL | Not built in | No built-in equivalent. |
| MySQL | Not built in | No built-in equivalent. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Sim | the only one of the five engines with NVL2 |
Exemplos
Oracle
SELECT NVL2(phone, 'listed', 'missing') FROM contacts;
Oracle
SELECT NVL2(discount, price * discount, price) FROM orders;
Bom saber
- Argument order trips people up: the not-NULL branch is the second argument, the NULL branch the third.
- Only the NULL-ness of expr matters: its value is discarded, so NVL2 is a boolean branch, not a fallback chain.
- The portable spelling is CASE WHEN expr IS NOT NULL THEN r1 ELSE r2 END.
Questions about NVL2
Which branch fires when expr is NULL?
The third argument; the second fires only when expr is not NULL.
What is NVL2 in MySQL?
Nothing native: IF(cond, r1, r2) or CASE WHEN expr IS NOT NULL THEN r1 ELSE r2 END.
NVL vs NVL2?
NVL substitutes a default for NULL; NVL2 chooses between two results based on NULL-ness.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: Oracle.
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.