Natural sort strings with numbers in SQL
Alphabetical order puts item10 before item2. Extract the text prefix and numeric suffix to sort properly.
The task
Rows named file1, file2 ... file10 sort as file1, file10, file2 alphabetically. Sorting by the text prefix plus the number fixes it.
The snippet
Written for PostgreSQL. Versions for MySQL are under Variations.
SELECT file_name
FROM attachments
ORDER BY regexp_replace(file_name, '[0-9]+$', ''),
NULLIF(substring(file_name FROM '[0-9]+$'), '')::int,
file_name;
工作原理
The first key is the name with its numeric tail removed, so file10 groups with file. The second key casts that tail to an integer so 2 sorts before 10. The final file_name breaks ties deterministically. NULLIF handles names with no digits, which would otherwise fail the cast.
Variations
MySQL (heuristic for same-prefix names)
MySQLSELECT file_name
FROM attachments
ORDER BY LENGTH(file_name), file_name;
Questions that come up
Why does ORDER BY LENGTH(name), name work?
When all names share a prefix, a longer string has a bigger number, so sorting by length first and text second approximates numeric order. It breaks on mixed prefixes: 'zz1' sorts before 'a10' because it is shorter. The PostgreSQL key-splitting version handles those; MySQL 8 can copy it with REGEXP_REPLACE and REGEXP_SUBSTR.
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.