Extract leading digits from a string in SQL
Codes like '123-ABC' or '42 Main St' begin with digits you need on their own for sorting or joining.
The task
The house number in '42 Main St' is everything before the first letter. A pattern anchored at the start grabs it.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
SELECT NULLIF(substring(address_line FROM '^[0-9]+'), '')::int AS house_number
FROM addresses;
仕組み
substring with the pattern '^[0-9]+' returns the leading run of digits, or an empty string when there is none. NULLIF turns that empty string into NULL so the cast does not fail and rows without a leading number surface as NULL instead of erroring.
Variations
MySQL 8+
MySQLSELECT CAST(REGEXP_SUBSTR(address_line, '^[0-9]+') AS UNSIGNED) AS house_number
FROM addresses;
SQL Server
SQL ServerSELECT CAST(LEFT(address_line, PATINDEX('%[^0-9]%', address_line + ' ') - 1) AS INT) AS house_number
FROM addresses;
Questions that come up
How does the SQL Server PATINDEX trick work?
PATINDEX finds the first non-digit; appending a space guarantees it always finds one, so subtracting 1 gives the length of the leading digit run. LEFT then takes exactly those digits. With no leading digits LEFT returns '', and CAST('' AS INT) is 0 on SQL Server, not NULL; wrap the LEFT in NULLIF(..., '') if you need NULL.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.