Class 18 of 58 • Data Manipulation & Querying (DML & DQL)

SQL Logical Operators: AND, OR, NOT & Operator Precedence

Real-world business rules frequently require filtering by multiple conditions simultaneously (e.g., "Find all BCA students who scored above 3.5 GPA OR have completed honors projects"). SQL provides three primary logical operators: AND, OR, and NOT.


1. The AND Operator (Conjunction)

The AND operator returns TRUE only if both conditions evaluate to true:

-- Must be in BCA AND have GPA >= 3.80
SELECT student_id, first_name, course, gpa
FROM students
WHERE course = 'BCA' AND gpa >= 3.80;

2. The OR Operator (Disjunction)

The OR operator returns TRUE if either condition (or both) evaluates to true:

-- Enrolled in BCA OR enrolled in MCA
SELECT student_id, first_name, course
FROM students
WHERE course = 'BCA' OR course = 'MCA';

3. The NOT Operator (Negation)

The NOT operator negates any boolean expression:

-- Exclude all B.Tech students
SELECT student_id, first_name, course
FROM students
WHERE NOT (course = 'B.Tech');

Operator Precedence: The AND vs OR Pitfall

In SQL, AND has higher operator precedence than OR, similar to how multiplication takes precedence over addition in arithmetic:

-- Unintended query bug:
SELECT * FROM students
WHERE course = 'BCA' OR course = 'MCA' AND gpa >= 3.80;

Because AND binds tighter, the engine evaluates this as: "All students in BCA regardless of GPA, PLUS MCA students with GPA >= 3.80".

Correct Production Fix: Always use Parentheses!
-- Correct: Explicit parentheses force OR evaluation first
SELECT * FROM students
WHERE (course = 'BCA' OR course = 'MCA') 
  AND gpa >= 3.80;

Next, let us learn how to sort query output using SQL ORDER BY!


Frequently Asked Questions (FAQ)

AND takes precedence over OR! The database engine evaluates all AND conditions before evaluating OR conditions, unless you explicitly override precedence using parentheses ().

Parentheses eliminate ambiguity, ensure the exact intended business logic is executed, and prevent serious bugs where unauthorized or unrelated rows are accidentally returned.

The NOT operator reverses the truth value of the following condition (e.g., WHERE NOT (course = 'BCA') returns all students whose course is not BCA).

Next Step in Your SQL Database Learning Path:

Proceed to the next class in sequence to build production mastery of relational database architecture.

Continue to Class 19: ORDER BY Clause → Previous: ← WHERE Clause | Full Syllabus


Related SQL Masterclass Lessons & Recommended Next Topics

WHERE Clause Basics →

Foundational row filtering predicates.

IN & BETWEEN Simplification →

Replacing long chains of OR conditions with clean IN lists.

Three-Valued Logic (NULL) →

How UNKNOWN truth values interact with AND and OR.

CASE Expressions →

Implementing complex branching conditional logic in SQL.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!