sql - Oracle - Sorting a VARCHAR2 field like a NUMBER - I found a solution, need explanation on it -
i have varchar2 column want sort numerically. 99% (or possibly 100%) of time contain numbers. looking around , found this solution. quoting source:
remember our goal sort supplier_id field in ascending order (based on numeric value). this, try using lpad function.
for example,
select * supplier order lpad(supplier_id, 10);
this sql pads front of supplier_id field spaces 10 characters. now, results should sorted numerically in ascending order.
i've played around little bit solution , seems workign (so far), how work, can explain?
when sorting strings/varchar, field serted left right, sort normal words.
that why have problems when sorting
1 2 3 10 11 20
which sorted as
1 10 11 2 20 3
but, if pad values left, have like
001 002 003 010 011 020
which sort correctly
Comments
Post a Comment