The following example returns all rows that contain at least one numerical digit in PostgreSQL.
Example
Suppose we have a table called Products
with the following data in its ProductName
column:
SELECT ProductName
FROM Products;
Result:
productname --------------------------------- Left handed screwdriver Right handed screwdriver Long Weight (blue) Long Weight (green) Straw Dog Box Bottomless Coffee Mugs (4 Pack) Smash 2000 Sledge Hammer Chainsaw (3 spare fingers)
This column contains character data, but some rows contain numbers within that character data (even though they’re not stored as a numeric type).
We can use the following query to return just those rows that contain numbers represented by numerical digits:
SELECT ProductName
FROM Products
WHERE ProductName ~ '[0-9]+';
Result:
productname --------------------------------- Bottomless Coffee Mugs (4 Pack) Smash 2000 Sledge Hammer Chainsaw (3 spare fingers)
As expected, only those rows that contain numbers are returned.
In PostgreSQL, ~
is a case-sensitive operator for matching the given regular expression. For case-insensitive matches, use ~*
.
You can use !~
to return all rows that don’t match the regular expression (and !~*
for case-insensitive matches).