Is it possible to order result rows by a varchar
column cast to integer
in Postgres 8.3?
相关问题
- Do the Java Integer and Double objects have unnece
- Django distinct is not working
- PostgreSQL: left outer join syntax
- Connecting Python to a Heroku PostgreSQL DB?
- Extracting from a Union Type when some have identi
相关文章
- postgresql 关于使用between and 中是字符串的问题
- postgresql 月份差计算问题
-
What is the difference between
and in java - Using boolean expression in order by clause
- Table valued Parameter Equivalent in Postgresql
- in redshift postgresql can I skip columns with the
- Use savefig in Python with string and iterative in
- How do I get from a type to the TryParse method?
It's absolutely possible.
Be sure to have valid integer literals in your
varchar
column or you get an exception. (Leading and trailing white space is ok - it will be trimmed automatically.)If that's the case, though, then why not convert the column to
integer
to begin with? Smaller, faster, cleaner, simpler.How to avoid exceptions?
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.)\D
is 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
g
is 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 toNULL
withNULLIF
. (You might consider0
instead.)The result is guaranteed to be valid. This procedure is for a cast to
integer
as requested in the body of the question, not fornumeric
as the title mentions.How to make it fast?
One way is an index on an expression. (Link to manual version 8.3.)
Then use the same expression in the
ORDER BY
clause:Test with
EXPLAIN ANALYZE
whether the functional index actually gets used.Also in case you want to order by a text column that has something convertible to float, then this does it: