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!

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!