Is it possible to order result rows by a varchar column cast to integer in Postgres 8.3?
Is it possible to order result rows by a varchar column cast to integer
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s absolutely possible.
Be sure to have valid integer literals in your
varcharcolumn for each entry or you get an exceptioninvalid input syntax for integer. Leading and trailing white space is ok – that’s trimmed automatically.If that’s the case, though, then why not convert the column to
integerto begin with? Smaller, faster, cleaner, simpler.How to avoid exceptions?
Postgres 16 or newer
If the input might not be valid integer literals, use the dedicated function
pg_input_is_valid()to test without raising an exception:SQL
CASEdefaults tonullin the absence ofELSE– which sorts last in default ascending order. See:The new built-in function is faster and more reliable than below manual solution. Also different in that it does not try to fix broken input.
Postgres 15 or older
To remove non-digit characters before the cast and thereby avoid possible exceptions:
The
regexp_replace()expression effectively removes all non-digits, so only digits remain or an empty string. (See below.)\Dis shorthand for the character class[^[:digit:]], meaning all non-digits ([^0-9]).In old Postgres versions with the outdated setting
standard_conforming_strings = off, you have to use Posix escape string syntaxE'\\D'to escape the backslash\. This was default in Postgres 8.3, so you’ll need that for your outdated version.The 4th parameter
gis for "globally", instructing to replace all occurrences, not just the first.You may want to allow a leading dash (
-) for negative numbers.If the the string has no digits at all, the result is an empty string which is not valid for a cast to
integer. Convert empty strings toNULLwithNULLIF. (You might consider0instead.)The result is guaranteed to be valid. This procedure is for a cast to
integeras requested in the body of the question, not fornumericas the title mentions.How to make it fast?
One way is an index on an expression.
Then use the same expression in the
ORDER BYclause:Test with
EXPLAIN ANALYZEwhether the functional index actually gets used.