1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL NULL Values Explained: IS NULL, COALESCE, NULLIF and the Traps to Avoid

NULL causes some of the quietest bugs in SQL, with queries that run without errors yet lose rows or skew averages. Learn how NULL really behaves, with tested examples, and how to handle it safely.

9 min read
SQL NULL values explained: IS NULL, COALESCE, NULLIF and the traps to avoid

Key takeaways

  • NULL means a missing or unknown value. It is not zero, and it is not an empty string.
  • Test for it with IS NULL, because = NULL never matches anything.
  • Most calculations with NULL give NULL, and WHERE keeps only rows that are definitely true.
  • Aggregates skip NULLs, which can quietly change an average.

A query runs without errors and returns a sensible-looking number, but rows are missing and the average is wrong. SQL NULL values are very often the cause. NULL does not behave like any normal value, and that catches out beginners and experienced developers alike.

This guide shows exactly how NULL behaves. We ran every query in SQLite 3.50, and the results shown come from that run. Most of this behaviour is standard SQL, and we note where databases differ, such as NULL sort order, and Oracle’s treatment of empty strings.

What is NULL?

NULL is a marker meaning that a value is missing or unknown. It is not a value in the usual sense, so these are all different things:

Value Meaning Example for a phone column
NULL Unknown or not provided We do not know the number
'' A known, empty text value Submitted as blank
0 The number zero Not relevant to text, but real for amounts

The difference matters for amounts especially. A bonus of 0 means the person received nothing. A NULL bonus means nobody knows yet.

The sample table

CREATE TABLE employees (
  id INT, name TEXT, phone TEXT, bonus INT, manager_id INT
);

INSERT INTO employees VALUES
 (1,'Meera','555-0101',500,NULL),
 (2,'Arjun',NULL,300,1),
 (3,'Sara','',NULL,1),
 (4,'Ravi',NULL,NULL,2);

Notice that Sara has an empty string for the phone, whereas Arjun and Ravi have NULL. The two are treated very differently.

Testing for NULL

Here is the mistake almost everyone makes at first:

SELECT name FROM employees WHERE phone = NULL;
-- (no rows)

SELECT name FROM employees WHERE phone IS NULL;
-- Arjun
-- Ravi

SELECT name FROM employees WHERE phone IS NOT NULL;
-- Meera
-- Sara

The first query is valid SQL and gives no error. It simply returns nothing, because comparing anything with NULL is never true. Sara shows up under IS NOT NULL, since an empty string is a real value. In Oracle, though, an empty string is treated as NULL, which is a notable exception.

Three-valued logic

In most programming languages, a condition is true or false. SQL adds a third result: unknown. If you do not know a value, you cannot say whether it equals 5. And two unknown values are not known to be equal, which is why NULL = NULL is not true. In our test, all of these returned NULL:

SELECT NULL = NULL, NULL <> 1, 1 + NULL, 'a' || NULL;

-- NULL | NULL | NULL | NULL

Combining conditions follows careful rules. Here are the results from our run, where 1 is true and 0 is false:

Expression Result Why
TRUE AND NULL NULL Depends on the unknown part
FALSE AND NULL False False whatever the unknown is
TRUE OR NULL True True whatever the unknown is
FALSE OR NULL NULL Depends on the unknown part
NOT NULL NULL The opposite of unknown is unknown

Rows that vanish from WHERE

WHERE keeps a row only if its condition is true. Rows where the result is unknown get dropped, along with those that are false. This leads to surprising results:

SELECT name FROM employees WHERE phone <> '555-0101';

-- Sara

You might expect Arjun and Ravi to appear, since their phone certainly is not that number. But their phone is unknown, so the result is unknown, and they vanish. To include them, say so explicitly: WHERE phone <> '555-0101' OR phone IS NULL. Negation does not help either:

SELECT name FROM employees WHERE NOT (bonus > 400);

-- Arjun

Sara and Ravi have no bonus, so they appear in neither bonus > 400 nor its opposite. This is a key thing to remember: a condition and its negation do not always cover every row.

COALESCE: provide a fallback

COALESCE returns the first non-NULL value in its list, and it works across all major databases:

SELECT COALESCE(NULL, NULL, 'third', 'fourth');
-- third

SELECT name, COALESCE(phone, 'no phone') FROM employees;
-- Meera | 555-0101
-- Arjun | no phone
-- Sara  |
-- Ravi  | no phone

Sara still appears blank, because an empty string is not NULL. Similar functions exist, such as IFNULL in MySQL and SQLite, ISNULL in SQL Server and NVL in Oracle. COALESCE is the portable choice. Our earlier point about calculations applies here too. bonus + 100 gives NULL for anyone without a bonus, so write COALESCE(bonus, 0) + 100 if treating a missing bonus as zero is correct for your business.

NULLIF: turn a value into NULL

NULLIF(a, b) returns NULL if the two values are equal, and otherwise returns a. Two uses are especially helpful. It can clean up placeholder values:

SELECT name, NULLIF(phone, '') FROM employees WHERE id = 3;
-- Sara | NULL

SELECT name FROM employees
WHERE COALESCE(NULLIF(phone, ''), '') = '';
-- Arjun
-- Sara
-- Ravi

That second query is a handy way to find values that are “missing or blank”. It can also guard against dividing by zero, which raises an error in many databases:

SELECT total / NULLIF(quantity, 0) FROM sales;

When quantity is 0, this gives NULL rather than failing. In our test, SELECT 100 / NULLIF(0, 0) returned NULL.

Aggregates skip NULL

This is where NULL does the most damage to reports:

SELECT COUNT(*), COUNT(bonus), SUM(bonus), AVG(bonus),
       AVG(COALESCE(bonus, 0))
FROM employees;

-- 4 | 2 | 800 | 400.0 | 200.0
Expression Result What it means
COUNT(*) 4 All rows
COUNT(bonus) 2 Only rows with a bonus
SUM(bonus) 800 NULLs are ignored
AVG(bonus) 400 800 divided by 2, not by 4
AVG(COALESCE(bonus, 0)) 200 800 divided by 4

So what is the average bonus, 400 or 200? It depends on what NULL means in your data. If NULL means “no bonus was paid”, then 200 is right. If it means “not yet decided”, then 400 may be right. The database cannot make this decision for you, so the question must go to someone who knows the business.

A related trap: SUM of no values is NULL rather than 0. When we summed only rows with no bonus, we got NULL, while COUNT returned 0. Application code expecting a number can crash on this, so wrap it: COALESCE(SUM(bonus), 0).

Tip: When a report total looks off, compare COUNT(*) with COUNT(column). Any gap between them tells you straight away how many NULLs that column has.

GROUP BY, sorting and DISTINCT

Although NULLs are “not equal” in comparisons, these operations treat them as one group:

SELECT bonus, COUNT(*) FROM employees GROUP BY bonus ORDER BY bonus;
-- NULL | 2
--  300 | 1
--  500 | 1

SELECT DISTINCT bonus FROM employees;
-- 500, 300, NULL

See SQL GROUP BY and HAVING for more on grouping. Sort order is where databases really differ. SQLite and MySQL treat NULL as the smallest value, while PostgreSQL and Oracle treat it as the largest. So the same ORDER BY bonus DESC can put NULLs last in one and first in another. PostgreSQL, Oracle and modern SQLite let you state this directly, using NULLS FIRST or NULLS LAST.

Joins

A join condition using = never matches NULL, so rows with a NULL key drop out of an inner join:

SELECT e.name FROM employees e
JOIN employees m ON m.id = e.manager_id;
-- Arjun, Sara, Ravi    (Meera is gone)

SELECT e.name, m.name FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
-- Meera | NULL
-- Arjun | Meera
-- Sara  | Meera
-- Ravi  | Arjun

Meera has no manager, so an inner join silently drops that row. A LEFT JOIN keeps it, and it also creates NULLs of its own for the missing side. Read more in SQL joins explained.

The NOT IN trap

A single NULL in a NOT IN list wipes out every result:

SELECT name FROM employees WHERE manager_id NOT IN (1);
-- Ravi

SELECT name FROM employees WHERE manager_id NOT IN (1, NULL);
-- (no rows)

The second form means manager_id <> 1 AND manager_id <> NULL, and that last part can never be true. This is particularly dangerous with subqueries, where a NULL can arrive unnoticed. Use NOT EXISTS instead, as explained in our SQL subqueries tutorial. Meera is also missing from the first result, since that row’s manager_id is NULL.

Designing with NULL

  • Use NOT NULL by default. Allow NULL only when a value can truly be missing.
  • Add sensible defaults. For example, quantity INT NOT NULL DEFAULT 0.
  • Do not use magic values. A date of 1900-01-01 or an age of -1 standing in for “unknown” will corrupt your calculations.
  • Know the UNIQUE behaviour. Most databases allow several NULLs in a UNIQUE column, and our test inserted two with no error. SQL Server is an exception, as it normally allows one.
  • Remember that a primary key cannot be NULL. See primary key vs foreign key.
  • Test with NULLs. Test data with no NULLs hides these bugs. Include them on purpose, as you would other edge cases.

Final thoughts

Treat NULL as “unknown”, and most of its behaviour starts to make sense: unknown plus one is unknown, and unknown equals unknown is not known to be true. Audit one of your own reports this week. Check nullable columns using COUNT(*) against COUNT(column), look for any NOT IN, and decide what NULL should mean in each average.

Frequently asked questions

What is NULL in SQL?

NULL is a marker for a missing or unknown value. It is different from zero and from an empty string, and it needs special handling in comparisons.

Why does = NULL not work?

Comparing anything with NULL gives unknown rather than true, so WHERE discards the row. Use IS NULL or IS NOT NULL to test for it.

What is the difference between COALESCE and ISNULL?

COALESCE is standard SQL and accepts many arguments. ISNULL is specific to SQL Server and takes two. For portable code, prefer COALESCE.

Does COUNT include NULL values?

COUNT(*) counts all rows, including those with NULLs. COUNT(column) counts only rows where that column is not NULL, which can give a smaller number.

Is NULL the same as an empty string?

No, in most databases. An empty string is a known value with no characters, and NULL means unknown. Oracle is a notable exception, as it treats empty strings as NULL.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →