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.
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;
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';
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');
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: 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!