π‘ SQL NULL Handling
In SQL, NULL represents a missing or unknown value. It is not the same as 0
or an empty string ''
. Handling NULL
correctly is essential for accurate results.
1οΈβ£ Identifying NULL Values
To check if a column has NULL
values, use IS NULL
:
SELECT FirstName, ManagerID
FROM Employees
WHERE ManagerID IS NULL;
π Finds employees who donβt have a manager assigned.
2οΈβ£ Filtering Non-NULL Values
To check if a column is not null, use IS NOT NULL
:
SELECT FirstName, ManagerID
FROM Employees
WHERE ManagerID IS NOT NULL;
π Finds employees who have a manager assigned.
3οΈβ£ NULL in Comparisons
Important: NULL
does not equal anything, not even another NULL
. This means:
SELECT *
FROM Employees
WHERE ManagerID = NULL; -- β This will never work
β
Always use IS NULL
or IS NOT NULL
instead.
4οΈβ£ Using NULL with Functions
Functions can handle NULL differently:
SELECT AVG(Salary), SUM(Salary)
FROM Employees;
π NULL salaries are ignored in aggregate functions like SUM
, AVG
, COUNT
.
Pro Tip: Use
COALESCE(column, value)
to replace NULL with a default value.SELECT FirstName, COALESCE(ManagerID, 'No Manager') AS ManagerStatus
FROM Employees;
β Key Takeaways
NULL
= unknown / missing value.- Use
IS NULL
/IS NOT NULL
to check NULL values. NULL
βNULL
(they are never equal).- Use
COALESCE
to replace NULL with default values.
π Continue Learning
π¬ Got a question about SQL NULL handling? Drop it in the comments below!