Explain Codes LogoExplain Codes Logo

How to detect if a string contains at least a number?

sql
pattern-matching
sql-server
postgresql
Nikita BarsukovbyNikita Barsukov·Dec 17, 2024
TLDR

Get all rows from your table where a specified column contains at least one digit using LIKE '%[0-9]%':

SELECT * FROM table WHERE column LIKE '%[0-9]%';

This SQL Server-compatible syntax will fetch any rows where column contains digits. It's simple yet effective.

Dive deeper: Other techniques and considerations

The LIKE statement is just the tip of the iceberg when it comes to pattern matching strings. Let's take a look under the surface.

Position of first number: Using PATINDEX

SQL Server's PATINDEX function provides the starting position of the first numeric character:

-- Where is Waldo... I mean, our first digit? SELECT PATINDEX('%[0-9]%', column) AS Position FROM table;

If you're looking to confirm a digit's existence before proceeding, use a condition to check for a PATINDEX result > (greater than) 0:

-- Does Waldo exist in this crowd? SELECT * FROM table WHERE PATINDEX('%[0-9]%', column) > 0;

Handling of special characters and multi-digit strings

Data can come with special characters or multiple continuous digits. Capturing these in your pattern search is crucial. When handling multiple digits, try a search like:

-- I've got 99 problems, but a digit ain't one SELECT * FROM table WHERE column LIKE '%[0-9][0-9]%';

This covers you for strings like "a123" and "a1b2"!

Pattern matching in PostgreSQL and SQL Server: SIMILAR TO

The love for pattern matching isn't exclusive to SQL Server, PostgreSQL also has its crush on SIMILAR TO:

-- SQL Server SELECT * FROM table WHERE column LIKE '%[0-9]%'; -- PostgreSQL SELECT * FROM table WHERE column SIMILAR TO '%[0-9]%';

This serves you well in keeping your SQL code cross-comparable.

Advanced pattern matching: CLR-based UDFs

Looking to match complex patterns? SQL Server supports CLR-based UDFs to create .NET regexes. An overkill for this scenario, but knowledge is power!

Taming various SQL flavors

Pattern matching can be slightly different across SQL variants:

  • MySQL

    Commands its loyal servant REGEXP:

    -- MySQL asking REGEXP for a secret dance SELECT * FROM table WHERE column REGEXP '[0-9]';
  • PostgreSQL

    Prefers POSIX style:

    -- PostgreSQL's POSIX secret handshake SELECT * FROM table WHERE column ~ '[0-9]';

Spotting pitfalls on the journey

Be wary of these potential pitfalls:

  • False Positives: Escape characters can confuse your pattern matcher. Tread lightly!
  • Performance Dragons: Large datasets can slow down text pattern indexing. Consider full-text indexing if the dragon roars.
  • Localization Curses: Global datasets might use different numeral systems, adjust your patterns as needed.