1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

LIKE finds rows that match a text pattern. It looks simple, but case rules, NULL values and leading wildcards cause real surprises. Here is how it behaves, with every query run.

9 min read
SQL LIKE operator explained: wildcards, case sensitivity and performance

Key takeaways

  • % matches any number of characters, including none. _ matches exactly one.
  • Rows where the column is NULL match neither LIKE nor NOT LIKE.
  • Case sensitivity depends on the database and its collation, so test it on yours.
  • A pattern that starts with % cannot use a normal index. In our test it was roughly 400 times slower.

A support agent needs every customer whose email ends in a certain company domain. A tester wants all order codes that start with a given prefix. These are jobs for the SQL LIKE operator, which matches text against a simple pattern inside a WHERE clause.

We ran every query in SQLite 3.50, and the results shown are from that run. LIKE and its two wildcards are standard SQL, so the basics work everywhere, but we point out where databases differ.

What does LIKE do?

column LIKE pattern is true when the text matches the pattern. The pattern is ordinary text plus two wildcards. Without any wildcards, LIKE behaves much like =, apart from case rules in some databases.

The sample table

CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, code TEXT);
INSERT INTO products (name, code) VALUES
 ('Blue Pen','P-100'), ('blue pencil','P-101'), ('Notebook','N_200'),
 ('Pen Stand','P-102'), ('Open Box','B-300'), ('50% off coupon','C-1'),
 (NULL,'X-1'), ('Café Mug','M-1');

The % wildcard

SELECT name FROM products WHERE name LIKE 'Pen%';
-- Pen Stand

SELECT name FROM products WHERE name LIKE '%pen%';
-- Blue Pen, blue pencil, Pen Stand, Open Box

SELECT name FROM products WHERE name LIKE '%box';
-- Open Box

'Pen%' means “starts with Pen”, '%box' means “ends with box”, and '%pen%' means “contains pen anywhere”. Look closely at the contains result. Open Box matched, because “Open” contains the letters “pen”. Substring searches often return more than you expect, so check the results before using them to update or delete data.

The other rows matched regardless of capital letters, because SQLite’s LIKE ignores case for ASCII letters by default. More on that below.

The _ wildcard

SELECT code FROM products WHERE code LIKE 'P-10_';
-- P-100, P-101, P-102

Each underscore stands for exactly one character. 'P-10_' matches five-character codes that start with “P-10”, but not P-1000. Underscores are useful for fixed-format values such as product codes, postcodes and dates stored as text.

Pattern Matches
'a%' Starts with a
'%a' Ends with a
'%a%' Contains a
'_a%' a is the second character
'a__' Exactly three characters, starting with a
'a%z' Starts with a and ends with z

Escaping % and _

What if the text itself contains a percent sign or an underscore? Our Notebook code is N_200, and one product name contains “50%”. An unescaped pattern like '%%%' simply matched all 7 non-NULL names. To treat a wildcard as a literal character, choose an escape character with ESCAPE:

SELECT name FROM products WHERE name LIKE '%\%%' ESCAPE '\';
-- 50% off coupon

The pattern now reads as “anything, a real percent sign, anything”. The escape character can be any single character you choose. This matters when patterns are built from user input. If a user searches for 50% and you insert it unescaped, the percent sign acts as a wildcard and the search becomes “starts with 50”.

Tip: When building a search from user input, pass the pattern as a query parameter, such as WHERE name LIKE ?, and escape %, _ and your escape character in the input first. Parameters prevent SQL injection, but they do not stop wildcards from acting as wildcards.

NOT LIKE and NULL

SELECT COALESCE(name, '<NULL>') FROM products WHERE name NOT LIKE '%pen%';
-- Notebook, 50% off coupon, Café Mug

The product with a NULL name is missing. We confirmed it with counts: the table has 8 rows, but name LIKE '%pen%' OR name NOT LIKE '%pen%' returned only 7. Comparing NULL with anything gives “unknown”, not true or false, so the row fails both conditions. If NULLs should be included, add OR name IS NULL. Our guide to SQL NULL values explains this three-valued logic.

Case sensitivity

This is where databases differ most. In SQLite, LIKE ignores case for plain ASCII letters but not for other characters:

SELECT name FROM products WHERE name LIKE 'CAFÉ%';   -- (no rows)
SELECT name FROM products WHERE name LIKE 'Café%';   -- Café Mug

Upper-case “É” did not match lower-case “é”. For case-sensitive matching, SQLite offers GLOB, which uses * and ? as wildcards, or the case_sensitive_like setting. Both returned only “blue pencil” and “Open Box” for a lower-case “pen” search.

Database LIKE default Case-insensitive option
PostgreSQL Case-sensitive ILIKE, or LOWER(col) LIKE LOWER(?)
MySQL Usually case-insensitive (depends on collation) Default _ci collations
SQL Server Usually case-insensitive (depends on collation) Default CI collations
SQLite Case-insensitive for ASCII only Default; use GLOB for case-sensitive
Oracle Case-sensitive UPPER() or linguistic settings

The other databases in this table are described from their documentation; we only ran SQLite. The safe habit is to never assume. Check what your database does with one quick query before relying on it.

Performance: the leading wildcard problem

We filled a table with 200,000 email addresses, indexed the column and compared two searches:

WHERE email LIKE 'user1999%'
-- plan: SEARCH big USING COVERING INDEX ix_email (email>? AND email<?)
-- 0.06 ms per query, 111 rows

WHERE email LIKE '%1999@example.com'
-- plan: SCAN big
-- 25.04 ms per query, 20 rows

A prefix search can use the index, because the database can jump to “user1999” in sorted order, like finding a surname in a phone book. A pattern starting with % could match anywhere, so every row had to be checked. Here that was roughly 400 times slower, and the gap grows with the table.

One SQLite detail: the index was only used because the column’s collation matched LIKE’s case-insensitive behaviour, which we set with COLLATE NOCASE. Each database has its own rules here. PostgreSQL, for example, may need a special operator class for LIKE prefix searches. Our SQL indexes guide and query optimization guide cover reading plans like these.

Beyond LIKE

  • Full-text search such as PostgreSQL tsvector, MySQL FULLTEXT or SQLite FTS5 handles word searches in large text quickly, with ranking.
  • Trigram indexes, such as PostgreSQL’s pg_trgm extension, can speed up %contains% searches.
  • Regular expressions are available as ~ in PostgreSQL and REGEXP in MySQL for complex patterns.
  • A reversed column with an index can make “ends with” searches fast, at the cost of extra storage.
  • A search engine such as Elasticsearch or OpenSearch suits fuzzy, typo-tolerant product search.

LIKE for testers

Testers use LIKE constantly to check data after a test run, for example finding records created by an automated test with WHERE email LIKE 'autotest+%'. Give test data a clear, unique prefix so such queries return only your records. When testing a search feature, include inputs containing %, _, accented characters and mixed case, since these are exactly the cases our examples show going wrong. Our list of SQL interview questions for testers includes more queries like these.

Using LIKE safely with parameters

Search boxes usually build the pattern from user input. Never paste the input into the SQL text. Pass it as a parameter and add the wildcards in SQL:

-- SQLite and PostgreSQL use || to join strings
SELECT name FROM products WHERE name LIKE '%' || ? || '%';

-- MySQL uses CONCAT
SELECT name FROM products WHERE name LIKE CONCAT('%', ?, '%');

Parameters stop SQL injection, but the wildcards inside the input still act as wildcards. We ran the SQLite version with two search terms:

"50%"    raw: ['50% off coupon', '500 sheets paper']
         escaped: ['50% off coupon']
"Blue_"  raw: ['Blue_Pen', 'BlueXPen']
         escaped: ['Blue_Pen']

Without escaping, “50%” also matched “500 sheets paper”, and “Blue_” matched “BlueXPen”. A tiny helper fixed both by escaping the escape character first, then % and _, before passing the term with ESCAPE '\':

def escape_like(s, esc="\\"):
    return s.replace(esc, esc * 2).replace("%", esc + "%").replace("_", esc + "_")

Many ORMs and query builders offer an equivalent option, so check your library’s documentation before writing your own.

Final thoughts

LIKE is the quickest way to search text in SQL. Remember the two wildcards, escape them when the data contains them, add IS NULL when NULLs matter, and verify case behaviour on your own database. For large tables, prefer prefix patterns, and move to full-text search when users need to find words anywhere.

Frequently asked questions

What is the difference between % and _ in SQL LIKE?

% matches any number of characters, including zero. _ matches exactly one character.

Is SQL LIKE case-sensitive?

It depends on the database. PostgreSQL and Oracle are case-sensitive by default. MySQL and SQL Server usually are not, depending on collation. SQLite ignores case only for ASCII letters.

How do I search for a literal % or _?

Use the ESCAPE clause, for example LIKE ‘%\%%’ ESCAPE ‘\’, which finds values containing a percent sign.

Why does NOT LIKE skip NULL values?

Comparing NULL with a pattern gives unknown rather than true, so the row is excluded. Add OR column IS NULL to include those rows.

Why is my LIKE query slow?

A pattern starting with % cannot use a normal index, so the database scans every row. Use prefix patterns, a trigram index or full-text search instead.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →