Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 321
404ram Avatar asked Dec 07 '25 10:12

404ram


2 Answers

Yes. If only there were some way to ORDER a SQL result BY something.

like image 89
Jonathan Feinberg Avatar answered Dec 09 '25 23:12

Jonathan Feinberg


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
like image 44
Mark Byers Avatar answered Dec 09 '25 23:12

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!