PostgreSQL LIKE can count the wrong campaigns when a prefix contains an underscore
A query for campaign names beginning with paid_ can also pull in paid-search. The fix is to distinguish a literal prefix from a SQL pattern.
An analyst asks a SQL assistant for signups from campaigns whose names start with paid_. The assistant writes WHERE campaign LIKE 'paid_%'. That looks like a prefix filter, but in PostgreSQL it also admits paid-search and paidXsearch. If those names belong to other reporting buckets, the signup count can be wrong even though the SQL runs successfully.
PostgreSQL’s pattern-matching reference spells out why: _ matches exactly one character and % matches zero or more. So the generated query asks for paid, followed by any one character, followed by any suffix. It does not require an underscore. The error is in translating the analyst’s intent, not in the database’s execution.
Use a prefix test when the prefix is literal
PostgreSQL’s reference points to starts_with() for this case. If the report is built around the naming convention, write WHERE starts_with(campaign, 'paid_'). If a query builder needs to use LIKE, write WHERE campaign LIKE 'paid!_%' ESCAPE '!'. The explicit escape makes _ literal and leaves the final % as a wildcard. A parameterized LIKE filter still interprets wildcard characters in the bound pattern: binding the text paid_% does not change what _ means. For a user-supplied literal prefix, binding it as the second argument to starts_with() avoids building a pattern at all.
Test the nearest wrong match
Consider a fixture with one signup each for paid_search, paid-search, paidXsearch, and paid. The unescaped pattern counts three signups; the literal prefix counts one. These are expected results derived from the documented matching rules, not a production measurement. Notice that paid matches neither filter: even the unescaped _ requires one more character.
For a regression test, ask the assistant for campaigns beginning with the literal text paid_ and assert that only paid_search comes back. Include a near match such as paid-search; a fixture containing only correctly named campaigns can let both versions of the SQL pass. What matters is not whether the assistant uses a particular function, but whether the rows match the naming rule the analyst intended.
sources
- PostgreSQL documentation: Pattern Matchingwww.postgresql.org
comments · 0
- EKOS’s pending BIRD submission pairs a SQLite-tuned run with a separate hidden-test scoreDec 3, 2026
- MotherDuck rolls out DuckDB 2.0 and reports faster cold reads, not faster agent answersDec 3, 2026
- Oracle Select AI can use two definitions of the same metric. Source order won’t break the tieDec 3, 2026