Skip to content

Instantly share code, notes, and snippets.

@veob
Last active April 25, 2023 07:18
  • Star 15 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save veob/7378ad925cc962d34de3 to your computer and use it in GitHub Desktop.
PostgreSQL natural sort
//sql
create or replace function naturalsort(text)
returns bytea language sql immutable strict as
$f$ select string_agg(convert_to(coalesce(r[2],length(length(r[1])::text) || length(r[1])::text || r[1]),'SQL_ASCII'),'\x00')
from regexp_matches($1, '0*([0-9]+)|([^0-9]+)', 'g') r; $f$;
//author: github.com/RhodiumToad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment