Sort Varchar data values

Hi,
I need data sorted in this order: MVA, BO, RST  

SQL> CREATE TABLE t1
(col1 varchar2(10));
INSERT INTO t1 VALUES('MVA');
INSERT INTO t1 VALUES('BO');
INSERT INTO t1 VALUES('RST');
What is the best approach?

Thanks in advance.
LVL 11
mohammadzahidAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Pawan KumarDatabase ExpertCommented:
Please try like this -

SELECT * FROM t1
ORDER BY CASE WHEN col1 = 'mva' THEN 1
 WHEN col1 = 'bo' THEN 2
 WHEN col1 = 'rst' THEN 3
END 

Open in new window

0
Pawan KumarDatabase ExpertCommented:
For performance reasons, and ease of use and maintenance, create a table that specifies the sort order.  
I've done it inline below, but if this is a common report, you'd probably want to create a permanent table to store the sort order:

DATA GENERATOR AND CREATE TABLE
CREATE TABLE t1
(
  col1 varchar2(10)
);

INSERT INTO t1 VALUES('RST');
INSERT INTO t1 VALUES('MVA');
INSERT INTO t1 VALUES('BO');

Open in new window


select t1.col1 
from t1 
inner join 
(
    select 'MVA' as col, 1 as sort_order from dual
    union all
    select 'BO', 2 from dual
    union all
    select 'RST', 3 from dual
) sortingOrder on sortingOrder.col = t1.col1
order by sortingOrder.sort_order;

Open in new window


OUTPUT
| COL1 |
|------|
|  MVA |
|   BO |
|  RST |
        

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sdstuberCommented:
If this is a common sorting criteria you may want to put the logic in a function for reusability and then, if necessary, create indexes on the function result.

You could then create a view or a virtual column on the view as needed.  Which is "best" would depend on your use cases.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Oracle Database

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.