WHERE: Conditions and Operators

WHERE evaluates the condition for each row and keeps only rows where it is TRUE. If the condition is false or unknown (NULL), the row is dropped. Unknown is covered in NULL and three-valued logic.

Comparison operators

OperatorMeaning
=Equal
<>Not equal (!= also works in all three DBs, but <> is standard)
<, <=, >, >=Ordering. Strings compare in dictionary order, dates in time order

Orders of 400,000 won or more

SELECT ord_id, cust_id, status, amt
FROM orders
WHERE cust_id = 101
  AND amt >= 400000
ORDER BY ord_id

BETWEEN: ranges

a BETWEEN x AND y is the same as a >= x AND a <= y. Both ends are included.

Customer IDs 101-105

SELECT cust_id, cust_nm, grade
FROM customers
WHERE cust_id BETWEEN 101 AND 105
ORDER BY cust_id

IN: one of a list

a IN (x, y, z) is the same as a = x OR a = y OR a = z. A subquery can take the place of the list.

VIP or GOLD customers

SELECT cust_id, cust_nm, grade
FROM customers
WHERE grade IN ('VIP', 'GOLD')
  AND cust_id <= 50
ORDER BY cust_id

LIKE: string patterns

SymbolMeaning
%Any string (including the empty string)
_Any single character

Customers whose name starts with CUST10

SELECT cust_id, cust_nm
FROM customers
WHERE cust_nm LIKE 'CUST10_'
ORDER BY cust_id

'CUST10_' matches only names with exactly one more character after CUST10 (CUST100-CUST109). Change it to 'CUST10%' and run it to also get names of other lengths, such as CUST10 and CUST1000.

NOTE Case sensitivity follows the DB settings. Oracle and PostgreSQL are case-sensitive by default; in SQL Server the default collation is often case-insensitive.

NOT and negation

NOT BETWEEN, NOT IN, and NOT LIKE invert a condition. NOT IN returns 0 rows if the list contains a NULL (NULL and three-valued logic).

VIP customers outside Seoul and Busan

SELECT cust_id, region
FROM customers
WHERE grade = 'VIP'
  AND region NOT IN ('SEOUL', 'BUSAN')
  AND cust_id <= 3000
ORDER BY cust_id

Precedence of AND and OR

AND is evaluated before OR. The two queries below differ only by one pair of parentheses, but their results differ.

No parentheses: all VIP + GOLD in Seoul

SELECT grade, region, COUNT(*) AS cnt
FROM customers
WHERE grade = 'VIP' OR grade = 'GOLD' AND region = 'SEOUL'
GROUP BY grade, region
ORDER BY grade, region

With parentheses: VIP and GOLD in Seoul

SELECT grade, region, COUNT(*) AS cnt
FROM customers
WHERE (grade = 'VIP' OR grade = 'GOLD') AND region = 'SEOUL'
GROUP BY grade, region
ORDER BY grade, region

The first query reads as grade = 'VIP' OR (grade = 'GOLD' AND region = 'SEOUL'). Always use parentheses when mixing AND and OR.