Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY clause to sort values in an explicit order in CodeIgniter

I have the following query:

select `state` from `table1` 
where `state` in ('NC','North Carolina','TN','Tennessee','CO','Colorado','NM','New Mexico','UT','Utah')
limit 200 offset 0

I need the results ordered by state as they appear in my where clause (i.e. first NC, then TN, then CO, and so on).

How can I do this? I tried using order by but it doesn't give this result.

like image 447
Vamsi Avatar asked Dec 10 '25 13:12

Vamsi


1 Answers

you can use ORDER BY FIELD

SELECT `state`
FROM `table1`
WHERE `state` IN ('NC','North Carolina','TN','Tennessee','CO','Colorado','NM','New Mexico','UT','Utah')
ORDER BY FIELD(`state`, 'NC','North Carolina','TN','Tennessee','CO','Colorado','NM','New Mexico','UT','Utah');
  • SQLFiddle Demo
like image 150
John Woo Avatar answered Dec 12 '25 03:12

John Woo



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!