NULL Values in SQL

🚫 NULL in SQL represents the absence of a value or unknown data. It does not mean zero, an empty string, or the word "NULL". Understanding how SQL handles NULL values is essential because they behave differently from regular values in comparisons, calculations, and queries.

📖 What is a NULL Value?

A NULL value indicates that a column has no value assigned or that the value is currently unknown. For example, a student may not have an email address yet, or an employee's resignation date may not be available.

Important

NULL is not the same as:
  • 0 (Zero)
  • '' (An empty string)
  • The text 'NULL'

📊 Sample Table

Consider the following Students table:

StudentIDNameEmailPhone
101Alicealice@example.com9876543210
102BobNULL9876501234
103Charliecharlie@example.comNULL
104DavidNULLNULL

🔍 Checking for NULL Values

Since NULL represents an unknown value, it cannot be compared using the standard comparison operators such as = or <>. Instead, SQL provides the IS NULL and IS NOT NULL operators.

1️⃣ Using IS NULL

The IS NULL operator retrieves rows where a column contains a NULL value.

Find Students Without an Email Address

SELECT *
FROM Students
WHERE Email IS NULL;

2️⃣ Using IS NOT NULL

The IS NOT NULL operator retrieves rows where a column contains a valid (non-NULL) value.

Find Students With an Email Address

SELECT *
FROM Students
WHERE Email IS NOT NULL;

❌ Incorrect Way to Check for NULL

Never use the equality operator to compare with NULL.

Incorrect Example

-- Incorrect
SELECT *
FROM Students
WHERE Email = NULL;

Warning

The above query returns no rows because NULL cannot be compared using = or <>. Always use IS NULL or IS NOT NULL.

🧮 NULL Values in Calculations

Arithmetic operations involving NULL usually return NULL because the result of an operation with an unknown value is also unknown.

Calculation with NULL

SELECT
    Salary,
    Bonus,
    Salary + Bonus AS TotalIncome
FROM Employees;

If Bonus is NULL, the value of TotalIncome is typically NULL.

🔄 Replacing NULL Values

Many database systems provide functions to replace NULL with a default value. The function name varies depending on the database.

DatabaseCommon Function
MySQL IFNULL()
PostgreSQL COALESCE()
SQL Server ISNULL()
Oracle NVL()

Using COALESCE (Standard SQL)

SELECT
    Name,
    COALESCE(Email, 'Not Available') AS Email
FROM Students;

The COALESCE() function returns the first non-NULL value from its list of arguments and is part of the SQL standard.

📊 NULL Values with Aggregate Functions

Most aggregate functions ignore NULL values.

FunctionBehavior with NULL
COUNT(column)Counts only non-NULL values.
COUNT(*)Counts all rows, including rows containing NULL values.
SUM()Ignores NULL values.
AVG()Ignores NULL values.
MIN()Ignores NULL values.
MAX()Ignores NULL values.

COUNT Example

SELECT
    COUNT(*) AS TotalStudents,
    COUNT(Email) AS StudentsWithEmail
FROM Students;

🔗 NULL Values with ORDER BY

When sorting data, databases may place NULL values either at the beginning or the end of the result set by default. This behavior differs among database systems. Some databases allow explicit control using NULLS FIRST or NULLS LAST.

Sort with NULLS LAST (Supported by Some Databases)

SELECT Name, Email
FROM Students
ORDER BY Email NULLS LAST;

💼 Real-World Example

Suppose a university wants to contact only students who have provided an email address.

Students with Valid Email Addresses

SELECT StudentID,
       Name,
       Email
FROM Students
WHERE Email IS NOT NULL
ORDER BY Name;

This query excludes students whose email address has not yet been recorded.

⚠️ Best Practices

Best Practice

Always use IS NULL or IS NOT NULL when checking for missing values. Use standard functions such as COALESCE() when replacing NULL values for better portability across database systems. Be aware that aggregate functions generally ignore NULL values, and understand how your database handles NULL values during sorting.

🚀 Key Points to Remember

  • 📌 NULL represents missing or unknown data.
  • 📌 NULL is different from 0 and an empty string.
  • 📌 Use IS NULL to find NULL values.
  • 📌 Use IS NOT NULL to find non-NULL values.
  • 📌 Never compare NULL using = or <>.
  • 📌 Aggregate functions usually ignore NULL values.
  • 📌 Use functions such as COALESCE() to replace NULL values when needed.
>>"Understanding NULL values is essential for writing accurate and reliable SQL queries."

Summary

NULL represents the absence or unknown state of data in SQL. By using IS NULL, IS NOT NULL, and functions like COALESCE(), you can correctly handle missing values and write more robust, portable, and efficient SQL queries.