SQL NULL Functions
SQL provides several functions to handle NULL values. These functions help manage and manipulate NULL values in your database queries.
Common SQL NULL Functions
IS NULLIS NOT NULLCOALESCE()NULLIF()IFNULL()(MySQL)NVL()(Oracle)
Example: IS NULL and IS NOT NULL
SELECT employee_id, first_name, last_name
FROM Employees
WHERE middle_name IS NULL;This query selects employees who do not have a middle name.
Example: COALESCE()
SELECT employee_id, first_name, last_name, COALESCE(middle_name, 'N/A') AS middle_name
FROM Employees;This query returns ‘N/A’ if the middle_name is NULL.
Example: NULLIF()
SELECT product_id, product_name,
NULLIF(discount_price, 0) AS discount_price
FROM Products;This query returns NULL if the discount_price is 0.
Example: IFNULL() (MySQL)
SELECT product_id, product_name,
IFNULL(discount_price, 0) AS discount_price
FROM Products;This query returns 0 if the discount_price is NULL in MySQL.
Example: NVL() (Oracle)
SELECT product_id, product_name,
NVL(discount_price, 0) AS discount_price
FROM Products;This query returns 0 if the discount_price is NULL in Oracle.
Sample Tables
Consider the following Employees table:
Employees:
| employee_id | first_name | middle_name | last_name |
|-------------|------------|-------------|-----------|
| 1 | John | NULL | Doe |
| 2 | Jane | A. | Smith |
| 3 | Michael | NULL | Johnson |Result of IS NULL Query
After running the IS NULL example query, the result would look like this:
| employee_id | first_name | last_name |
|-------------|------------|-----------|
| 1 | John | Doe |
| 3 | Michael | Johnson |Important Notes
- Use
IS NULLandIS NOT NULLto check for NULL values. - The
COALESCE()function returns the first non-NULL value in the list. - The
NULLIF()function returns NULL if the two arguments are equal. - Use
IFNULL()in MySQL andNVL()in Oracle to replace NULL with a specified value.