SQL IFNULL function
Returns the second argument when the first is NULL. Each engine has its own name for it and slightly different type rules; COALESCE is the standard spelling that works everywhere.
- Category
- Conditional
- Returns
type of the first argument- In this category
- 5 of 43
Syntax
IFNULL(a, b) -- MySQL, SQLite
ISNULL(a, b) -- SQL Server
NVL(a, b) -- Oracle
Each block is a separate form. The support table and the examples show which engine takes which.
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Different name or syntax | spelled ISNULL(a, b) |
| PostgreSQL | Not built in | no IFNULL or NVL; use COALESCE(a, b) |
| MySQL | Yes | Supported under this name. |
| SQLite | Yes | Supported under this name. |
| Oracle | Different name or syntax | spelled NVL(a, b) |
Examples
MySQL
SELECT IFNULL(discount, 0) AS discount FROM orders;
SQL Server
SELECT ISNULL(discount, 0) AS discount FROM orders;
Oracle
SELECT NVL(discount, 0) AS discount FROM orders;
Good to know
- SQL Server's ISNULL casts the fallback to the first argument's type: ISNULL(col, 'too long for varchar(3)') silently truncates. COALESCE picks the higher-precedence type instead.
- PostgreSQL has none of the three names: COALESCE(a, b) is the only option there, and the portable one everywhere else.
- Oracle's NVL evaluates both arguments even when the first is not NULL; COALESCE stops at the first non-NULL one. That matters when the fallback is an expensive function call.
- ISNULL on MySQL is a predicate: ISNULL(x) returns 1 or 0, not a fill value. Same spelling, different function from SQL Server's.
Questions about IFNULL / NVL / ISNULL
Is IFNULL available in every database?
No: MySQL and SQLite have IFNULL, SQL Server calls it ISNULL, Oracle calls it NVL, and PostgreSQL has none of them. COALESCE(a, b) works on all five.
Why does ISNULL truncate my fallback value?
SQL Server's ISNULL adopts the first argument's type, so a fallback longer than the column's varchar width is cut. COALESCE returns the wider type and avoids the surprise.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Replacing NULL in output: COALESCE, ISNULL, NVL, IFNULL Dialect comparison
- Sorting with COALESCE in ORDER BY Dialect comparison
- Find unused index candidates Snippet
- Find the sessions consuming tempdb space in SQL Server Snippet
- Find the largest indexes in PostgreSQL Snippet
- Generate CREATE INDEX statements from SQL Server's missing index DMVs Snippet
Cheat sheets for the engines that have it: SQL Server, MySQL, SQLite, 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.