SQL NULL Handling




🟑 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!




Leave a Comment