404ram 404ram - 6 months ago 9
SQL Question

Customised Ordering in SQL

I have a SQL query like

SELECT column1,column2
FROM table1
WHERE column1 IN('q1','q2','q3')


The results are shown in the order:

q1
q2
q3


If I change the query to

SELECT column1,column2
FROM table1
WHERE column1 IN('q3','q1','q2')


Still the order remains same.

How to achieve this ordering in the sql statement?

Help!!

Thanks

Answer

One way to solve this is to add an extra column in your table called for example 'SortOrder' that contains integers determining in which order the rows should be returned. For example, you can set SortOrder to 1 for q3, 2 for q1 and 3 for q2. The you can use the following SELECT statement to return the rows in the order you need:

SELECT column1,column2 
FROM table1 
WHERE column1 IN('q3','q1','q2')
ORDER BY SortOrder