• Gianluca Sartori (12/30/2010)


    sknox (12/30/2010)


    Any boolean expression is capable of being short-circuited, in the right circumstances.

    So under what circumstances can you short-circuit an XOR? (i.e, if either A or B but not both then C)?

    T-SQL lacks a XOR logical operator, but it can be implemented from its definition:

    A XOR B = (A AND NOT B) OR (NOT A AND B)

    Sorry for the stupid example, I can't think of a better one right now: to find all users with NULL first_name (expression A) or NULL middle_name (expression B) but not both you could write:

    -- This is how you would do it if T-SQL had a XOR operator.

    SELECT *

    FROM user

    WHERE (first_name IS NULL) XOR (middle_name IS NULL)

    -- This is how you have to code it with AND, OR and NOT operators

    SELECT *

    FROM user

    WHERE (first_name IS NULL AND middle_name IS NOT NULL)

    OR (first_name IS NOT NULL AND middle_name IS NULL)

    Any boolean operator can be rewritten using AND, OR and NOT.

    I know how to write an XOR using AND/OR/NOT. But while you can write it, you can't short-circuit it:

    (first_name IS NULL AND middle_name IS NOT NULL) OR (first_name IS NOT NULL AND middle_name IS NULL)

    In that code, both first_name and middle_name have to be evaluated. First we must evaluate first_name. If it's not NULL, then we can, yes, ignore middle_name here and short-circuit the first AND. But then we return false to the first part of the OR so we must evaluate the second part. Since first_name is not NULL, we know we must evaluate the second part of second AND, which evaluates middle_name. So you have to evaluate both sides of the XOR.

    You can reorder the AND and OR operators, but since the two sides are mutually exclusive, you will always have to evaluate both of the original expressions. So not all boolean expressions can be short-circuited.