TECHNOLOGY
The LIKE Operator in SQL for Multiple Value Searches
The LIKE operator in SQL tests many patterns with OR or LIKE ANY if each pattern covers the whole value and you escape a literal percent sign.
You have a list of email domains, product prefixes, or file names, and one equals test will not take the list. The LIKE operator in SQL compares one column value with one pattern, so several values mean several patterns in the same WHERE clause.
OR is the form every engine accepts. On PostgreSQL, LIKE ANY takes the list as an array. The detail that decides the rows is smaller than the choice between those two forms: each pattern has to describe the whole column value, and a shortcut that drops the escape character or puts a percent sign at the front will not follow the single-pattern examples you already trust.
This page walks through that whole-value rule, the three ways to test a list, how case changes the same text on PostgreSQL, MySQL, and SQL Server, how to match a literal percent sign, and which of those patterns a B-tree can use.
LIKE and the Whole Column Value
A LIKE test is true when the string matches the pattern you supply. NOT LIKE is the flip of that result, and NOT (email LIKE pattern) is the same flip. The written form is the column, the word LIKE, the pattern, and an optional ESCAPE clause when a percent sign or underscore in the data should stay a literal character.
Two characters inside the pattern are wildcards, and every other character is literal text that has to appear as itself.
- Percent sign: % matches any run of characters, including a run of length zero, so ‘a%’ matches a, ab, and abc.
- Underscore: _ matches exactly one character, so ‘_b_’ matches abc and does not match ab or abcd.
A pattern that contains neither mark asks for the whole value and nothing else, which makes LIKE behave like equals. ‘abc’ LIKE ‘abc’ is true, and ‘abc’ LIKE ‘c’ is false, because the pattern c does not cover the letters in front of it. To find a piece of text sitting anywhere in the value, the pattern has to start and end with %.
| Pattern | Result for abc |
|---|---|
| abc | true |
| a% | true |
| _b_ | true |
| c | false |
Those four results, plus the escape and collation rules behind them, sit in the PostgreSQL pattern matching chapter. Five underscores in a row match a value of exactly five characters, which is how you pin a code or a short name to a fixed width. Mix the marks when you know one position and not the rest: ‘_da@%’ matches ada@gmail.com, and it also matches any other address whose second and third characters are da.
Once a single pattern covers the value the way you mean, the next job is testing more than one pattern without losing that rule.
How to Search Several Values With LIKE
Picture a contacts table with ada@gmail.com in Austin, ben@outlook.com in Austin, cy@work.test in Dallas, and Ada@gmail.com in Dallas. You want the two public-mail domains, and only the Austin rows. IN cannot do it. IN compares a value with a list for equality, and no major engine defines a LIKE IN form, so ‘IN (‘%@gmail.com’, ‘%@outlook.com’)’ is not a pattern search.
Chain Several LIKE Tests With OR
Chained OR is the portable spelling. Write one LIKE per pattern, join them with OR, and put parentheses around that group before any AND.
- Write one LIKE test per pattern, and put % only where unknown characters are allowed.
- Join the tests with OR so a row survives when any one pattern fits.
- Wrap the OR group in parentheses before you AND a city, a status, or a second column.
SELECT email
FROM contacts
WHERE (email LIKE '%@gmail.com' OR email LIKE '%@outlook.com')
AND city = 'Austin';
Under a case-sensitive collation, that query keeps ada@gmail.com and ben@outlook.com. Ada@gmail.com fails the gmail pattern on case, and cy@work.test fits neither domain, so the city test never saves them. AND binds more tightly than OR. Drop the parentheses and a city test written next to the last LIKE applies only to that last pattern, which silently changes the Austin filter.
Two columns are a different kind of list. first_name LIKE ‘A%’ AND last_name LIKE ‘B%’ keeps a row only when both tests pass. That is a pair of restrictions, not another OR branch, and the parentheses habit still matters as soon as one of those columns grows a second pattern.
Pass an Array With LIKE ANY
PostgreSQL treats LIKE as an operator, so the same test can run against every element of an array. LIKE ANY is true when at least one pattern matches, which is the OR list written as one predicate.
SELECT email
FROM contacts
WHERE email LIKE ANY (ARRAY['%@gmail.com', '%@outlook.com']);
ILIKE ANY is the case-insensitive version of that array test. Application code can bind one array parameter instead of splicing a new OR branch every time the list changes length.
NO ESCAPE CLAUSE ON ANY
- The array: One bound parameter holds every pattern, which keeps the SQL text stable while the list grows.
- The limit: An ESCAPE clause cannot be attached to LIKE ANY, so a literal percent sign in that array has to rely on the default escape inside the pattern string.
When the patterns themselves contain percent signs or underscores, go back to a normal LIKE that names its escape character, or join a table of patterns. Both of those forms still accept ESCAPE. The array form does not.
Keep the Patterns in a Table
A list that editors change, such as blocked domains or brand prefixes, belongs in a table rather than in the query text. Join it, or use EXISTS, and the query stays the same when someone inserts another pattern.
SELECT DISTINCT c.email
FROM contacts c
JOIN domain_patterns d ON c.email LIKE d.pattern;
DISTINCT matters because two patterns can hit the same address and the join then repeats the row. EXISTS avoids the duplicate without a distinct pass: keep the contact when at least one stored pattern matches. This is ordinary LIKE, so you can write ESCAPE on the join condition, and the statement runs on engines that have no array form of ANY. On SQL Server the same idea is an OR list or this join, because that engine has no LIKE ANY.
The three forms above all inherit the case rules of the engine you run them on, and those rules do not match.
How Do Case and Collation Change LIKE?
PostgreSQL LIKE follows the collation. With a typical case-sensitive collation, ‘AbC’ LIKE ‘abc’ is false. The same comparison is true when you attach a case-insensitive collation, and ‘AbC’ LIKE ‘a%’ is true under that collation as well. ILIKE is the PostgreSQL extension that ignores case according to the active locale. It is not part of the SQL standard. LOWER(email) LIKE ‘%@gmail.com’ is the spelling that travels, at the cost of an expression the plain index on email may not match.
| Engine | What LIKE does with case | How you override it |
|---|---|---|
| PostgreSQL | Follows the collation, and a normal collation keeps case | ILIKE, or LIKE with a case-insensitive collation |
| MySQL 8.4 | Case-insensitive by default | A case-sensitive collation, or REGEXP_LIKE with the c flag, when case has to count |
| SQL Server | Follows the collation on the column | COLLATE on that one comparison |
The MySQL pattern matching examples show LIKE ‘b%’ returning both Buffy and Bowser. That default is why Ada@gmail.com, dropped by PostgreSQL LIKE ‘%@gmail.com’, comes back on MySQL from the same pattern text. Copying a working query onto another engine changes the row set before any wildcard is wrong.
SQL Server adds two wildcards the other engines do not use in LIKE. Brackets name a set or a range of single characters, and a caret inside the brackets names the characters to refuse. Case still comes from the collation, so a CI collation ignores case and a CS collation keeps it. Override one comparison with COLLATE rather than rebuilding the column.
A collation that ignores punctuation splits a LIKE pattern into wildcard pieces and plain pieces, then compares the plain pieces under that collation. The underscore still matches exactly one character. ILIKE does not accept that kind of collation, which is a limit of its own and not a reason to avoid LIKE.
How to Escape a Percent Sign or Underscore
A discount code of 100% or a file named report_v2 contains the same characters LIKE treats as wildcards. Left alone, % eats the rest of the value and _ eats any one character, so report_v2 also matches reportXv2. Mark the literal character with an escape.
PostgreSQL’s default escape character is a backslash. The documentation calls that slightly nonstandard, because the SQL standard says that omitting ESCAPE means there is no escape character at all. Pick a character you can see in the pattern and name it.
SELECT name
FROM products
WHERE name LIKE '%100!%%' ESCAPE '!';
The ! tells LIKE that the next percent sign is data, and the percents on either side still mean unknown text, so the pattern finds values that contain the characters 100%. The same move fixes an underscore.
SELECT name
FROM products
WHERE name LIKE 'Apple!_Care%' ESCAPE '!';
Apple_Care Plus matches. AppleXCare Plus does not, because the escaped underscore no longer stands for any character. Write the escape character twice when you need to match that character itself. ESCAPE ” turns the mechanism off, and then a literal percent sign or underscore cannot be written in the pattern. If standard_conforming_strings is off, backslashes inside a quoted literal have to be doubled, which is another reason to pick an escape character other than the backslash.
The SQL Server LIKE wildcard list shows a second way to disarm a wildcard: brackets. LIKE ‘5[%]’ is the two characters 5%, and LIKE ‘[_]n’ is underscore followed by n. Azure Synapse Analytics accepts LIKE and does not support the ESCAPE clause, so brackets are the form that stays available there. On PostgreSQL, remember the array limit from the last section: LIKE ANY cannot carry ESCAPE, so a pattern with a real percent sign belongs in a normal LIKE or in the join.
Index Use With a Multi-Value LIKE Search
A long OR list is still only as fast as each branch. A B-tree can support LIKE, and the regex operator ~, when the pattern is a constant anchored at the start of the value. col LIKE ‘foo%’ and col ~ ‘^foo’ are that shape. col LIKE ‘%bar’ is not. The B-tree pattern matching rules also limit ILIKE and ~*. Those two can use a B-tree only when the pattern starts with characters that upper and lower case do not change.
Outside the C locale, a prefix search needs an index built with text_pattern_ops, varchar_pattern_ops, or bpchar_pattern_ops. Those classes compare character by character instead of by the locale’s sort rules. Comparisons with < and > still want an ordinary index, and both indexes can sit on the same column. Equality can use the pattern class.
A leading percent sign is the pattern people write for “contains,” and a plain B-tree will not serve it. The pg_trgm extension adds GIN and GiST indexes that support LIKE and ILIKE without a left anchor. The planner pulls trigrams out of the pattern. A pattern with no extractable trigrams falls back to a full index scan, so a search for a one-character or two-character piece does not get the same help as a longer token.
Put that next to the multi-value forms. Each branch written as ‘gmail%’ or ‘outlook%’ is a left-anchored constant, which is the shape a B-tree can consider. Every branch written as ‘%gmail%’ is the shape it will not, unless a trigram index exists. LIKE ANY does not change that fact. The array is still a set of patterns, and each pattern is anchored or not on its own.
SIMILAR TO and Regex for Several Values
A long prefix list is sometimes easier as one alternation. SIMILAR TO uses the SQL standard’s regular expressions and, like LIKE, succeeds only when the pattern matches the entire string. It keeps % and _, and it adds alternation with a pipe and grouping with parentheses. A period is an ordinary character in SIMILAR TO, not a stand-in for any character.
SELECT email
FROM contacts
WHERE email SIMILAR TO '%@(gmail|outlook).com';
The official examples make the whole-string rule obvious. ‘abc’ SIMILAR TO ‘%(b|d)%’ is true, and ‘abc’ SIMILAR TO ‘(b|c)%’ is false, because abc does not start with b or c. Forgetting the leading % on a SIMILAR TO alternation drops every row that has characters in front of the match, which feels like a broken OR list.
POSIX regular expressions in PostgreSQL can match any part of the string, which is the behavior LIKE and SIMILAR TO refuse. The operator ~ is case-sensitive, ~* ignores case, and !~ and !~* are the negated pair. You do not wrap those patterns in percent signs. SIMILAR TO and POSIX expressions do not support nondeterministic collations. If you need one, stay on LIKE or apply a different collation to the expression.
PATTERNS FROM OUTSIDE THE APP
- LIKE: A LIKE pattern is the safer test to accept from a user, because the operator is much simpler than the other two.
- Regex: A POSIX pattern, and a SIMILAR TO pattern, can be written to consume arbitrary time and memory, so set a statement timeout if that text comes from outside.
For a fixed list of prefixes, OR or LIKE ANY stays easier to read and keeps you on the operator that is safer with outside text. Reach for SIMILAR TO or ~ when one expression has to express alternation that wildcards cannot, and keep that expression away from untrusted input.
Mistakes With Multiple LIKE Patterns
The wrong rows from a multi-value search usually trace to one of a few pattern mistakes. Each one is a check you can run on the text of the query.
CHECKS BEFORE YOU TRUST THE ROWS
- Missing percent signs: A pattern of gmail.com asks for that exact value, not for an address that merely contains those letters.
- Bare OR beside AND: Without parentheses, a city or status test binds only to the last LIKE.
- LIKE next to IN: IN has no pattern form, so the statement is invalid, or, if the wildcards were removed, it matches exact strings only.
- Unescaped underscore: report_v2 also matches reportXv2 until the underscore is escaped or bracketed.
- Case moved between engines: A pattern that ignores case on default MySQL keeps case on a normal PostgreSQL collation.
Read one row you expected to keep and one you expected to drop. If the dropped row came back, the pattern is wider than the text you had in mind, through a bare underscore or a percent sign in the wrong place. If the kept row vanished, the pattern is short of a %, or the case of one letter no longer agrees with the collation.
Frequently Asked Questions
What Does ~~ Mean in an EXPLAIN Plan?
PostgreSQL rewrites LIKE to the operator ~~, so an EXPLAIN plan shows ~~ where your query wrote LIKE. ILIKE becomes ~~*, NOT LIKE becomes !~~, and NOT ILIKE becomes !~~*. Those four names are specific to PostgreSQL, and you can write them yourself when the word form will not parse.
How Do You Exclude Several LIKE Patterns at Once?
Use NOT LIKE ALL with the array of patterns, which keeps a row only when every pattern fails. Joining separate NOT LIKE tests with OR does the opposite of a ban list, because a gmail address fails an outlook pattern and the OR then succeeds. AND between NOT LIKE tests is the form that matches NOT LIKE ALL.
Does ILIKE Work With a Case-Insensitive Collation?
ILIKE does not support nondeterministic collations, including one built to ignore case, so that collation belongs on a plain LIKE test instead. The comparison is written LIKE ‘abc’ COLLATE case_insensitive, and ILIKE remains a PostgreSQL extension that follows the active locale.
Can the LIKE Operator Search a Number Column?
LIKE is a text pattern test, so a list of exact ids belongs in IN, which compares whole values. A pattern such as ‘2%’ describes characters rather than a numeric range. Keep LIKE on text columns and filter numbers with comparison operators or BETWEEN.
What Is the Starts-With Operator in PostgreSQL?
PostgreSQL also offers the operator ^@ and the function starts_with() when you only need the beginning of a string and there is no wildcard. They do the same job as a prefix pattern without a percent sign. Several prefixes still need OR or LIKE ANY, because neither form takes a list.
Before that query hits the full table, run it on a few rows you already understand: one that should match, one that should miss, one with a capital letter, and one that stores a real percent sign. Those four results show whether the parentheses, the case, and the escape character are doing what you wrote.
-
TRAVEL3 years agoSouthwest Preboarding: Who Qualifies and What to Do
-
NEWS2 months agoFalse AI Intel Nearly Put US Crews on a Chinese Ship
-
LIFESTYLE3 years agoHow Often Do You Have to Change a Monkey’s Diaper?
-
ENTERTAINMENT2 months agoDunes Air Sues Nora Fatehi Over Its Luxury Jet
-
BUSINESS3 months agoTim Cook’s $4.6 Trillion Apple Still Runs on One Phone
-
LIFESTYLE3 years agoHow Long Does It Take for Armpit Hair to Grow?
-
NEWS2 months agoOpenAI Posts a Navier-Stokes Proof Clay Has Not Touched
-
TRAVEL2 years agoSmallest Airlines in the US: Niche Carriers and Unique Flights
