sqlsql-servert-sqlthree-valued-logic

Example of three valued logic in SQL Server


I understand that SQL uses three valued logic but I am having trouble understanding how to use this in practice, especially why TRUE || NULL = True and FALSE && NULL = False instead of evaluating to null.

Here are the three valued truth tables that apply to SQL Server:

Tri truth tables

I found a couple explanations of three valued logic online but I cannot find any real code examples of this in use. Can someone show me a code example using three valued logic to help me understand this a little better?


Solution

  • An example of TRUE || NULL = True would be

    declare @x as int = null;
    if 1=1 or @x/1=1
        print 'true'
    

    An example of FALSE && NULL = False would be

    declare @x as int = null;
    if not(1=2 and @x/1=1)
        print 'false'