SQL AND, OR and NOT Operators
The SQL AND, OR and NOT operators let you combine several conditions in a WHERE clause. AND requires all conditions to be true, OR requires at least one, and NOT reverses a condition.
The AND Operator
Find products in the Snacks category that also cost less than 10.
SELECT ProductName, Category, Price
FROM Products
WHERE Category = 'Snacks' AND Price < 10;ProductName | Category | Price ---------------+----------+------ Dark Chocolate | Snacks | 4.25 (1 row)
The OR Operator
Find customers who are in the UK or in Spain.
SELECT CustomerName, Country
FROM Customers
WHERE Country = 'UK' OR Country = 'Spain';CustomerName | Country ---------------+-------- Cedar Market | UK Delta Supplies | Spain Fresh Mart | UK (3 rows)
The NOT Operator
NOT turns a condition around. This returns every customer outside Pakistan.
SELECT CustomerName, Country
FROM Customers
WHERE NOT Country = 'Pakistan';CustomerName | Country ---------------+-------- Cedar Market | UK Delta Supplies | Spain Evergreen Co | UAE Fresh Mart | UK Harbor Goods | USA Indigo Retail | USA Jade Imports | Canada (7 rows)
Combining AND and OR with Parentheses
AND is evaluated before OR, just like multiplication before addition. Use parentheses to make your intent clear. Here we want beverages or grains, but only if they are in stock above 100 units.
SELECT ProductName, Category, Stock
FROM Products
WHERE (Category = 'Beverages' OR Category = 'Grains')
AND Stock > 100;ProductName | Category | Stock -------------+-----------+------ Basmati Rice | Grains | 120 Green Tea | Beverages | 300 Wheat Flour | Grains | 200 (3 rows)
Tips
- Always use parentheses when mixing AND and OR, even if you know the precedence rules
- For many OR conditions on the same column, IN is shorter
- NOT can be combined with IN, BETWEEN, LIKE and EXISTS
Frequently asked questions
Which runs first in SQL, AND or OR?
AND has higher precedence than OR, so A OR B AND C means A OR (B AND C). Use parentheses to avoid surprises.
How many conditions can I put in a WHERE clause?
There is no practical limit for normal queries. Combine as many as you need with AND and OR, and keep them readable with line breaks and parentheses.
Is NOT the same as <>?
For a single equality, NOT Country = 'UK' and Country <> 'UK' give the same result. NOT is more general because it can negate any condition, such as NOT IN or NOT EXISTS.