SQL IN, BETWEEN and LIKE: Lists, Ranges and Pattern Matching
Three operators that make WHERE clauses shorter and clearer: IN and NOT IN for lists (and the NULL trap inside NOT IN), BETWEEN for inclusive ranges and its pitfalls with dates, and LIKE with the % and _ wildcards, case sensitivity, ILIKE and ESCAPE.
kvi5hnuCode Sprout team member9 min readOn this page
The comparison operators from article 6 can express any condition, but some come up so often that SQL has shorter forms for them:
INtests whether a value equals any value in a list.BETWEENtests whether a value lies in a range.LIKEtests whether text matches a simple pattern.
Each one also has a NOT form. The examples use the Part 2 products table again.
IN and NOT IN
x IN (a, b, c) is shorthand for x = a OR x = b OR x = c. x NOT IN (a, b, c) means x <> a AND x <> b AND x <> c. The list can hold numbers, text or dates, and in article 22 you'll see that it can also be a subquery.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- IN: equal to any value in a list
SELECT name, category FROM products
WHERE category IN ('tents', 'packs')
ORDER BY product_id;
-- NOT IN: equal to none of them
SELECT name, category FROM products
WHERE category NOT IN ('tents', 'packs')
ORDER BY product_id;
-- BETWEEN includes both ends
SELECT name, price FROM products
WHERE price BETWEEN 27.00 AND 89.95
ORDER BY price;
-- The low value must come first: this range is empty
SELECT name, price FROM products
WHERE price BETWEEN 89.95 AND 27.00;
name | category
-------------------+----------
Ridge 2 tent | tents
Summit 4 tent | tents
Trail 30 backpack | packs
Day 18 backpack | packs
(4 rows)
name | category
------------------+----------
Glow head torch | lighting
Basecamp lantern | lighting
Merino socks | clothing
(3 rows)
name | price
-------------------+-------
Basecamp lantern | 27.00
Glow head torch | 34.50
Day 18 backpack | 54.00
Trail 30 backpack | 89.95
(4 rows)
name | price
------+-------
(0 rows)
IN is easier to read than a chain of ORs, and it can't go wrong with precedence the way a = 1 OR a = 2 AND b = 3 can. Use it whenever you're comparing one expression with several values.
NOT IN and NULL
There's one trap with NOT IN, and it's important enough to show before the details of NULL in article 8. If the list contains a NULL, NOT IN can never be true:
-- With a NULL in the list, a value that isn't found gives NULL (unknown), not false
SELECT 3 IN (1, 2) AS plain_in,
3 IN (1, NULL) AS in_with_null,
1 IN (1, NULL) AS found_anyway,
3 NOT IN (1, 2) AS plain_not_in,
3 NOT IN (1, NULL) AS not_in_with_null;
plain_in | in_with_null | found_anyway | plain_not_in | not_in_with_null
----------+--------------+--------------+--------------+------------------
f | | t | t |
(1 row)
The blank cells are NULLs, meaning "unknown":
3 IN (1, NULL)is unknown: 3 isn't 1, and whether 3 equals the unknown value is unknown.1 IN (1, NULL)is true, because one match is enough.3 NOT IN (1, NULL)expands to3 <> 1 AND 3 <> NULL, which istrue AND unknown, which is unknown.
In a WHERE clause, unknown means the row is dropped. So WHERE x NOT IN (list containing a NULL) returns no rows at all. With a literal list you'd rarely type a NULL, but with a subquery, as in WHERE customer_id NOT IN (SELECT customer_id FROM orders), a single NULL in the subquery's result empties your result. Article 16 shows how NOT EXISTS avoids the problem.
BETWEEN
x BETWEEN low AND high means x >= low AND x <= high. It includes both ends, which the first example showed: the products priced exactly 27.00 and 89.95 were included. NOT BETWEEN means x < low OR x > high.
Two things to remember:
- The low value must come first.
BETWEEN 89.95 AND 27.00asks for values that are at least 89.95 and at most 27.00, which is impossible, so the result is empty. There's no error. (The standard has aBETWEEN SYMMETRICform that accepts either order. PostgreSQL supports it, most other products don't.) - Be careful with dates and times.
placed_at BETWEEN '2026-03-01' AND '2026-03-31'stops at midnight at the start of March 31 ifplaced_atholds times. For dates and timestamps, prefer the half-open form from article 6:>= DATE '2026-03-01' AND < DATE '2026-04-01'. Some teams avoidBETWEENfor dates entirely for this reason.
BETWEEN works on text too, using the collation's order: name BETWEEN 'A' AND 'M' includes 'M' itself but not 'Merino socks', which sorts after 'M'. Ranges on text are rarely what you want. For "starts with a letter from A to L", a pattern or a comparison on the first character is clearer.
LIKE and wildcards
LIKE compares text with a pattern that can contain two wildcards:
| Wildcard | Matches | Example pattern | Matches |
|---|---|---|---|
% | any sequence of characters, including none | '%tent' | Ridge 2 tent, tent |
_ | exactly one character | 'S_mmit%' | Summit 4 tent, Sammit |
Every other character in the pattern matches itself. Unless the pattern starts or ends with %, the whole value has to match: 'tent' alone only matches the exact value tent.

CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- % matches any run of characters (including none), _ exactly one
SELECT name FROM products WHERE name LIKE '%backpack' ORDER BY name;
SELECT name FROM products WHERE name LIKE '% _ %' ORDER BY name; -- a one-character word
SELECT name FROM products WHERE name LIKE 'g%' ORDER BY name; -- case matters
-- Case-insensitive matching: lower() works everywhere, ILIKE is PostgreSQL's shortcut
SELECT name FROM products WHERE lower(name) LIKE 'g%' ORDER BY name;
SELECT name FROM products WHERE name ILIKE 'G%' ORDER BY name;
-- NOT LIKE
SELECT name FROM products WHERE name NOT LIKE '%t%' ORDER BY name;
name
-------------------
Day 18 backpack
Trail 30 backpack
(2 rows)
name
---------------
Ridge 2 tent
Summit 4 tent
(2 rows)
name
------
(0 rows)
name
-----------------
Glow head torch
(1 row)
name
-----------------
Glow head torch
(1 row)
name
-------------------
Day 18 backpack
Merino socks
Trail 30 backpack
(3 rows)
Notes on these results:
'%backpack'means "ends with backpack".'backpack%'would mean "starts with", and'%backpack%'would mean "contains".'% _ %'finds names containing a one-character word surrounded by spaces, such as the2inRidge 2 tentand the4inSummit 4 tent. The30and18in the backpack names are two characters, so those don't match.LIKEis case-sensitive in PostgreSQL and Oracle.'g%'found nothing. The usual portable fix is to lowercase both sides:lower(name) LIKE 'g%'. PostgreSQL also hasILIKE, a case-insensitiveLIKE. MySQL, SQL Server and SQLite (for ASCII letters) are case-insensitive by default.NOT LIKE '%t%'kept the names with no lowercaset.Trail 30 backpackwas kept because its onlytis uppercase.
Escaping wildcards
What if you need to match a literal % or _? An ESCAPE clause names a character that makes the next character in the pattern literal:
CREATE TABLE coupons (
code VARCHAR(20) PRIMARY KEY,
discount VARCHAR(10) NOT NULL
);
INSERT INTO coupons VALUES
('SPRING_10', '10%'),
('SPRING10', '10'),
('WINTER_25', '25%'),
('WELCOME', '5%');
-- _ is a wildcard, so this also matches SPRING10
SELECT code FROM coupons WHERE code LIKE 'SPRING_%' ORDER BY code;
-- ESCAPE makes the next character literal: an actual underscore
SELECT code FROM coupons WHERE code LIKE 'SPRING!_%' ESCAPE '!' ORDER BY code;
-- Values that contain a percent sign
SELECT code, discount FROM coupons WHERE discount LIKE '%!%' ESCAPE '!' ORDER BY code;
code
-----------
SPRING10
SPRING_10
(2 rows)
code
-----------
SPRING_10
(1 row)
code | discount
-----------+----------
SPRING_10 | 10%
WELCOME | 5%
WINTER_25 | 25%
(3 rows)
'SPRING_%'matched bothSPRING10andSPRING_10, because the_is a wildcard standing for any one character.'SPRING!_%' ESCAPE '!'matched only the code with a real underscore.'%!%' ESCAPE '!'means "ends with a literal percent sign".
PostgreSQL and MySQL also treat a backslash as the default escape character, so 'SPRING\_%' works there without an ESCAPE clause. Oracle and SQL Server don't have a default escape character, so the explicit ESCAPE form is the portable one. SQL Server also supports character classes in LIKE, such as [0-9] for any digit and [^a] for anything except a, and you can escape a wildcard by putting it in brackets: 'SPRING[_]%'.
When the pattern comes from user input, such as a search box, escape %, _ and the escape character itself in the input before building the pattern, and pass the pattern as a parameter. Otherwise a user who types % matches everything.
LIKE and performance
A pattern with a fixed prefix, such as 'Ridge%', can use an ordinary index on the column. (In PostgreSQL this needs the C collation or an index built with the text_pattern_ops operator class.) A pattern that starts with a wildcard, such as '%tent' or '%tent%', can't use a normal index, so the database tests every row. For real search features on large tables, use full-text search or trigram indexes, such as PostgreSQL's pg_trgm extension, which can speed up LIKE '%tent%' (article 55).
Beyond LIKE
LIKE only has two wildcards. For anything more, such as "a digit followed by two letters" or "either tent or tarp", use regular expressions: ~ in PostgreSQL, REGEXP_LIKE in Oracle, MySQL and SQL Server 2025, and REGEXP in MySQL and SQLite (SQLite's REGEXP needs a regexp() function from an extension; the sqlite3 shell includes one). Article 42 covers them. PostgreSQL also implements the standard SIMILAR TO operator, a cross between LIKE and regular expressions, but it's rarely used.
What's current
- SQL Server 2025 added
REGEXP_LIKEand the other regular-expression functions, so for complex patterns you no longer needLIKEwith character classes or CLR code. - PostgreSQL keeps adding index support for pattern matching through extensions such as
pg_trgm, and version 18 can use B-tree indexes more often for multi-column conditions (article 55).
Common questions
Is IN faster than a chain of ORs?
They mean the same thing, and the optimizer treats them the same way in practice. Use IN because it's easier to read.
How many values can I put in an IN list?
Thousands work, but very long lists are slow to parse and plan, and some products have limits (Oracle allows at most 1,000 expressions in one list). For large sets of values, put them in a table, or a temporary table, and join or use a subquery. In application code, PostgreSQL's = ANY($1) with an array parameter avoids building a long statement.
Does BETWEEN include the end values?
Yes, both of them. x BETWEEN 1 AND 10 includes 1 and 10.
Is LIKE case-sensitive?
In PostgreSQL and Oracle, yes. In MySQL and SQL Server with default collations, no. In SQLite, it's case-insensitive for ASCII letters only. Lowercasing both sides gives the same behaviour everywhere.
Why doesn't LIKE '%tent%' use my index?
A B-tree index is sorted from the first character, so it can find values that start with something, but not values that merely contain it. Use a trigram or full-text index for "contains" searches.
What does x IN () with an empty list do?
It's a syntax error in standard SQL and most products (SQLite accepts it as always false). Application code that builds IN lists must handle the empty case itself, usually by skipping the query or writing a condition that's always false.
Summary
x IN (a, b, c)meansxequals one of the values.NOT INmeans it equals none of them.- If an
INlist contains a NULL, a value that isn't found gives unknown, andNOT INcan never be true. Watch out for this with subqueries. BETWEEN low AND highincludes both ends, and the low value must come first. For dates and times, prefer>= start AND < next_start.LIKEuses%for any sequence of characters and_for exactly one. It's case-sensitive in PostgreSQL and Oracle.- Use
lower(col) LIKE ...(or PostgreSQL'sILIKE) for case-insensitive matching, andESCAPEto match a literal%or_. - A leading
%prevents normal index use. For anything beyond two wildcards, use regular expressions.
Practice questions
Write a query for products in the lighting or clothing categories that cost between 20 and 40, inclusive.
Answer
SELECT name, category, price
FROM products
WHERE category IN ('lighting', 'clothing')
AND price BETWEEN 20 AND 40
ORDER BY price;
This returns the Basecamp lantern (27.00) and the Glow head torch (34.50). The socks are in clothing, but at 16.00 they're below the range.
A teammate writes WHERE product_id NOT IN (SELECT product_id FROM discontinued_items) and gets no rows, even though only two products are discontinued. What's the likely cause?
Answer
discontinued_items.product_id almost certainly contains a NULL. NOT IN against a list that contains a NULL can never be true: each product's test becomes ... AND product_id <> NULL, which is unknown, so every row is dropped. Use NOT EXISTS instead (article 16), or filter the NULLs out of the subquery with WHERE product_id IS NOT NULL.
Which of these names match the pattern '_a%k': Day 18 backpack, Basecamp lantern, Trail 30 backpack, pack?
Answer
'_a%k' means: any one character, then a, then anything, ending with k.
Day 18 backpack: matches (D,a, theny 18 backpac, endingk).Basecamp lantern: doesn't match, because it doesn't end withk.Trail 30 backpack: doesn't match, because the second character isr, nota.pack: matches (p,a, thenc, endingk).
Write a condition that finds coupon codes containing a literal underscore anywhere, in a way that works in PostgreSQL, Oracle and SQL Server.
Answer
WHERE code LIKE '%!_%' ESCAPE '!'
The explicit ESCAPE clause works in all three. Relying on a backslash as the default escape only works in PostgreSQL and MySQL.
Previous: Filtering Rows With WHERE: Comparison and Logical Operators
Next: NULL in SQL: Three-Valued Logic, IS NULL, COALESCE and NULLIF

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.