• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 261
  • Last Modified:

mysql ORDER BY based on IN clause

I want to ORDER my sql query based on the IN clause

select * from acct where acct_num in (200,100,150) order by (200,100,150)

My result is ordered by
I assume because acct_num is an index.

I want my resulting order to be
  • 3
1 Solution
Guy Hengel [angelIII / a3]Billing EngineerCommented:
you then need to write the order by like that:
select * from acct where acct_num in (200,100,150)
 order by case when acct_num = 200 then 0 when acct_num =  100 then 2 else 3 end

Open in new window

pmsguyAuthor Commented:
Is there an easier way to do this query?
The IN list will be dynamic.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
not that I know of.
but if the "IN" list will be dynamic, so can be your order by?
Ovid BurkeConsultant InstructorCommented:
Try this:
SELECT * FROM acct WHERE acct_num IN (200,100,150) ORDER BY FIELD(acct_num,200,100,150);

Open in new window

Guy Hengel [angelIII / a3]Billing EngineerCommented:
actually, that is a good one!
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.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now