SQL and databases

Stage 2 · Lesson 3 of 8

NULL and three-valued logic

Querying one table

means a value is missing or unknown. Any comparison with NULL, even NULL = NULL, gives "unknown" rather than true. WHERE keeps only rows where the condition is true, so rows with NULL quietly vanish from filters.

This is called three-valued logic: a condition can be true, false or unknown. Test for missing values with IS NULL and IS , and swap NULL for a default with COALESCE. NULL also affects arithmetic (anything plus NULL is NULL), joining strings in some databases, counting, sorting and , all of which appear in later stages. This one idea explains most "my query lost rows" surprises.

Common trapwriting WHERE phone = NULL, which matches nothing, or WHERE status <> 'cancelled', which also drops every row where status is NULL.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

  • CoursePaid
    Grokking SQL for Tech Interviews

    Design Gurus · Intermediate · Subscription

    The basics, order of execution and functions chapters, each followed by graded problems

  • CourseFree
    SQLBolt

    SQLBolt · Beginner

    Free: Lessons 1 to 4, 8, 9 and 12 cover SELECT, filtering, sorting, NULLs, expressions and query order

Practise

Keep handy

  • The SELECT statement page and the string and date function chapters

  • Its SQL pages give quick examples and note where MySQL and SQL Server syntax differ

Also worth your time

Mark this stage as not done?