Sub topic 1
Predicates in the WHERE Clause
Prerequisites
This chapter assumes you can write basic SELECT statements, understand tables, rows, and columns, use comparison operators such as =, <, and >, and combine conditions with AND and OR in a WHERE clause.
How a Predicate Filters Rows
A predicate is a condition that evaluates to true, false, or unknown for each row. The WHERE clause keeps only the rows where the predicate is true.
SELECT id, name
FROM employees
WHERE department = 'Sales';Matching Text Patterns with LIKE
LIKE compares a text column to a pattern. The % wildcard matches any sequence of characters, including none. The _ wildcard matches exactly one character.
SELECT id, name
FROM employees
WHERE name LIKE 'A%';SELECT id, product_code
FROM products
WHERE product_code LIKE 'AB_-%';Matching a Literal % or _ with ESCAPE
Because % and _ are wildcards, a plain pattern cannot match them as ordinary characters. The ESCAPE clause names a character that marks the next wildcard as literal.
SELECT id, label
FROM promotions
WHERE label LIKE '10!%%' ESCAPE '!';This matches labels that begin with the text "10%". The first % is literal because it follows the escape character, and the second % is a wildcard.
Case Sensitivity and Portability
Whether LIKE ignores case depends on the database and its collation settings. PostgreSQL's LIKE is case-sensitive by default, while MySQL's usually is not. To get the same result on any database, apply LOWER() to the column and write the pattern in lowercase:
SELECT id, name
FROM employees
WHERE LOWER(name) LIKE 'a%';Wrapping the column in LOWER() usually prevents a standard index on that column from being used, so use this form only when portability matters more than speed.
Testing Membership with IN
IN checks whether a value appears in a list. It replaces a chain of OR comparisons and is easier to read.
SELECT id, name, department
FROM employees
WHERE department IN ('Sales', 'Marketing', 'Support');Exercise
Write a WHERE clause that matches product codes beginning with the literal text "50%", using ESCAPE with the character "!".
Show answer
WHERE code LIKE '50!%%' ESCAPE '!'