SQL NULL Functions

SQL NULL Functions

SQL provides several functions to handle NULL values in a more controlled way. A NULL value can be problematic in calculations or when displaying data. These functions allow you to substitute a NULL with another value.

The exact function names vary between different database systems.


Common NULL Functions

MySQL: IFNULL() and COALESCE()

SQL Server: ISNULL() and COALESCE()

Oracle: NVL() and COALESCE()

Note: The COALESCE() function is part of the SQL standard and is generally preferred for portability across different database systems.


Demo Database

Customers Table: (Assume some contacts are NULL)

CustomerID CustomerName ContactName
1 Alfreds Futterkiste Maria Anders
2 Ana Trujillo Emparedados NULL
3 Antonio Moreno Taquería Antonio Moreno
4 Around the Horn NULL

IFNULL() Example (MySQL)

The following SQL statement will return the text "No Contact" if the ContactName value is NULL.

IFNULL() Example

SELECT CustomerName, IFNULL(ContactName, 'No Contact') AS Contact
FROM Customers;

Without IFNULL(), the result would show NULL for customers without a contact name.


COALESCE() Example (Standard SQL)

The COALESCE() function provides the same functionality and is more portable.

COALESCE() Example

SELECT CustomerName, COALESCE(ContactName, 'No Contact') AS Contact
FROM Customers;