The idea: NULL is "no value", so a test on it is UNKNOWN

NULL marks a missing value: we do not know Bob's salary. It is not 0 and not an empty string. If the value is unknown, then "is it above 1000?" has no answer either. So SQL conditions have three values: TRUE, FALSE and UNKNOWN. Any comparison with NULL gives UNKNOWN, and AND, OR, NOT follow the tables below. MariaDB writes these values as 1, 0 and NULL.

Three truth tables over T, F and U. AND: T AND T is T, anything AND F is F, T AND U and U AND U are U. OR: anything OR T is T, F OR F is F, F OR U and U OR U are U. NOT: NOT T is F, NOT F is T, NOT U is U.
FALSE wins in AND and TRUE wins in OR; in every other case an UNKNOWN keeps the answer UNKNOWN.

The data on the canvas

One table, emp(id, name, dept, salary, badge), where badge is UNIQUE. Ann (Sales, 1200, B1), Bob (Sales, NULL, NULL), Cid (IT, 800, B3), Dee (NULL, 1500, NULL) and Eve (IT, NULL, B5). Bob and Eve have no salary, Dee has no department, Bob and Dee have no badge. Every query starts from these five rows.

The canvas works each row out the plain way, one row at a time. The truth-table panel lights the AND, OR or NOT cell the row used. The results are the ones MariaDB returns.

WHERE keeps only TRUE

WHERE keeps a row only when its condition is TRUE. FALSE and UNKNOWN both drop it. WHERE salary > 1000 gives Ann and Dee; for Bob and Eve, NULL > 1000 is UNKNOWN (Demo: WHERE keeps only TRUE).

Now flip the test: WHERE NOT (salary > 1000) gives only Cid. NOT UNKNOWN is still UNKNOWN, so Bob and Eve are dropped again (Demo: NOT (salary > 1000) misses NULLs too). The two queries together return 3 of the 5 rows. A condition and its opposite do not split a table in two when the column has NULLs. To get the rest, ask for them: OR salary IS NULL.

AND, OR and NOT with UNKNOWN

Think of UNKNOWN as "could be TRUE or FALSE". If the answer is the same either way, it is known. FALSE AND anything is FALSE, and TRUE OR anything is TRUE. Otherwise the answer stays UNKNOWN (Demo: AND and OR with UNKNOWN):

  • salary > 1000 AND dept = 'Sales' keeps only Ann. Dee is TRUE AND UNKNOWN = UNKNOWN, so she is dropped. Eve is UNKNOWN AND FALSE = FALSE.
  • salary > 1000 OR dept = 'IT' keeps Ann, Cid, Dee and Eve. Dee is TRUE OR UNKNOWN = TRUE. Only Bob is dropped: UNKNOWN OR FALSE = UNKNOWN.

These are the tables of two-valued logic with one more row and column; the two-valued ones are on Truth Tables and Sets.

Testing for NULL: IS NULL, <=>, COALESCE

WHERE salary = NULL returns no rows. It is a comparison with NULL, so it is UNKNOWN for every row, even for Bob and Eve. Even NULL = NULL is UNKNOWN: two missing values are not known to be equal. The right test is salary IS NULL (Bob and Eve) or IS NOT NULL. They are only ever TRUE or FALSE (Demo: = NULL finds nothing, IS NULL works).

MariaDB also has the null-safe equality <=>. It works like =, but it never returns NULL: NULL <=> NULL is 1 and 'IT' <=> NULL is 0. So WHERE NOT (dept <=> 'IT') returns Ann, Bob and Dee, while NOT (dept = 'IT') loses Dee and returns only Ann and Bob (Demo: <=> null-safe equality). <=> is handy when comparing two columns that may both be NULL.

A table of three tests on four inputs. NULL = NULL gives NULL, NULL IS NULL gives 1, NULL <=> NULL gives 1. 'IT' = NULL gives NULL, 'IT' <=> NULL gives 0. 'IT' = 'IT' and 'IT' <=> 'IT' give 1. 'IT' IS NULL gives 0.
= gives NULL (UNKNOWN) as soon as one side is NULL; IS NULL and <=> always answer 1 or 0.

To put a value in place of NULL, use COALESCE(a, b, …), which returns its first argument that is not NULL, or MariaDB's two-argument IFNULL(a, b). COALESCE(salary, 0) is 0 for Bob and Eve. NULLIF(a, b) goes the other way: it returns NULL when a = b.

Aggregates and NULL

Aggregate functions skip NULL values. COUNT(*) counts rows; COUNT(salary) counts the salaries that are not NULL; SUM and AVG use only those values. On emp: COUNT(*) = 5, COUNT(salary) = 3, SUM(salary) = 3500, and AVG(salary) = 3500 / 3 = 1166.6667, not 3500 / 5 (Demo: COUNT(*) vs COUNT(salary), AVG).

Whether that is right depends on what NULL means. If a NULL salary means "not known", averaging the known ones is fair. If it means "paid nothing", write AVG(COALESCE(salary, 0)) = 3500 / 5 = 700.0000. MariaDB prints the average of an INT column as a DECIMAL with 4 more decimal places (div_precision_increment = 4). Over no non-NULL values at all, SUM, AVG, MIN and MAX give NULL, while COUNT gives 0.

GROUP BY, ORDER BY and UNIQUE: are two NULLs the same?

For WHERE, NULL = NULL is UNKNOWN. Other parts of SQL had to decide anyway, and they decided differently:

WhereTwo NULLs are…On emp
WHERE a = bneither: UNKNOWNsalary = NULL: 0 rows
GROUP BY, DISTINCTthe same: one groupone NULL group for Dee
ORDER BYequal, and smaller than every valueNULL first in ASC, last in DESC
UNIQUE index (InnoDB)different: any number allowedBob, Dee and Fay all have badge NULL

SELECT dept, COUNT(*), COUNT(salary) FROM emp GROUP BY dept ORDER BY dept gives NULL (1, 1), IT (2, 1) and Sales (2, 1). All NULL depts would fall in the one NULL group, and it sorts first (Demo: GROUP BY puts NULLs in one group). How GROUP BY and ORDER BY fit in a whole SELECT is on How a SELECT Runs.

A UNIQUE column refuses a real value that is already there, but it accepts any number of NULLs. Inserting Fay with badge NULL succeeds; there are now 3 NULL badges. Inserting Gus with badge 'B1' fails with ERROR 1062 (23000): Duplicate entry 'B1' for key 'badge', because Ann has it (Demo: UNIQUE allows many NULLs). To forbid missing badges too, declare the column NOT NULL UNIQUE. A PRIMARY KEY column is always NOT NULL.

Summary

Query on empResult
WHERE salary > 1000Ann, Dee
WHERE NOT (salary > 1000)Cid (Bob, Eve in neither)
salary > 1000 AND dept = 'Sales'Ann
salary > 1000 OR dept = 'IT'Ann, Cid, Dee, Eve
WHERE salary = NULLno rows
WHERE salary IS NULLBob, Eve
WHERE NOT (dept <=> 'IT')Ann, Bob, Dee
COUNT(*), COUNT(salary), SUM, AVG, AVG(COALESCE)5, 3, 3500, 1166.6667, 700.0000
GROUP BY dept ORDER BY deptNULL 1 1, IT 2 1, Sales 2 1
2 INSERTs into badge UNIQUENULL accepted; 'B1' error 1062

See also SQL Subqueries, Row by Row for the NOT IN trap, where one NULL in a subquery's result empties the whole answer, and SQL Joins on Real Rows for how an outer join fills missing partners with NULL.

See also EER Specialization, where a CHECK uses the null-safe <=> so that a NULL type column can't slip through as unknown.

What the page leaves out

MariaDB has no separate boolean type: BOOLEAN is TINYINT(1), and a condition's UNKNOWN is simply NULL. The tests IS TRUE, IS FALSE and IS UNKNOWN exist and never return NULL; they are not drawn. CHECK constraints pass on UNKNOWN, the opposite of WHERE. The NOT IN trap with subqueries, NULL padding in outer joins, NULLS FIRST/NULLS LAST (MariaDB does not have them; sort on col IS NULL first instead) and indexes on NULL columns are only named here. The canvas lists rows in table order; without ORDER BY MariaDB promises no order.

On the mind map

Open the Databases & Storage mind mapDatabases& StorageSchema and storage: how rows land on diskSchema and storageIndexes: find rows without a full scanIndexesRunning a query: parse, plan, executeRunning a queryCost-based optimizer: estimate rows, pick cheapest planCost-based optimizerQuery rewrites: same answer, simpler queryQuery rewritesTransactions: ACID: isolation and recoveryTransactionsApps and connections: the client side of the databaseApps and connectionsMongoDB: documents, replica sets, shardsMongoDBHow MySQL runs a queryHow MySQL runs a querybuffer pool, undo, redo, binlogHow PostgreSQL runs a queryHow PostgreSQL runs a querynew tuple per update, VACUUM, WALSELECT clause orderSELECT clause orderFROM, WHERE, GROUP BY, HAVING, SELECTJoin algorithmsJoin algorithmsnested loop, hash, merge: pick by sizeExternal merge sortExternal merge sort2N I/Os per pass, merge B−1 runs at onceFile organizationsFile organizationsHeap inserts, sorted ranges, hash findsMySQL JOIN, GROUP, ORDERMySQL JOIN, GROUP, ORDERtemporary table and filesortPostgres JOIN, GROUP, ORDERPostgres JOIN, GROUP, ORDERHashAggregate or Sort, by work_memRelational algebraRelational algebraselect, project, join: tables in, table outSQL joins on rowsSQL joins on rowsOuter joins pad unmatched rows with NULLSQL subqueriesSQL subqueriesOne NULL makes NOT IN return no rowsNULL and 3-valued logicWHERE keeps only TRUE, not UNKNOWNTriggers and proceduresTriggers and proceduresPer row; a CALL is not one statementWindow functionsWindow functionsaggregate per row without collapsingOpen the Databases & Storage mind mapDatabases & Storageparse, plan, executeRunning a queryHow MySQL runs a queryHow MySQL runs a querybuffer pool, undo, redo, binlogHow PostgreSQL runs a queryHow PostgreSQL runs a querynew tuple per update, VACUUM, WALSELECT clause orderSELECT clause orderFROM, WHERE, GROUP BY, HAVING, SELECTJoin algorithmsJoin algorithmsnested loop, hash, merge: pick by sizeExternal merge sortExternal merge sort2N I/Os per pass, merge B−1 runs at onceFile organizationsFile organizationsHeap inserts, sorted ranges, hash findsMySQL JOIN, GROUP, ORDERMySQL JOIN, GROUP, ORDERtemporary table and filesortPostgres JOIN, GROUP, ORDERPostgres JOIN, GROUP, ORDERHashAggregate or Sort, by work_memRelational algebraRelational algebraselect, project, join: tables in, table outSQL joins on rowsSQL joins on rowsOuter joins pad unmatched rows with NULLSQL subqueriesSQL subqueriesOne NULL makes NOT IN return no rowsNULL and 3-valued logicWHERE keeps only TRUE, not UNKNOWNTriggers and proceduresTriggers and proceduresPer row; a CALL is not one statementWindow functionsWindow functionsaggregate per row without collapsing
This page on the Databases & Storage mind map · 58 pages in 8 branches · open it to see the whole map and test yourself in recall mode.