Skip to content

SQL NULL Functions

A NULL in a calculation makes the whole result NULL: anything plus or minus an unknown is unknown. The null functions replace a NULL with a value you choose, so the calculation can go ahead.

The examples use the Productions and Invoices tables from the example database. SQL Null explains what NULL is.

To work out how much of each production’s budget is left after its invoices:

SELECT Productions.Title,
Productions.Budget - SUM(Invoices.Amount) AS Remaining
FROM Productions
LEFT JOIN Invoices ON Invoices.ProductionID = Productions.ProductionID
GROUP BY Productions.ProductionID, Productions.Title
ORDER BY Productions.ProductionID;
Title Remaining
The Lantern Keepers 18,434,150.00
Quarry Lane 7,196,820.00
Saltmarsh
Six Bells 10,997,060.00
Fennick’s Return

Saltmarsh and Fennick’s Return have no invoices, so their SUM is NULL, and the subtraction gives NULL too. Nothing has been spent, so the answer should be the full budget.

COALESCE returns the first of its arguments that is not NULL. Writing COALESCE(SUM(Invoices.Amount), 0) turns a missing total into zero:

SELECT Productions.Title,
Productions.Budget - COALESCE(SUM(Invoices.Amount), 0) AS Remaining
FROM Productions
LEFT JOIN Invoices ON Invoices.ProductionID = Productions.ProductionID
GROUP BY Productions.ProductionID, Productions.Title
ORDER BY Productions.ProductionID;
Title Remaining
The Lantern Keepers 18,434,150.00
Quarry Lane 7,196,820.00
Saltmarsh 3,900,000.00
Six Bells 10,997,060.00
Fennick’s Return 850,000.00

COALESCE also gives a readable stand-in for display:

SELECT InvoiceID, COALESCE(PaidDate, 'Not paid') AS PaidDate
FROM Invoices;
InvoiceID PaidDate
1001 2025-04-01
1002 2025-03-28
1003 Not paid
1004 Not paid

The arguments must be of compatible types. Where PaidDate is a true date column, as in PostgreSQL, convert it to text first, as in COALESCE(CAST(PaidDate AS VARCHAR(10)), 'Not paid').

COALESCE can take more than two arguments, and returns the first one that has a value: COALESCE(MobilePhone, OfficePhone, 'No number').

COALESCE is part of the SQL standard and works in every major database, which makes it the one to reach for. Each database also has a two-argument function of its own:

Database Function
MySQL, SQLite IFNULL(PaidDate, 'Not paid')
SQL Server ISNULL(PaidDate, 'Not paid')
Oracle NVL(PaidDate, 'Not paid')
Microsoft Access IIF(IsNull(PaidDate), 'Not paid', PaidDate)

Note that ISNULL means different things in different places. In SQL Server it replaces a NULL, as above; in Access and MySQL, IsNull(x) or ISNULL(x) only tests whether x is NULL.