// SQL snippet

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.

Main statement
PostgreSQL
다음도 지원
SQL Server MySQL

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.

PostgreSQL
SELECT NULLIF(substring(doc_name FROM '[0-9]+$'), '')::int AS version_no
FROM documents;

작동 방식

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+

MySQL
SELECT CAST(REGEXP_SUBSTR(doc_name, '[0-9]+$') AS UNSIGNED) AS version_no
FROM documents;

SQL Server

SQL Server
SELECT 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

// snippets are better with a schema brain

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.