Skip to content

Logic and Comparison

Single conditions are rarely enough for complex data analysis. SQL provides logical operators to combine multiple conditions and specialized comparison operators to handle ranges and lists efficiently.

Logical operators allow you to build complex “Boolean” expressions.

  • AND: Returns TRUE only if both conditions are true.
  • OR: Returns TRUE if at least one condition is true.
  • NOT: Reverses the value of a condition (True becomes False, and vice-versa).

Just like in math where multiplication happens before addition ($2 + 3 imes 5 = 17$), SQL has an order of precedence for logical operators:

  1. NOT (Highest)
  2. AND
  3. OR (Lowest)

Detailed Explanation: Range and List Operators

Section titled “Detailed Explanation: Range and List Operators”

While you could use multiple AND or OR statements, SQL provides cleaner alternatives.

Used to filter values within a range (inclusive of the start and end values).

  • Standard: Price >= 10 AND Price <= 20
  • SQL Idiomatic: Price BETWEEN 10 AND 20

Used to check if a value matches any value in a provided list.

  • Standard: City = 'London' OR City = 'Paris' OR City = 'Tokyo'
  • SQL Idiomatic: City IN ('London', 'Paris', 'Tokyo')

We have a Staff table:

IDNameDeptSalaryPerformance
1JohnIT600004
2JaneHR550005
3BobIT900003
4MarySales700005

We want IT employees earning between 50k and 100k, OR anyone with a Performance score of 5.

Complex Predicates
SELECT Name, Dept, Salary, Performance
FROM Staff
WHERE (Dept = 'IT' AND Salary BETWEEN 50000 AND 100000)
OR Performance = 5;
NameDeptSalaryPerformance
JohnIT600004
JaneHR550005
BobIT900003
MarySales700005

Wait, why was Bob included? Let’s check the logic:

  • Bob is in IT? Yes.
  • Bob’s salary is between 50k-100k? Yes (90k).
  • Thus, the first part of the OR is true.

Most modern SQL engines use Short-Circuit Evaluation.

  • For an AND operation: If the first condition is FALSE, the engine stops immediately because the result can never be TRUE.
  • For an OR operation: If the first condition is TRUE, the engine stops immediately because the result is already guaranteed to be TRUE.

If you have two conditions in an AND clause:

  1. One is a complex calculation (slow).
  2. One is a simple ID check (fast).

Place the simple check first. The engine might skip the slow calculation entirely if the simple check fails.