Understanding and Handling NULL Values in SQL

In SQL, a NULL value represents the absence of a value, not the value of zero or an empty string. It signifies that a field has not been assigned any data.



What is a NULL Value?

A NULL value indicates that a field in a database table is empty or doesn't have a value. This is different from a field containing zero, an empty string (" "), or spaces. A NULL represents the complete absence of data in that field. If a field is optional, it can be left blank during insertion; the database will automatically assign NULL to that field.

Testing for NULL Values

You can't use standard comparison operators (like =, <, >) to check for NULL values directly because NULL isn't considered a value in the traditional sense. Instead, you must use the IS NULL and IS NOT NULL operators.

IS NULL Syntax

Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NULL;
      

IS NOT NULL Syntax

Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
      

Example Database

Let's consider a sample 'Customers' table for the following examples:

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

Examples using IS NULL and IS NOT NULL

Finding Customers with NULL Addresses

This query identifies customers who have not yet provided their address.

Syntax

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
      
Output

(This will return zero rows based on the sample data provided, as all customers have addresses)
      

Finding Customers with Addresses

This query selects customers who have provided an address.

Syntax

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
      
Output

(This will return all rows from the sample data, as all customers have addresses)