Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL regexp_like: A Practical How-To

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL does not have a built-in regexp_like function. To check whether a string matches a regular expression, use the ~ operator (case-sensitive) or ~* (case-insensitive), or the regexp_match() function when you need the matched text. The ~ operator returns a boolean and is the direct equivalent of Oracle's REGEXP_LIKE. This guide shows how to use it, how to write patterns safely, and what to do when results surprise you.

What You'll Need

  • A PostgreSQL database (version 9.0 or later; the ~ operator has existed for much longer, but modern versions are recommended).
  • A client to run SQL: psql, pgAdmin, DBeaver, or any tool that connects to PostgreSQL.
  • Basic familiarity with SQL SELECT and WHERE clauses.
  • Optional: a table with text data to test against. You can also test with literal strings, as shown below.

Step-by-Step

  1. Confirm your PostgreSQL version. Run SELECT version(); in your SQL client. The ~ operator works in all supported versions, but knowing your version helps when reading documentation. Menu labels in GUI clients can differ slightly by version, device, or region.
  2. Test a basic match with the ~ operator. Execute:
    SELECT 'hello world' ~ 'world';
    This returns true. The left side is the string, the right side is the regular expression. The operator returns a boolean, exactly like regexp_like in other databases.
  3. Use case-insensitive matching with ~*. Run:
    SELECT 'Hello World' ~* 'hello';
    This returns true. Use ~ when case matters and ~* when it does not.
  4. Anchor your pattern when you need an exact match. The pattern 'cat' matches any string containing "cat", including "concatenate". To match only the whole string, use ^ and $:
    SELECT 'cat' ~ '^cat$';
    This returns true, while SELECT 'concatenate' ~ '^cat$'; returns false.
  5. Apply it in a WHERE clause. Assuming a table users with a column email, run:
    SELECT * FROM users WHERE email ~ '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$';
    This filters rows whose email matches the pattern. Note the double backslash before the dot: in a standard SQL string, a single backslash is an escape character, so you write \\. to pass a literal \. to the regex engine. Alternatively, use a dollar-quoted string: $regex$\.[a-z]{2,}$regex$.
  6. Use regexp_match() when you need the matched text. The operator only tells you true or false. To extract the match, run:
    SELECT regexp_match('order 12345', '\d+');
    This returns an array like {12345}. If there is no match, it returns NULL.
  7. Use regexp_replace() for substitution. To replace matched text, run:
    SELECT regexp_replace('abc123', '\d+', '#');
    This returns abc#. This is useful for cleaning data before matching.
  8. Test with EXPLAIN on large tables. Regex conditions are not indexable by default. If performance matters, consider a trigram index (pg_trgm extension) or a functional index on a simplified expression. Run EXPLAIN SELECT ... to see whether PostgreSQL uses a sequential scan.
  9. Handle NULLs explicitly. If the column is NULL, NULL ~ 'pattern' returns NULL, not false. In a WHERE clause, NULL rows are excluded, which is usually what you want, but be aware when counting or using NOT.

Common Mistakes

  • Expecting a regexp_like function. PostgreSQL does not provide one. Use ~ or ~*. If you are porting SQL from Oracle, replace REGEXP_LIKE(col, pat) with col ~ pat.
  • Forgetting to escape backslashes. In standard SQL strings, \d becomes d unless you write \\d. Use dollar-quoted strings ($regex$...$regex$) to avoid double escaping.
  • Assuming ~ is anchored. It matches anywhere in the string. Add ^ and $ for full-string matching.
  • Using LIKE wildcards inside a regex. In regex, % and _ are literal characters, not wildcards. Use .* and . instead.
  • Ignoring case sensitivity. ~ is case-sensitive; ~* is not. Pick deliberately.
  • Assuming regex uses indexes. Plain ~ conditions usually force a sequential scan. Plan for performance on large tables.

Tips

  • Use SIMILAR TO only if you need SQL-standard pattern matching; for real regular expressions, stick with ~.
  • Test patterns interactively with SELECT 'sample' ~ 'pattern'; before putting them in a query.
  • Prefer regexp_match() over substring() when you need the matched substring; it is clearer and returns an array.
  • Use the pg_trgm extension and a GIN or GiST index if you need faster pattern searches on large text columns.
  • Keep patterns simple. Complex regexes are hard to read and can be slow; break them into smaller checks where possible.
  • Remember that PostgreSQL regexes are POSIX-style, not PCRE. Some PCRE features (like lookbehind) are not supported.

Troubleshooting

  • Query returns no rows unexpectedly. Check case sensitivity: try ~* instead of ~. Check anchoring: add ^ and $ if you meant an exact match. Check escaping: print the pattern with SELECT 'pattern'; to see what the database actually receives.
  • Syntax error near ~. Ensure the operator is between two string expressions, not used as a function call. For example, regexp_like(col, 'x') is invalid; use col ~ 'x'.
  • Pattern works in another tool but not in PostgreSQL. PostgreSQL uses POSIX regular expressions. Features like \p{L} or lookahead may not be supported. Simplify the pattern or use regexp_replace() in steps.
  • Performance is slow. Run EXPLAIN ANALYZE to confirm a sequential scan. Consider a trigram index or rewriting the condition to use LIKE with a prefix if possible.
  • NULL results confuse you. Remember that NULL ~ 'x' is NULL. Use COALESCE(col, '') ~ 'x' if you want NULL treated as an empty string.
  • If that did not work, check the PostgreSQL documentation for your version's regular expression syntax, and test the pattern against a literal string first to isolate whether the issue is the pattern or the data.

Frequently Asked Questions

Is there a regexp_like function in PostgreSQL?

No. PostgreSQL uses the ~ and ~* operators for boolean regex matching. There is no built-in function named regexp_like.

How do I do a case-insensitive regex match?

Use the ~* operator, for example SELECT 'Hello' ~* 'hello'; returns true. The ~ operator is case-sensitive.

Can I use regex in a WHERE clause?

Yes. Write WHERE column ~ 'pattern'. This filters rows where the pattern matches anywhere in the column value. Add anchors for exact matches.

How do I extract the matched text instead of just true/false?

Use regexp_match(), which returns an array of captured groups, or substring() with a regex pattern. For example, SELECT regexp_match('abc123', '\d+'); returns {123}.

Why does my pattern with backslashes fail?

In standard SQL strings, backslashes are escape characters. Double them (\\d) or use dollar-quoted strings ($regex$\d$regex$) to pass a single backslash to the regex engine.

Does ~ use indexes?

Not directly. Regex conditions typically cause a sequential scan. For large tables, consider a trigram index using the pg_trgm extension or a functional index on a simplified expression.