Hello! Welcome to your seventh lesson in the Advanced SQL module.
In our last lesson, we constructed a cohort analysis to measure user retention—a powerful technique for understanding business health. During that process, we noted that the accuracy of such an analysis depends heavily on clean data. Specifically, we saw how NULL customer IDs could corrupt our results and needed to be filtered out.
Today, we'll dive deep into that exact challenge. You will learn how to handle NULL values in analytical queries using functions like COALESCE and NULLIF to ensure accurate aggregations. Mastering this skill is non-negotiable for a data analyst, as NULLs are a common source of errors and can silently lead to incorrect business metrics if not managed properly.
What is a NULL Value?
First, let's be precise about what NULL means. A NULL value in a database column represents a missing or unknown value. It's crucial to understand that NULL is not the same as:
- The number
0. - An empty string
''. - A blank space
' '.
Think of it as a placeholder for "we don't know". This distinction has significant implications for our queries. For a quick introduction, please watch the first minute of this video.
SQL NULL Functions | COALESCE, ISNULL, NULLIF, IS (NOT) NULL | #SQL Course 18
This video from Data with Baraa starts with a clear, concise explanation of what NULL values represent in a database context.
Watch from the beginning until 01:09 to solidify your understanding of what NULL signifies.
The Problem: How NULLs Affect Calculations
When performing analysis, NULL values can cause two major problems:
- Inaccurate Aggregations: Most aggregate functions like
AVG(),SUM(), andCOUNT(column_name)simply ignore rows withNULLvalues. If you're calculating the average order value and some orders have aNULLamount, those orders won't be part of the calculation at all. If the business assumes a missing value should be treated as zero, your reported average will be inflated. - Broken Mathematical Operations: Any arithmetic operation involving a
NULLresults inNULL. For example,100 + NULLisNULL. Similarly, concatenating strings like'John' + ' ' + NULLalso results inNULL. This can lead to unexpected empty fields in your reports.
Let's watch a practical demonstration of these issues.
SQL NULL Functions | COALESCE, ISNULL, NULLIF, IS (NOT) NULL | #SQL Course 18
The same video provides excellent examples of how NULLs can skew aggregations and break mathematical operations, which are common tasks in business reporting.
Watch the following two segments: Aggregations (14:33 - 18:09): Pay close attention to the example of calculating the average score. See how the result changes when NULL is explicitly handled versus when it is ignored. Mathematical Operations (18:09 - 24:11): Observe the full-name concatenation and bonus points examples. This clearly shows how a single NULL can cause the entire result to become NULL.
The Solution Part 1: Replacing NULLs with COALESCE
The most common and versatile function for handling NULLs is COALESCE. It takes a list of arguments and returns the first non-NULL value it encounters, reading from left to right. It is an ANSI SQL standard, meaning it works across most database systems (PostgreSQL, SQL Server, BigQuery, etc.).
Syntax: COALESCE(value1, value2, ..., fallback_value)
Simple Replacement
The simplest use is to provide a single fallback value. In the video example, to treat NULL scores as 0 before averaging, you would use AVG(COALESCE(score, 0)).
Creating Fallback Hierarchies
COALESCE's real power comes from its ability to handle multiple arguments, creating a "fallback hierarchy." This is perfect for business logic. Imagine you need to find the best contact method for a customer, prioritizing their mobile number, then their work phone, then their email.
SELECT
customer_id,
COALESCE(
mobile_phone,
work_phone,
email,
'No contact info'
) AS primary_contact
FROM customers;
This query checks mobile_phone first. If it's NULL, it moves to work_phone. If that's also NULL, it tries email. If all are NULL, it returns the default string 'No contact info'.
This article provides another great example of this business use case.
The 5 best ways to handle NULL values in SQL
This blog post from Metaplane, titled 'The 5 best ways to handle NULL values in SQL', frames NULL handling in a practical, business-oriented way. It's great for understanding the 'why' behind the code.
Read section '1. Using COALESCE for default values'. Note the marketing attribution example and the 'Pro tip' about establishing a fallback hierarchy.
COALESCE vs. ISNULL/IFNULL
You might also encounter ISNULL (specific to SQL Server) and IFNULL (specific to MySQL and others). These functions work similarly but are limited to only two arguments and are not universally supported.
For portability and flexibility, COALESCE is almost always the better choice.
Test your understanding!
You have a table products with columns product_id, sale_price, and msrp (Manufacturer's Suggested Retail Price). For a sales report, you need to display a final price for each product. The logic is: use the sale_price if it exists; otherwise, use the msrp. If both are NULL, display 0.
How would you write the SELECT statement for the final price column?
Show answer
You would use COALESCE with three arguments to implement the fallback logic:
SELECT
product_id,
COALESCE(sale_price, msrp, 0) AS final_price
FROM products;
The Solution Part 2: Replacing Values with NULLIF
Sometimes, you need to do the opposite: turn a specific value into a NULL. This is where NULLIF comes in. It takes two arguments and returns NULL if they are equal; otherwise, it returns the first argument.
Syntax: NULLIF(value_to_check, value_if_equal)
This is extremely useful for two main scenarios:
-
Data Cleaning: Datasets often use placeholder values like
-1,'N/A', or even empty strings''to represent missing data.NULLIFallows you to convert these into properNULLs for consistent handling.For example, if a
departmentcolumn uses an empty string for unknown departments, you could clean it like this before joining:NULLIF(department, ''). The ByteScout article (resource LINK) shows a great example of this whenCOALESCEalone isn't enough. -
Preventing Division by Zero Errors: This is a classic use case. A query like
SELECT revenue / number_of_orderswill fail ifnumber_of_ordersis0. You can prevent this gracefully withNULLIF.SELECT revenue / NULLIF(number_of_orders, 0)If
number_of_ordersis0,NULLIFturns it intoNULL. Since any math operation withNULLresults inNULL(not an error), the query runs successfully, producing aNULLfor that row.
Let's watch a clear demonstration of NULLIF, focusing on the division-by-zero scenario.
SQL NULL Functions | COALESCE, ISNULL, NULLIF, IS (NOT) NULL | #SQL Course 18
This segment from the 'Data with Baraa' video explains the NULLIF function and demonstrates its most critical use case in analytics.
Watch from 36:43 to 42:42. Focus on how NULLIF is used to replace the 0 in the quantity column to avoid an error.
Filtering with IS NULL and IS NOT NULL
Finally, to filter rows based on NULL values, you must use the IS NULL or IS NOT NULL operators in your WHERE clause.
You cannot use = NULL or != NULL. Because NULL represents an unknown state, it is not considered equal (or unequal) to anything, including itself.
-- Correct: Find all customers without a recorded first name
SELECT *
FROM customers
WHERE first_name IS NULL;
-- Incorrect: This will not return any rows
SELECT *
FROM customers
WHERE first_name = NULL;
This short video provides a good review of how to use IS NULL and IS NOT NULL for filtering.
Null Values in SQL - 5 tips in 14 min (IFNULL & COALESCE)
This video from Jess Ramos gives a quick and clear guide on how to filter for NULL values in a WHERE clause.
Watch from 02:27 to 05:05 to see how IS NULL and IS NOT NULL are used with WHERE, AND, and OR to filter data.
Quick Reference
Here is a handy image summarizing the functions we've discussed today. It's a great cheat sheet to keep available as you write your queries.
Conclusion
You've now learned the essential techniques for managing NULL values in SQL. This is a fundamental skill that moves you from simply writing queries to writing robust, reliable analytical code. Incorrectly handled NULLs can lead to flawed reports and bad business decisions, and as a data analyst, it's your job to prevent that.
Key Takeaways:
NULLmeans "unknown" and is different from0or''.- Aggregate functions typically ignore
NULLs, which can skew results likeAVG(). - Use
COALESCE(value, fallback)to replaceNULLs and ensure accurate calculations. It is the flexible, industry-standard choice. - Use
NULLIF(value, value_if_equal)to turn specific values (like0or placeholder strings) intoNULLfor cleaning or to prevent errors like division-by-zero. - Always use
IS NULLorIS NOT NULLin yourWHEREclause to filter forNULLvalues.
Next Lesson Preview:
In this module, you've used Common Table Expressions (CTEs) extensively to structure complex logic like cohort analysis. In our next and final lesson of this module, we will formalize this practice. You will learn how to rewrite subqueries as CTEs or JOINs to improve query readability and maintainability, a key skill for collaborating with other analysts and building professional-grade analytical scripts.