Basics: pattern matching instead of LIKE

Operators ~ and ~*: Where LIKE Falls Short

34 min

Chapter 1 — “Basics: Pattern Matching Instead of LIKE”

You enter the Sorting Room of Vault-9. Racks hum behind the door, while fragments of the first signal flicker together on an amber panel: a delivery complaint, a phone number, an address, a line from a server log. The decoder has already sorted out the Kotomarket tables, but this tail end of the signal was left here untouched.

The Commandant puts the first message on the screen: Hello! Order KM-2024-001234 still has not arrived. He opens the eighth—the code is hidden inside a link. The fourteenth message contains several such codes at once. In the third, the same prefix is lowercase: km-2024-000777.

Checking known codes one by one makes no sense: there may be a hundred today and a thousand tomorrow. We need a notation that describes the general shape of a code and searches for that shape inside text.

QUERY: The fragments have different numbers, but the pattern is the same. That's what we'll track down.

That notation is called a regular expression, or simply a regex. We'll get to the special symbols later. For now, we'll start with ordinary letters and see how this kind of search differs from the LIKE you already know.

A cadet with a flashlight enters the dark Sorting Room: piles of glowing fragments surround them, while a rectangular sieve of light floats ahead and catches only a few matching capsules as the rest slip through; a cat watches the sieve from the cadet's shoulder.
LIKE knows letters and two wildcards, % and _. A regex can catch an entire family of values.

Find by description

Take the pattern cat. There's no magic in it yet: just three ordinary letters. Read it from left to right—first “c,” immediately followed by “a,” then “t.”

Apply it to the string cat. The first letter matches, then the second, then the third. Together they form one continuous three-character piece. A piece of text found this way is called a match.

With the string cut, the match fails on the second letter. The pattern expects “a” but gets “u,” so there is no match at that position. In my cat sleeps, however, the text at the beginning doesn't matter: the search reaches cat in the middle of the string and finds those three letters.

A regular expression describes what kind of text fragment should match. This notation is also called a pattern. In documentation, you'll often see the terms regular expression and regex.

For now, the pattern almost looks too simple. That's useful. Once special symbols appear later, reading a regex piece by piece will make it much easier to understand. I don't try to take in someone else's half-screen-long pattern at a glance either: I move from left to right and work out what each part requires.

Now take KM-. Again, we have three exact characters in a row: the Latin letter K, the Latin letter M, and a hyphen. The string Order KM-2024-001234 contains that fragment, so it matches. Promo code KOTO-2024 does not: after K comes O, while the pattern expects M.

A regex knows nothing about orders or promo codes. It only sees characters. If you write KM-, it looks for K, then M, then -. Keep that in mind whenever you're tempted to give a pattern more common sense than you actually wrote into it.

Where this kind of search appears

Real-world data rarely looks like a tidy classroom example. In contacts, one person writes Miami, another writes Miami, FL, and a third writes miami. An order code in a support message may appear after a greeting, be hidden inside a link, or occur several times. In a server log, the page address is surrounded by the request time, response code, and browser name.

So we often search for a fragment with a particular shape rather than an entire string. Code editors can search with regexes. grep does the same in text files. Forms can use a pattern to check whether entered text resembles the expected format. When cleaning an export, a regex can quickly reveal extra spaces or different versions of the same separator.

This kind of search has a clear limit. A regex checks the form of text. A string may look like an email address, but that doesn't mean the mailbox exists. A sequence of digits may resemble a phone number, but a regex can't tell whether that number belongs to anyone.

Our archive has three tables: contacts with raw contact data, tickets with customer messages, and access_log with the server log. We'll start with tickets. In an ordinary sentence, it's easier to see where the match is and why the query selected it.

Where regular expressions came from

The term appeared long before PostgreSQL and modern text editors. In 1951, mathematician Stephen Kleene described a theory involving regular sets and regular languages. Here, “language” is meant mathematically: a set of sequences that follow particular rules. The work appeared as a RAND report, followed by a well-known publication in a book in 1956.

By the late 1960s, Ken Thompson had brought these ideas into text search: first in the QED editor, then in ed. Dennis Ritchie describes this history in detail. The ed command that searched for lines and printed them later gave rise to grep.

Regular expressions have a long history, but our first task is much more practical: find KM- inside a message. For now, three ordinary characters are enough.

Start with a familiar search: LIKE

In the first message, the code is surrounded by other text. On the left is Hello! Order , and the sentence continues on the right. The condition body LIKE 'KM-' won't match this row: a LIKE pattern is matched against the entire string.

So to search for a fragment inside a string with LIKE, you'd usually write %KM-%.

Here's what happens. The first % matches any number of characters before the part we need. Then K, M, and - must appear consecutively. The second % matches the rest of the string. For Order KM-2024-001234 is ready, the first percent sign matches Order , then KM- matches, and the last percent sign covers 2024-001234 is ready.

Here's a useful edge case: a string containing only KM- also matches. Both % symbols can match an empty fragment, so characters before and after KM- are optional.

LIKE also has _, which matches exactly one arbitrary character. But “any character” becomes a problem when the requirement specifically calls for a digit. A letter would match just as easily in place of _. We'll get to more precise rules for codes later. For now, focus on the difference in how the two searches work.

Before you run the cell, make two predictions. Will ticket 1 appear even though KM- sits in the middle of a long sentence? And what will happen to ticket 3, where the text contains lowercase km-?

SELECT ticket_id, body
FROM tickets
WHERE body LIKE '%KM-%'
ORDER BY ticket_id;

The tilde: is there a match?

Take the same text, but replace LIKE with PostgreSQL's ~ operator. The condition body ~ 'KM-' asks: does a fragment matching KM- occur anywhere inside body?

For each row, there is only one answer: true or false. If that condition appears in WHERE, PostgreSQL keeps the rows for which the result is true.

For now, the pattern is read literally: K, then M, then -. Characters that represent themselves are called characters. Even these three literal characters already form a regular expression, despite having no special symbols yet.

Here's the first difference to remember. LIKE matches its pattern against the entire string, so we added % on both sides when searching inside it. ~ searches for a suitable position inside the text on its own. You don't need percent signs around KM-.

Picture a short transparent three-cell frame containing KM-. The search places it at the start of the string. No match? It shifts the frame forward. Still no match? It moves again. In ticket 1, the frame eventually reaches the position after the word Order, where all three cells match.

In the diagram beside this text, the two approaches appear on the same line: the regex finds a place for KM-, while LIKE with % describes the entire value from beginning to end.

I often see the same mistake here: after years of using LIKE, your fingers automatically type %KM-% inside a regex too. Don't carry that syntax over by habit. In a regular expression, % does not play the role it has in LIKE.

And don't give the pattern meaning that isn't there. The check body ~ 'KM-' confirms only that the characters KM- are present. The string broken: KM- also returns true, even though no number follows the hyphen. We asked PostgreSQL to find three characters, and that's exactly what it did.

With ~, specifying KM- is enough: the search finds that fragment inside the string on its own. With LIKE, the same task requires % on both sides.
SELECT ticket_id, body
FROM tickets
WHERE body ~ 'KM-'
ORDER BY ticket_id;

Let's test both mechanisms on four short strings. There's no long support message to hide behind now: you can see every character.

Order KM-2024-001234 is ready matches both the %KM-% pattern and the KM- regex. With LIKE, the percent signs match the beginning and end of the value. The regex simply finds KM- in the middle.

The string KM- also matches both conditions. With LIKE, both % symbols match empty fragments. With the regex, the matched fragment occupies the entire string.

km-2024-000777 matches neither of these two conditions. Both patterns contain uppercase K and M, while the string contains lowercase k and m.

That leaves %KM-%. Try to answer before running the query. For LIKE '%KM-%', the actual percent signs inside the value can be matched by the outer % symbols, while KM- in the middle matches literally. The regex KM- also doesn't care that % characters surround its fragment: it will still find what it needs.

SELECT sample,
       sample LIKE '%KM-%' AS like_found,
       sample ~ 'KM-' AS regex_found
FROM (VALUES
  ('Order KM-2024-001234 is ready'),
  ('KM-'),
  ('km-2024-000777'),
  ('%KM-%')
) AS demo(sample);

Uppercase and lowercase letters

The Commandant reviews the results and notices a gap: ticket 3 is missing. It contains km-2024-000777, but the query with ~ 'KM-' didn't select it.

You can see the reason in the very first letter. The pattern expects uppercase K, but the text contains lowercase k. The check fails immediately at that position. The ~ operator is case-sensitive, so K and k are different to it.

The same applies to English letters in general. The pattern cat finds lowercase cat in ticket 3. Later in the same string, there is Cat with an uppercase first letter, and this pattern won't match there.

If case doesn't matter for the task, PostgreSQL provides the ~* operator. Notice the syntax: the asterisk belongs to the SQL operator and sits outside the quotes. The pattern itself can stay ordinary: km-.

The condition body ~* 'km-' matches km-, KM-, Km-, and kM-. Letter case no longer matters. The hyphen is still required and must come after the two letters.

Before running the query, make another prediction. Ticket 3 should now appear. Tickets 1 and 14, which use uppercase KM-, won't disappear: ~* accepts both cases; it doesn't require the letters to be lowercase.

SELECT ticket_id, body
FROM tickets
WHERE body ~* 'km-'
ORDER BY ticket_id;

When you need rows without a match

Sometimes you need the opposite selection: for example, tickets that don't mention an order code at all. In PostgreSQL, you put ! before the tilde for this. The question becomes: “Is there no matching fragment?”

That gives us four operators:

  • ~ — there is a match, case-sensitive;
  • ~* — there is a match, case-insensitive;
  • !~ — there is no match, case-sensitive;
  • !~* — there is no match, case-insensitive.

Let's test them on the string Cat. The expression Cat ~ 'cat' gives false because C and c differ in case. So the opposite check, Cat !~ 'cat', gives true.

With ~*, the result flips: Cat ~* 'cat' returns true, while Cat !~* 'cat' returns false. A match was found, so the claim that there is no match is false.

Now take dog. Neither ~ 'cat' nor ~* 'cat' finds anything there. So both negative checks return true.

Don't think of !~ as an operation on the text itself. It doesn't cut anything out or show you “what remains.” The result of the check is simply true or false for the entire string.

Before the next cell, we'll work through one string completely and leave the second one for you.

For cat, it's simple: ~ 'cat' finds all three letters, so found = true. ~* also gives true. The negative operators return the opposite result, so the last two columns will both be false.

Now take Cat and mentally fill in the four values from left to right. A useful order is this: first decide what ~ and ~* return, then flip each corresponding result for !~ and !~*.

Pay special attention to scatter. It's an ordinary English word, but the engine moves through the characters s-c-a-t-t-e-r, and in the middle it really does contain consecutive c, a, t.

SELECT sample,
       sample ~ 'cat' AS found,
       sample ~* 'cat' AS found_any_case,
       sample !~ 'cat' AS absent,
       sample !~* 'cat' AS absent_any_case
FROM (VALUES ('cat'), ('Cat'), ('scatter'), ('dog')) AS demo(sample);

Marker: show the matched fragment

true answers the query's question, but that's often not enough when you're debugging. Take ticket 12: Why does the home page say "cat cat"? Typo? The condition body ~ 'cat' confirms that there is a match, but it doesn't show which part of the string matched or where it is.

That's why QUERY has a marker. The ready-made expression regexp_replace(body, 'cat', '⟦\&⟧', 'g') leaves the string in place and highlights every matching fragment. The brackets ⟦\&⟧ in the query are the marker template: in the cell output, they turn into a colored background, so you won't see the brackets themselves.

Don't worry about how regexp_replace works yet. The course will cover it in Chapter 4. For now, you only need to change the pattern in the second argument and look at what gets highlighted.

For example, take the fragment cats. The pattern contains exactly c, a, t, so the result is cats. The s stays outside because we never asked the pattern to find it.

On scatter, the marker shows scatter. That output makes the issue obvious. You may have thought of the task as “find the word cat,” but the query actually asks for only three adjacent letters.

Case differences become obvious too. Ticket 3 contains both variants: lowercase cat and uppercase Cat. The marker in the next cell uses the case-sensitive pattern cat, so the first match will be highlighted while the second remains unchanged.

I usually check a new regex with more than just a count of matching rows. Two or three real strings with a marker often reveal immediately that the pattern grabbed an extra character or matched inside a word.

SELECT ticket_id,
       regexp_replace(body, 'cat', '⟦\&⟧', 'g') AS marked
FROM tickets
WHERE body ~ 'cat'
ORDER BY ticket_id;

Now try it without a detailed walkthrough. You have four strings: cat, cats, scatter, Cat. Before running the cell, decide which letters will be highlighted in each one.

In the first, the match occupies the entire string. In the second, one character remains on the right. In the third, one character remains on each side. The last string checks whether you remembered case sensitivity.

If your prediction doesn't match the result, read the pattern literally again. cat contains only three characters. There is no concept of a “word,” no word boundaries, and no guess about meaning in this pattern yet.

SELECT sample,
       regexp_replace(sample, 'cat', '⟦\&⟧', 'g') AS marked
FROM (VALUES ('cat'), ('cats'), ('scatter'), ('Cat')) AS demo(sample);

A match doesn't have to be a word

scatter has already shown a trap that catches almost everyone at first. The pattern cat requires only three adjacent letters: c, a, t. It doesn't care what comes before or after them.

So in cats, we get cats. In scatter, we get scatter. In catering, the match again begins with the first character: catering.

QUERY: I don't see a separate word cat in scatter. I do see the three required letters in a row. The search agrees with me.

In data, this mistake is no longer harmless. A task says “find the word,” someone puts only the letters of that word into the pattern, and mentally adds boundaries around it. PostgreSQL can't see those imaginary boundaries.

We'll learn how to require a separate word in Chapter 3. For now, use a simpler way to check yourself: read the pattern literally and inspect a few real matches with the marker.

The Commandant switches the screen to contacts. Now we need records from Miami. The city column contains Miami, Miami, FL, and miami. This uses both things we've already tested: a regex can find a fragment inside a longer value, and the operator controls case sensitivity.

Check yourself
The city column contains the values “Miami”, “Miami, FL”, and “miami”. What will the condition WHERE city ~ 'Miami' return?

The final task comes without a step-by-step walkthrough. The broken query uses city = 'Miami'. The = operator requires the entire value to match exactly, so Miami, FL is filtered out because of the extra text, while miami also differs in case.

The Commandant needs every Miami record from this export, including both Miami, FL and miami. You've already used the operator you need. It searches for a fragment inside a string and ignores uppercase/lowercase differences.

Practice: solve the tasks
Solved 0 of 2 · any 1 is enough to pass
Find and fix the bug
Right now, = compares the entire value with the text “Miami”. Replace that condition with a regex search so that both “Miami, FL” and “miami” appear in the result. Don't change the rest of the query: you need the same columns and the same sorting.
SELECT contact_id, full_name, city
FROM contacts
WHERE city = 'Miami'
ORDER BY contact_id;

Common mistakes

Bringing % from LIKE into a regex

After LIKE '%KM-%', it's easy to keep typing on autopilot and write body ~ '%KM-%'. But % belongs to the rules of LIKE. In a regular expression, it does not mean “any text around the edges.”

For the string Order KM-2024-001234, today's task only needs body ~ 'KM-'. If you're unsure, put a short string in a separate example and use the marker to see which fragment actually matched. For a normal search for KM- inside a string, percent signs aren't needed.

Forgetting about case

Ticket 3 contains km-2024-000777. Your eye quickly treats KM- and km- as the same prefix, but ~ returns false: the very first uppercase K fails to match lowercase k.

When both cases are allowed, use ~*. For a case-insensitive negative check, use !~*. There's no need to convert the entire column to lowercase just for one condition like this: PostgreSQL already provides an operator for the check you need.

Mistaking part of a word for a whole word

The expression scatter ~ 'cat' returns true. It's natural to object at first: that's not a separate word cat. But the engine sees characters, and inside s-c-a-t-t-e-r, the three pattern letters really do appear consecutively.

The marker makes this obvious: scatter. If the task requires a separate word, the pattern cat alone isn't enough. Boundaries will appear in Chapter 3. Until then, don't add them in your head on PostgreSQL's behalf.

Confusing negation with removing a match

For the string Cat, the expression !~ 'cat' gives true. At first, it's easy to read !~ as “remove the match” or “show everything except the match.” But the operator doesn't modify the text at all. It checks whether a match is absent and returns a Boolean result.

This is especially clear with dog: dog !~ 'cat' is also true, even though there's nothing to cut out of the string. Changing text is a separate operation.

Counting rows instead of matches

In ticket 14, KM- appears three times. The query WHERE body ~ 'KM-' still returns that ticket as a single row. WHERE works with the table row as a whole: it either keeps it or discards it.

So the number of rows in the result tells you nothing about how many matches occurred inside one body. In this lesson, use the marker to inspect cases like this: it highlights every matching fragment, so all three matches will be visible right in the text.

How to check your first pattern

When you start working with your own text column, don't begin with a twenty-character regex. First pull out two or three real strings and write down in words exactly what must appear in the text.

For our prefix, that sounds like this: “uppercase K, immediately followed by uppercase M, then a hyphen.” That description almost turns itself into KM-. Then decide separately how case should work. If uppercase and lowercase letters should count as the same, use ~* in PostgreSQL.

After testing examples that should work, always add an awkward one. In our archive, that's ticket 3 with lowercase km-. For the pattern cat, scatter became that test. One troublesome example often tells you more about a regex than five rows where everything happened to work as intended.

Finally, inspect the match with the marker. Expected a separate cat but got scatter? Then there's no need to search for the problem: PostgreSQL has shown you exactly what rule you wrote.

Key takeaways
  • A regex describes the fragment of text that should match. KM- is read literally: K, then M, then -.
  • LIKE matches its pattern against the whole string, so you usually put % on both sides when searching inside it. The ~ operator finds a suitable position inside the text on its own.
  • ~ is case-sensitive, while ~* is not. The !~ and !~* operators check the opposite condition: that no match exists.
  • The letters in a pattern may appear inside a longer word. That's why cat is found in both cats and scatter.
  • WHERE filters table rows. The marker highlights the matches themselves and makes it easy to spot patterns that matched too much.

The first batch is ready for the Commandant. But the next message is trickier: it contains an address that almost looks like the store's real address. In the next lesson, the pattern gets its first special character. Just one dot—but it can let through much more than you might expect.