Posted on July 16, 2024 by AgentM

Are You Qualified To Use Null in SQL?

Take this quiz to find out.


Difficulty: Level 1

Boolean with NULL

SELECT NULL AND TRUE;

Boolean with NULL 2

SELECT NULL AND FALSE;

SUM with NULL

SELECT SUM(a) FROM (VALUES (3),(NULL)) as x(a);

COUNT with NULL

SELECT COUNT(a) FROM (VALUES (3),(NULL)) as x(a);

NULL equality

SELECT * FROM (VALUES (3),(NULL)) as x(a) WHERE a = NULL;

IS NULL

SELECT * FROM (VALUES (3),(NULL)) as x(a) WHERE a IS NULL;


Difficulty: Level 2

OUTER JOIN with NULL

SELECT * FROM (VALUES (3),(NULL)) as x(a) LEFT OUTER JOIN (VALUES (3),(NULL)) as y(a) ON x.a = y.a;

SUM of column with NULL

SELECT SUM(a) FROM (VALUES (NULL::int)) AS x(a);

SUM of an empty table

SELECT SUM(a) FROM (VALUES (1),(2)) as x(a) WHERE false;

AVG with NULL

SELECT AVG(a) FROM (VALUES (3),(NULL)) as x(a);

NULL with IN

SELECT * FROM (VALUES (3),(NULL)) as x(a) WHERE a IN (NULL,3);

NULL with NOT IN

SELECT * FROM (VALUES (3),(NULL)) as x(a) WHERE a NOT IN (1);

NULL with CONCAT

SELECT CONCAT('uh oh', NULL);

NULL with ||

SELECT 'uh oh' || NULL;


Difficulty: Level 3

NULL in CHECK constraint

CREATE TABLE test(a INTEGER CHECK(a>0)); INSERT INTO test(a) VALUES (NULL);

NULL with DISTINCT

SELECT DISTINCT(a) FROM (VALUES (3),(NULL),(NULL)) as x(a);

NULL with GROUP BY

SELECT a FROM (VALUES (3),(NULL),(NULL)) as x(a) GROUP BY a;

NULL with GROUP BY + CASE

SELECT CASE WHEN a IS NULL THEN 5 ELSE a END FROM (VALUES (3),(NULL),(NULL)) as x(a) GROUP BY a;

NULL WITH GROUP BY + NULL equality + CASE

SELECT CASE WHEN a = NULL THEN 5 ELSE a END FROM (VALUES (3),(NULL),(NULL)) as x(a) GROUP BY a;

NULL with UNIQUE constraint

CREATE TABLE y(a INTEGER, UNIQUE(a)); INSERT INTO y(a) VALUES (NULL),(NULL),(3); table y;

NULL with EXISTS

SELECT 5 WHERE EXISTS(SELECT NULL);

Typed NULL

SELECT CAST(NULL AS INTEGER) IS DISTINCT FROM CAST(NULL AS TEXT);

Did you score as well as you expected? Did you ever consider that a DBMS could be created which did not include support for NULL? Project:M36 is a ground-up implementation of the relational algebra without NULL or its pitfalls.

To learn more about the pitfalls surrounding SQL NULLs and ternary logic, read On NULL.