Skip to content

Instantly share code, notes, and snippets.

@falsecz
Created June 28, 2011 08:48
Show Gist options
  • Save falsecz/1050760 to your computer and use it in GitHub Desktop.
Save falsecz/1050760 to your computer and use it in GitHub Desktop.
Order by numbers first cs_CZ
CREATE OR REPLACE FUNCTION order_numbers_first(string character varying)
RETURNS character varying AS
$BODY$
DECLARE new_string character varying;
c character varying;
i integer;
BEGIN
i := 0;
new_string := '';
LOOP
i := i + 1;
c := substr(string, i, 1);
IF NOT c > '0' THEN
c := '9' || c;
END IF;
new_string = new_string || c;
EXIT WHEN i >= char_length(string);
END LOOP;
RETURN new_string;
END;$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
SELECT * FROM
(SELECT regexp_split_to_table('a1a aa1 1aa', E'\\s+') AS name) AS tab
ORDER BY order_numbers_first(name);
/*
order by order_numbers_first(name) order by name
=================================== =============
"1aa" "aa1"
"a1a" "a1a"
"aa1" "1aa"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment