SQL NULL Functions
SQL NULL functions are used to handle NULL values in database queries. Here are some common SQL NULL functions, along with examples and their output:
-
IS NULL and IS NOT NULL
- IS NULL: Used to check if a value is NULL.
- IS NOT NULL: Used to check if a value is not NULL.
SELECT * FROM Employees WHERE ManagerID IS NULL;This query retrieves all employees who do not have a manager (where
ManagerIDis NULL).SELECT * FROM Employees WHERE ManagerID IS NOT NULL;This query retrieves all employees who have a manager (where
ManagerIDis not NULL). -
COALESCE
- Returns the first non-NULL value in a list.
SELECT EmployeeID, COALESCE(PhoneNumber, 'No Phone Number') AS PhoneNumber FROM Employees;Example output:
EmployeeID PhoneNumber ----------- ------------ 1 123-456-7890 2 No Phone Number 3 987-654-3210 -
NULLIF
- Returns NULL if the two arguments are equal, otherwise returns the first argument.
SELECT NULLIF(Salary, 0) AS AdjustedSalary FROM Employees;Example output:
AdjustedSalary --------------- 50000 NULL 75000 -
IFNULL (MySQL specific) / ISNULL (SQL Server specific)
- Returns the first argument if it is not NULL; otherwise, returns the second argument.
-- MySQL SELECT EmployeeID, IFNULL(PhoneNumber, 'No Phone Number') AS PhoneNumber FROM Employees; -- SQL Server SELECT EmployeeID, ISNULL(PhoneNumber, 'No Phone Number') AS PhoneNumber FROM Employees;Example output:
EmployeeID PhoneNumber ----------- ------------ 1 123-456-7890 2 No Phone Number 3 987-654-3210 -
NVL (Oracle specific)
- Similar to IFNULL/ISNULL, replaces NULL with the specified value.
SELECT EmployeeID, NVL(PhoneNumber, 'No Phone Number') AS PhoneNumber FROM Employees;Example output:
EmployeeID PhoneNumber ----------- ------------ 1 123-456-7890 2 No Phone Number 3 987-654-3210
Example Data
Let's use the following example table Employees:
| EmployeeID | Name | ManagerID | Salary | PhoneNumber |
|---|---|---|---|---|
| 1 | John Doe | NULL | 50000 | 123-456-7890 |
| 2 | Jane Smith | 1 | 0 | NULL |
| 3 | Bob Brown | 1 | 75000 | 987-654-3210 |
These SQL NULL functions are essential for handling missing data gracefully and ensuring queries return meaningful results.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
