Extract trailing digits from a string in SQL
Versioned names like 'report-3' and 'report-10' need the trailing number as a real integer for natural ordering.
The task
The version number is the digit run at the end of the name. Anchor the pattern at the end to grab it.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
SELECT NULLIF(substring(doc_name FROM '[0-9]+$'), '')::int AS version_no
FROM documents;
Fonctionnement
The pattern '[0-9]+$' matches digits only at the end of the string. Wrapping in NULLIF keeps rows with no numeric suffix as NULL rather than failing the cast. This is the same key used in the natural-sort recipe, shown here as a plain projection.
Variations
MySQL 8+
MySQLSELECT CAST(REGEXP_SUBSTR(doc_name, '[0-9]+$') AS UNSIGNED) AS version_no
FROM documents;
SQL Server
SQL ServerSELECT CAST(RIGHT(doc_name, PATINDEX('%[^0-9]%', REVERSE(doc_name) + ' ') - 1) AS INT) AS version_no
FROM documents;
Questions that come up
What if digits appear in the middle too?
Only the final run matches: 'v2-fix-10' yields 10, not 210 or 2. If you need all digit groups, split the string with a regex-splitting function instead.
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.