Logical Operators
In this page:
The AND Operator
The AND operator combines conditions in a WHERE clause. It returns true only if all individual conditions are true, so adding more AND conditions can only narrow your results further, never widen them.
Example: The AND Operator
CREATE TABLE products (id INT, price INT, stock INT);
INSERT INTO products VALUES (1, 20, 5), (2, 80, 5), (3, 20, 0);
SELECT * FROM products WHERE price = 20 AND stock > 0;
The OR Operator
The OR operator evaluates multiple conditions. It returns true if at least one of the conditions is true, so it's useful for matching any of several acceptable values or states.
Example: The OR Operator
CREATE TABLE products (id INT, category TEXT);
INSERT INTO products VALUES (1, 'Books'), (2, 'Toys'), (3, 'Food');
SELECT * FROM products WHERE category = 'Books' OR category = 'Toys';
The NOT Operator
The NOT operator reverses the truth value of a condition. It turns true into false, and false into true, which is handy for excluding a specific case without rewriting the whole condition as its opposite.
Example: The NOT Operator
CREATE TABLE products (id INT, category TEXT);
INSERT INTO products VALUES (1, 'Books'), (2, 'Toys'), (3, 'Food');
SELECT * FROM products WHERE NOT category = 'Food';
The XOR Operator
The XOR operator stands for exclusive OR. It returns true if exactly one condition is true, but not both, which is useful for 'either but not both' logic that plain OR can't express directly.
Example: The XOR Operator
CREATE TABLE users (id INT, has_email INT, has_phone INT);
INSERT INTO users VALUES (1, 1, 0), (2, 1, 1), (3, 0, 0);
SELECT * FROM users WHERE has_email XOR has_phone;
Logical Operator Precedence
SQL evaluates operators in a specific order when combining AND, OR, and NOT in one WHERE clause. NOT is evaluated first, then AND, and finally OR. Use parentheses to change this precedence explicitly rather than relying on the reader to remember the default order.
Example: Logical Operator Precedence
CREATE TABLE products (id INT, category TEXT, price INT);
INSERT INTO products VALUES (1, 'Books', 20), (2, 'Toys', 80), (3, 'Food', 20);
SELECT * FROM products WHERE category = 'Books' OR category = 'Toys' AND price > 50;
SELECT * FROM products WHERE (category = 'Books' OR category = 'Toys') AND price > 50;
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: