Lab 17: NULL Handling

Time: 30 minutes | Level: Foundations | DB: MySQL 8 / PostgreSQL 15

Overview

Master NULL semantics, IS NULL/IS NOT NULL, COALESCE, NULLIF, IFNULL, NULL in aggregates, NULL in ORDER BY, and three-valued logic.


Step 1: NULL Semantics — NULL is Not a Value

NULL represents the absence of a value — it is unknown, not zero or empty string.

docker run -d --name mysql-lab -e MYSQL_ROOT_PASSWORD=rootpass mysql:8.0
for i in $(seq 1 30); do docker exec mysql-lab mysql -uroot -prootpass -e "SELECT 1" 2>/dev/null && break || sleep 2; done

docker exec mysql-lab mysql -uroot -prootpass << 'EOF'
CREATE DATABASE nulllab;
USE nulllab;

-- Demonstrate NULL != NULL (the critical mistake)
SELECT NULL = NULL;           -- Returns NULL, not TRUE!
SELECT NULL != NULL;          -- Returns NULL, not FALSE!
SELECT NULL = 0;              -- NULL
SELECT NULL = '';             -- NULL
SELECT NULL IS NULL;          -- TRUE (correct way to check)
SELECT NULL IS NOT NULL;      -- FALSE
SELECT 1 + NULL;              -- NULL (any arithmetic with NULL = NULL)
SELECT CONCAT('hello', NULL); -- NULL (MySQL: string + NULL = NULL)
EOF

📸 Verified Output:

💡 Never use = NULL to check for NULL values. Always use IS NULL or IS NOT NULL. This is the most common NULL-related bug in SQL.


Step 2: Setup — Table with NULLs


Step 3: IS NULL and IS NOT NULL

📸 Verified Output (count NULLs):


Step 4: COALESCE — Return First Non-NULL

📸 Verified Output:

💡 COALESCE(a, b, c) returns the first non-NULL among a, b, c. It's equivalent to CASE WHEN a IS NOT NULL THEN a WHEN b IS NOT NULL THEN b ELSE c END — but much more readable.


Step 5: NULLIF — Return NULL When Values Match

📸 Verified Output (NULLIF sentinel):


Step 6: IFNULL (MySQL) — Two-Argument Shorthand

📸 Verified Output:


Step 7: NULL in Aggregates and ORDER BY

📸 Verified Output (ORDER BY with NULLs):

NULL ordering in PostgreSQL:

💡 MySQL: NULLs sort first in ASC, last in DESC. PostgreSQL lets you control with NULLS FIRST / NULLS LAST. To force NULLs last in MySQL ASC: ORDER BY score IS NULL ASC, score ASC


Step 8: Capstone — Three-Valued Logic

SQL uses three-valued logic: TRUE, FALSE, and UNKNOWN (NULL).

📸 Verified Output:

Cleanup:


Summary

Function/Syntax
Description
Example

IS NULL

Check for NULL

WHERE col IS NULL

IS NOT NULL

Check for non-NULL

WHERE col IS NOT NULL

COALESCE(a,b,c)

First non-NULL value

COALESCE(bonus, 0)

NULLIF(a, b)

NULL if a=b, else a

NULLIF(score, 0)

IFNULL(a, b)

MySQL: b if a is NULL

IFNULL(email, 'N/A')

NVL(a, b)

Oracle equivalent of IFNULL

Not in MySQL/PG

= NULL

NEVER use this

Always use IS NULL

Behavior
Effect

NULL in arithmetic

Result is NULL

NULL in aggregates

Ignored (not counted)

NULL in ORDER BY (MySQL)

First in ASC, last in DESC

NULL in WHERE

Row excluded (UNKNOWN ≠ TRUE)

Three-valued logic

TRUE / FALSE / UNKNOWN

Next: Lab 18 — PostgreSQL JSONB and Arrays

Last updated