iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL AND

AND combines multiple conditions in WHERE - all must be true for a row to match.

AND in practice

EXAMPLE
-- All three must be true
SELECT id, email
FROM users
WHERE country = 'AU'
  AND active = TRUE
  AND created_at > '2025-01-01';

-- Parentheses control precedence
SELECT id
FROM orders
WHERE (status = 'paid' OR status = 'shipped')
  AND total >= 100;

-- WITHOUT the parens this would mean:
-- status = 'paid' OR (status = 'shipped' AND total >= 100)
-- which is NOT what you wanted.

-- Combine with BETWEEN for ranges
SELECT id
FROM orders
WHERE total BETWEEN 100 AND 500
  AND created_at >= '2026-01-01';

-- Combine with IN
SELECT id
FROM users
WHERE country IN ('AU', 'NZ', 'US')
  AND tier = 'pro';

-- Combine with LIKE
SELECT id
FROM users
WHERE email LIKE '%@example.com'
  AND active = TRUE;

-- NULL is tricky - = does not match NULL
SELECT id
FROM users
WHERE active = TRUE
  AND deleted_at IS NULL;

-- Index hint
-- If country + active is a common combination, a compound index
-- CREATE INDEX users_country_active ON users (country, active);
-- helps both 'WHERE country=' and 'WHERE country AND active'.

-- Equivalent to JOIN ON conditions
SELECT u.id
FROM users u
JOIN orders o ON o.user_id = u.id
            AND o.status = 'paid';
-- JOIN ON is just AND between the joined rows.

-- Common mistake: forgetting AND between WHERE and JOIN ON
-- WHERE conditions filter the final result; JOIN ON filters per row.

Why it matters

AND is straightforward but parentheses matter once OR enters. Whenever you combine AND with OR, parenthesise explicitly - SQL precedence rules favour AND, which surprises new readers and old code alike.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
SELECT * FROM products
WHERE price > 50 AND stock > 0;
Try it Yourself »

Exercise

Find products that are both expensive AND in stock.

WHERE price > 50 stock > 0

Test yourself

Q1. AND returns true when…
Q2. TRUE AND NULL is treated by WHERE as…
Q3. In precedence AND binds…

Discussion

Loading…