SQL: Structured Query LanguageSQL FundamentalsPattern Matching

How does the LIKE operator work?

Question 24 of 30 · Updated

On this page

The SQL LIKE operator compares a string with a pattern and returns a Boolean result. In a WHERE clause, it retains rows whose text matches the pattern. For example, WHERE name LIKE 'Pen%' searches for names beginning with Pen under ordinary case-sensitive matching. LIKE is useful for simple prefix, suffix and substring searches without requiring an exact value.

1. Syntax and pattern matching#

SQL
SELECT column_name FROM table_name WHERE column_name LIKE pattern;

A LIKE pattern is a string expression that can contain literal characters and two special wildcards. A percent sign (%) matches zero or more characters. An underscore (_) matches exactly one character. The whole string must match the pattern; LIKE does not automatically search for a substring. To match a substring, put % on both sides of the desired text.

PatternMeaning under ordinary case-sensitive matchingExample match
'Pen'Entire string PenPen
'Pen%'Starts with PenPencil
'%Pen'Ends with PenBlue Pen
'%Pen%'Contains PenBlue Pen Stand
'P_'P followed by exactly one characterPa
'%'Any non-NULL string, including an empty stringNotebook

The quotes delimit SQL string literals. The percent and underscore characters inside those literals are interpreted by LIKE, not as ordinary string equality. Wildcard composition is explored in the subsequent curriculum question; here the focus is choosing LIKE for an actual filtering requirement.

2. Reproducible sample catalog#

Suppose a stationery shop provides a simple name search. The CTE below creates a nine-row inline dataset rather than writing to a permanent table. It deliberately includes different letter cases, literal wildcard characters, a NULL, and an empty string.

idname
1Pen
2Pencil
3Blue Pen
4pen case
5Notebook
6Pen_Stand
7100% Cotton
8NULL
9Empty string

The runnable catalog examples use PostgreSQL's COLLATE "C" to make the ordinary ASCII case-sensitive comparisons explicit and reproducible. This is a PostgreSQL-specific collation choice, not a requirement for using LIKE in every database. In an application, the collation should reflect its search and language requirements.

3. Prefix search: starts with#

SQL
WITH catalog(id,name) AS ( VALUES (1,'Pen'),(2,'Pencil'),(3,'Blue Pen'), (4,'pen case'),(5,'Notebook'),(6,'Pen_Stand'), (7,'100% Cotton'),(8,NULL::text),(9,'') ) SELECT id,name FROM catalog WHERE name COLLATE "C" LIKE 'Pen%' ORDER BY id;
idname
1Pen
2Pencil
6Pen_Stand

The literal prefix Pen must occur at the beginning. The wildcard can match an empty suffix, so Pen itself is included. Blue Pen does not qualify because it begins with Blue, and pen case does not qualify under the explicit case-sensitive comparison. ORDER BY id makes the result order deterministic; LIKE itself does not rank or sort matches.

4. Substring search: contains#

SQL
WITH catalog(id,name) AS ( VALUES (1,'Pen'),(2,'Pencil'),(3,'Blue Pen'), (4,'pen case'),(5,'Notebook'),(6,'Pen_Stand'), (7,'100% Cotton'),(8,NULL::text),(9,'') ) SELECT id,name FROM catalog WHERE name COLLATE "C" LIKE '%Pen%' ORDER BY id;
idname
1Pen
2Pencil
3Blue Pen
6Pen_Stand

Putting % before and after Pen permits any number of characters on either side. This includes exact matches, prefixes and matches inside longer names. This is a literal character-sequence search under the selected collation; it is not a word-boundary, semantic or fuzzy search. Searching for Pen also finds Pencil, which is often useful in a catalog but might be undesirable when exact terms matter.

5. Suffix search and exact matching#

SQL
WITH catalog(id,name) AS ( VALUES (1,'Pen'),(2,'Pencil'),(3,'Blue Pen'), (4,'pen case'),(5,'Notebook'),(6,'Pen_Stand'), (7,'100% Cotton'),(8,NULL::text),(9,'') ) SELECT id,name FROM catalog WHERE name COLLATE "C" LIKE '%Pen' ORDER BY id;
idname
1Pen
3Blue Pen

The string must end with Pen. Pencil and Pen_Stand do not qualify because extra characters follow Pen.

Without a wildcard, the pattern must match the entire string:

SQL
WITH catalog(id,name) AS ( VALUES (1,'Pen'),(2,'Pencil'),(3,'Blue Pen'), (4,'pen case'),(5,'Notebook'),(6,'Pen_Stand'), (7,'100% Cotton'),(8,NULL::text),(9,'') ) SELECT id,name FROM catalog WHERE name COLLATE "C" LIKE 'Pen' ORDER BY id;

Result: ID 1, Pen. For ordinary exact comparisons without pattern interpretation, prefer WHERE name = 'Pen'. Equality is clearer when the value is intended to be literal, particularly if it could contain % or _. Do not assume equality and LIKE behave identically for all types, padding rules and collations.

6. Case sensitivity and PostgreSQL ILIKE#

The case behavior of LIKE depends on the database and its applicable collation and settings. Do not memorize the universal claim that LIKE is always case-sensitive. PostgreSQL provides ILIKE as a case-insensitive pattern-matching extension, with behavior influenced by the active locale. The following ASCII test explicitly uses the C collation:

SQL
WITH catalog(id,name) AS ( VALUES (1,'Pen'),(2,'Pencil'),(3,'Blue Pen'), (4,'pen case'),(5,'Notebook'),(6,'Pen_Stand'), (7,'100% Cotton'),(8,NULL::text),(9,'') ) SELECT id,name FROM catalog WHERE name COLLATE "C" ILIKE 'pen%' ORDER BY id;
idname
1Pen
2Pencil
4pen case
6Pen_Stand

Unlike the earlier prefix search, this returns pen case. ILIKE is not portable standard SQL. Some other database engines use case-insensitive collations for LIKE; another common approach is to compare normalized text with a normalized pattern, such as LOWER(name) LIKE LOWER(pattern). That expression is illustrative and its Unicode, accent, collation and indexing behavior must be checked for the deployed database. Case-insensitive matching does not automatically imply accent-insensitive matching, transliteration or spelling correction.

7. Matching literal percent and underscore characters#

What if the user searches for a product name containing an actual underscore or percent sign? These symbols have pattern meaning unless escaped. An explicit ESCAPE clause identifies the character used to mark the next pattern character as literal. Choose a clear escape character, such as !, instead of relying on backslash and SQL string-literal settings.

SQL
WITH catalog(id,name) AS ( VALUES (1,'Pen'),(2,'Pencil'),(3,'Blue Pen'), (4,'pen case'),(5,'Notebook'),(6,'Pen_Stand'), (7,'100% Cotton'),(8,NULL::text),(9,'') ) SELECT id,name FROM catalog WHERE name COLLATE "C" LIKE '%!_%' ESCAPE '!' OR name COLLATE "C" LIKE '%!%%' ESCAPE '!' ORDER BY id;
idname
6Pen_Stand
7100% Cotton

The first pattern finds strings containing a literal underscore. The second finds strings containing a literal percent sign. With ! as the escape character, !! represents a literal exclamation mark. The unescaped outer percent signs still permit any preceding or following text. Check ESCAPE syntax and defaults for the target database. A detailed study of individual wildcard patterns belongs in the next curriculum lesson.

8. NOT LIKE, NULL and empty strings#

NOT LIKE negates the pattern predicate; it does not turn an unknown comparison into TRUE. Inspect the Boolean results directly:

SQL
WITH catalog(id,name) AS ( VALUES (1,'Pen'),(2,'Pencil'),(3,'Blue Pen'), (4,'pen case'),(5,'Notebook'),(6,'Pen_Stand'), (7,'100% Cotton'),(8,NULL::text),(9,'') ) SELECT id,name, name COLLATE "C" LIKE 'Pen%' AS matched, name COLLATE "C" NOT LIKE 'Pen%' AS negated FROM catalog ORDER BY id;
idnamematchednegated
1PenTRUEFALSE
2PencilTRUEFALSE
3Blue PenFALSETRUE
4pen caseFALSETRUE
5NotebookFALSETRUE
6Pen_StandTRUEFALSE
7100% CottonFALSETRUE
8NULLNULLNULL
9Empty stringFALSETRUE

WHERE retains only TRUE. Therefore WHERE name NOT LIKE 'Pen%' selects known nonmatching strings but excludes the NULL value. If the requirement explicitly includes missing names, use a condition such as WHERE name NOT LIKE 'Pen%' OR name IS NULL. That fragment is illustrative. Do not confuse missing text with a zero-length string.

The following test illustrates the minimum wildcard lengths:

SQL
SELECT '' LIKE '%' AS empty_percent, 'P' LIKE 'P_' AS missing_char, 'Pa' LIKE 'P_' AS one_char, 'Pen' LIKE 'P_' AS extra_char;
empty_percentmissing_charone_charextra_char
TRUEFALSETRUEFALSE

Percent can consume zero characters; underscore requires one character, and the entire pattern must match. Character matching is not a byte-count test. Avoid using LIKE to validate user-perceived grapheme counts or complex Unicode formatting.

9. Safe literal substring search from user input#

Parameterized SQL protects the SQL statement from injection when values are bound correctly, but it does not remove wildcard meaning from a parameter used as a LIKE pattern. An application must decide whether user input is a literal search term or a deliberately authored pattern. For literal substring matching, escape the escape character first, then the percent sign and underscore, and finally surround the escaped text with percent signs.

Here is a reproducible SQL-only demonstration. The input term is 100%, and the result must contain that literal sequence rather than any text beginning with 100.

SQL
WITH input(term) AS (VALUES ('100%')), pattern(p) AS ( SELECT '%' || replace(replace(replace(term,'!','!!'), '%','!%'),'_','!_') || '%' FROM input ), catalog(name) AS ( VALUES ('100% Cotton'),('1000 Cotton'),('100% Linen') ) SELECT name FROM catalog CROSS JOIN pattern WHERE name COLLATE "C" LIKE p ESCAPE '!' ORDER BY name COLLATE "C";

| name | |---| | 100% Cotton | | 100% Linen |

The result excludes 1000 Cotton. Replacing ! first prevents newly introduced escape characters from being escaped again. In a real application, construct the escaped pattern and bind it as a value, or bind the raw search term and perform the escaping in a fixed SQL expression. For example, the following is a PostgreSQL parameterized query template, not a standalone executable statement:

SQL
SELECT id,name FROM catalog WHERE name LIKE $1 ESCAPE '!' ORDER BY id;

The driver binds the already-escaped complete pattern to $1. If the product intentionally supports wildcard searches, do not automatically escape them away; still bind the value safely and enforce query limits. Empty search terms need an explicit policy because surrounding an empty term with percent signs can match almost every known name. Rate limits, bounded result sizes and permissions remain important for public search endpoints.

10. Supabase client usage#

The Supabase JavaScript references provide dedicated like and ilike filters for pattern matching. For a configured client and an accessible catalog table, the following is an illustrative case-insensitive substring search with a fixed pattern:

JAVASCRIPT
const { data, error } = await supabase .from('catalog') .select('id, name') .ilike('name', '%pen%') .order('id') .limit(50); if (error) throw error;

The corresponding like modifier uses LIKE semantics. This snippet is not a live test against a production catalog, and actual matching follows the server's applicable comparison semantics. The official Supabase like and ilike documentation was consulted. For dynamic input, verify how the API and driver represent pattern syntax and escaping, especially literal wildcard characters; do not assume an API helper accepts a SQL ESCAPE clause. Filters are not a substitute for authorization or row-level security.

11. LIKE versus other search techniques#

TechniqueSuitable requirement
Equality (=)Exact known value
INSeveral discrete known values
LIKESimple whole-string, prefix, suffix or substring pattern
Regular expressionMore complex structured pattern
Full-text searchTokenized language-aware text retrieval, often with ranking
Trigram similarityApproximate or substring-oriented text matching depending on operator and index

LIKE has a deliberately small pattern language; it is not a regular expression engine. For example, a dot and asterisk do not have their usual regex meanings in a normal LIKE pattern. PostgreSQL full-text search handles lexical processing and query matching differently, so do not substitute it blindly for literal substring search. Supabase's official Full Text Search guide was also consulted to distinguish these approaches.

12. Performance and indexing#

A prefix pattern with a fixed leading string, such as 'Pen%', can sometimes be supported by a B-tree index with suitable collation and operator class. A leading wildcard such as '%Pen%' generally prevents using an ordinary B-tree as a selective prefix lookup. This does not mean every LIKE query performs a full table scan: PostgreSQL's pg_trgm extension can support suitable LIKE and ILIKE queries through trigram indexes, and the optimizer can combine other filters or choose different strategies.

Very short or broad patterns may still be expensive. A LIMIT caps returned rows, not necessarily the work needed to find them. Choose the index for the workload, inspect the actual execution plan, and measure with representative data. No extension, index or schema change was made for this lesson, and no performance claims were benchmarked.

13. Common mistakes#

MistakeBetter approach
Expecting LIKE 'Pen' to find Blue PenUse '%Pen%' for substring search
Assuming LIKE is always case-sensitive everywhereCheck the database and collation
Treating % or _ as literal text by defaultEscape them when literal matching is intended
Expecting NOT LIKE to include NULLExplicitly decide whether missing values qualify
Using LIKE for spelling correction or semantic searchChoose a search technique matching the requirement
Concatenating raw user input into SQLBind a parameter; define wildcard behavior separately
Assuming every LIKE pattern uses an indexInspect plans and consider appropriate search indexes

14. Interview-ready answer#

LIKE is a SQL pattern-matching predicate for strings. In a WHERE clause it selects rows matching a pattern. The percent wildcard matches zero or more characters, while underscore matches exactly one character. LIKE 'Pen%' finds prefixes, LIKE '%Pen' finds suffixes, and LIKE '%Pen%' finds substrings under the applicable comparison rules. PostgreSQL supports ILIKE for case-insensitive matching; case behavior is database- and collation-dependent. Use ESCAPE to match literal wildcard characters and remember that NULL produces UNKNOWN rather than a match. LIKE is not a regex or full-text search, and performance depends on the pattern and available indexes.

15. Validation and authoritative references#

Nine read-only PostgreSQL statements were executed using synthetic VALUES data or literal expressions: prefix, substring, suffix, exact pattern, ILIKE, escaped wildcards, NOT LIKE and NULL evaluation, minimum wildcard lengths, and literal user-term escaping. All returned the displayed results. General templates and JavaScript client code were not executed. No educational DDL or production business data was accessed or modified. The pattern and result tables directly explain the matching behavior; no Mermaid diagram is necessary. Official Supabase like, ilike and Full Text Search documentation was retrieved through the documentation connector. PostgreSQL links below are authoritative reference destinations but were not live fetched under the established offline research exception. No public-page rendering or cross-database benchmark was verified.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning