0
0
SQLquery~5 mins

NULL in AND, OR, NOT logic in SQL

Choose your learning style9 modes available
Introduction
NULL means unknown in databases. Understanding how NULL works with AND, OR, and NOT helps you get correct answers when data is missing or unknown.
When you want to check if multiple conditions are true but some values might be missing.
When filtering data that may have unknown or missing values.
When combining conditions and you need to know how unknown values affect the result.
When writing queries that use NOT to exclude certain rows but some values are NULL.
When debugging why some rows appear or disappear unexpectedly in query results.
Syntax
SQL
condition1 AND condition2
condition1 OR condition2
NOT condition
NULL means unknown, so logical operations with NULL can result in NULL (unknown) instead of TRUE or FALSE.
In SQL, TRUE, FALSE, and NULL form a three-valued logic system.
Examples
Result is NULL because one side is unknown.
SQL
TRUE AND NULL
Result is NULL because one side is unknown and the other is false.
SQL
FALSE OR NULL
Result is NULL because NOT unknown is still unknown.
SQL
NOT NULL
Result is TRUE because OR with TRUE always returns TRUE.
SQL
TRUE OR NULL
Sample Program
This query shows how NULL behaves with AND, OR, and NOT.
SQL
SELECT
  TRUE AND NULL AS and_result,
  FALSE OR NULL AS or_result,
  NOT NULL AS not_result,
  TRUE OR NULL AS or_true_result;
OutputSuccess
Important Notes
When NULL is involved, AND returns TRUE only if both sides are TRUE.
OR returns TRUE if any side is TRUE, even if the other is NULL.
NOT NULL remains NULL because negation of unknown is still unknown.
Summary
NULL means unknown and affects logical operations differently than TRUE or FALSE.
AND with NULL returns NULL unless the other side is FALSE (then FALSE).
OR with NULL returns TRUE if the other side is TRUE, else NULL.
NOT NULL always returns NULL.