I have records like
A5
A4
Z1
B2
C7
C1A
C11A
B1
B4
I want them to be sorted in this manner
A4
A5
B1
B2
B4
C1
C11A
C7
Z1
using the ORDER BY
clause.
I want them to be sorted by alphabets and then by numeric values.
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It only takes a minute to sign up.
Sign up to join this communityI have records like
A5
A4
Z1
B2
C7
C1A
C11A
B1
B4
I want them to be sorted in this manner
A4
A5
B1
B2
B4
C1
C11A
C7
Z1
using the ORDER BY
clause.
I want them to be sorted by alphabets and then by numeric values.
For your request:
sorted by alphabets and then by numeric values
I assume (deriving from your sample data) you want to ORDER BY
:
The first letter, treated as text
.
The first number (consecutive digits), treated as integer
.
The whole string to break remaining ties, treated as text
. May or may not be needed.
SELECT *
FROM tbl
ORDER BY left(col, 1) -- 1st letter as text
, substring(fest, '\d+')::int NULLS FIRST -- first number in string as int
, col -- whole columns as cheap tiebreaker
More details:
substring(text,text)
an undocumented variant of substring(string from pattern)
?
Mar 5, 2015 at 14:08
EXPLAIN VERBOSE SELECT substring(col FROM 'FROM') AS s1, substring(col, 'COMMA') AS s2 FROM (SELECT 'foo'::text) t(col);
Mar 5, 2015 at 20:50