beginner

Logical Operators

7 min readLast updated: 2026-07-23

Overview

Logical operators connect multiple filter predicates inside a WHERE clause, enabling highly precise multi-conditional queries.

Learning Objectives

  • Combine filters using AND, OR, and NOT operators.
  • Analyze operator precedence rules and how to override them with parentheses.
  • Master Boolean truth tables in SQL three-valued logic.

Detailed Concept Explanation

SQL uses three-valued logic: TRUE, FALSE, and NULL (unknown).

  • AND: Returns TRUE only if both conditions evaluate to TRUE.
  • OR: Returns TRUE if at least one condition evaluates to TRUE.
  • NOT: Reverses the boolean outcome of a condition.

Operator Precedence

SQL evaluates logical operators in the order of NOT, then AND, then OR. To override this order and prevent logical bugs, wrap conditions inside parentheses ().


Code Examples

SQL

sql
-- Filter active users located in either the North or West regions
-- Parentheses are vital here to group the OR regions before applying AND status
SELECT name, region, status 
FROM users 
WHERE status = 'Active' 
  AND (region = 'North' OR region = 'West');

-- Negate a criteria using NOT
SELECT product_name 
FROM products 
WHERE NOT category = 'Electronics';

Best Practices

  • Parenthesise Complex Criteria: Always use parentheses when mixing AND and OR to guarantee predictable execution logic.
  • Readability: Format multi-line predicates with consistent indentation so that compound rules are visually clear.

Interview Perspective

Warning

Common Pitfall: Mixing AND/OR without Parentheses

Consider WHERE status = 'A' AND region = 'US' OR region = 'CA'. Due to precedence, this evaluates as (status = 'A' AND region = 'US') OR region = 'CA'. It will return active US users AND all Canadian users regardless of status. Fix this with: status = 'A' AND (region = 'US' OR region = 'CA').


Interactive Challenges

Challenge 1: Compound Filter

Select all names from 'employees' where the 'department' is 'Sales' and 'salary' is strictly less than 50000.


Summary

Logical operators AND, OR, and NOT build complex filters. Remember to use parentheses to secure evaluation precedence.