Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null values - boolean expression

Tags:

sql

null

boolean

So I have a question in regards to an exam assignment, in this assignment we have a bunch of Boolean expressions like:

FALSE OR NULL = NULL

And then we are expected to write the value of the Boolean expression. To do this I am making use of the Three-valued logic, but how does that apply when you get a Boolean expression as follow:

(NULLL AND TRUE) OR FALSE

or

(NULL AND NULL) OR TRUE

The first one can easily be found through three-valued logic, but how do I figure out the other two.

Very basic question, I know, but I am still brand new to this.

Thanks in advance

like image 424
user1845777 Avatar asked Dec 19 '22 07:12

user1845777


1 Answers

You need three-phase truth tables for boolean AND and OR:

OPERAND1  OPERATOR  OPERAND2  RESULT
------------------------------------
TRUE      AND       TRUE      TRUE
TRUE      AND       FALSE     FALSE
FALSE     AND       FALSE     FALSE
TRUE      AND       NULL      UNKNOWN
FALSE     AND       NULL      FALSE
NULL      AND       NULL      UNKNOWN
TRUE      OR        TRUE      TRUE
TRUE      OR        FALSE     TRUE
FALSE     OR        FALSE     FALSE
TRUE      OR        NULL      TRUE
FALSE     OR        NULL      UNKNOWN
NULL      OR        NULL      UNKNOWN

This table is abbreviated, relying on the commutative properties of AND and OR in Boolean logic. In most SQL variants, UNKNOWN and NULL are equivalent. In plain English, if the value can be known even with partial information, it is provided. For example X OR Y is always true if X is true, whether or not Y is known and regardless of the value it takes. Similarly, X AND Y is always false if X is false, whether or not Y is known and regardless of the value it takes. These are lemmas on the Boolean operators and are taught in introductory set theory, among other places.

Once you have these truth tables, you can evaluate your expressions, following the proper precedence order for SQL operators when parentheses are not present.

Here is an evaluation chain for one of your examples:

  • (NULL AND TRUE) OR FALSE
  • (NULL) OR FALSE
  • NULL OR FALSE
  • NULL

See Wikipedia's Three-valued logic entry:Application in SQL for more.

One final note: NULL is never equal to NULL, because you cannot know if two unknown values are in fact equal to each other.

like image 182
Tajh Taylor Avatar answered Jan 02 '23 17:01

Tajh Taylor