Ordering by the order of values in a SQL IN clause

0 votes

I have 2 queries, one that gets all of the IDs and the second that retrieves all the information. The first creates the order of the IDs which I want the second to order by. The IDs are put in an IN() clause in the correct order.

So it'd be something like:

SELECT id FROM table1 WHERE ... ORDER BY display_order, name

SELECT name, description, ... WHERE id IN ([id's from first])

the second query does not return the results in the same order that the IDs are put into the IN() clause.

One solution I have found is to put all of the IDs into a temp table with an auto incrementing field which is then joined into the second query

I am using MySQL.

Jun 6 in Others by polo
• 1,500 points
30 views

1 answer to this question.

0 votes

Use MySQL FIND_IN_SET function:

  SELECT * 
    FROM table_name 
   WHERE id IN (..,..,..,..) 
ORDER BY FIND_IN_SET (coloumn_name, .., .., ..);
answered Jun 6 by nisha
• 2,180 points

Related Questions In Others

0 votes
1 answer
0 votes
1 answer

Change the permission for a file created by me in linux

If you are the system administrator or ...READ MORE

answered Mar 8, 2019 in Others by Nabarupa
340 views
0 votes
1 answer

How to retrieve the value of a text field in Flutter App?

Hi@akhtar, In your TextField, you can call one ...READ MORE

answered Sep 3, 2020 in Others by MD
• 95,360 points
817 views
0 votes
2 answers

How to get the URL of the current tab in Google Chrome?

Its so simple.... If you want to ...READ MORE

answered Aug 12, 2020 in Others by Steve
• 200 points
814 views
0 votes
1 answer

Ordering by the order of values in a SQL IN() clause

Use MySQL's FIELD() function: SELECT name, description, ... FROM ... WHERE id ...READ MORE

answered Feb 4 in Database by Neha
• 8,740 points
669 views
0 votes
1 answer

Ordering by the order of values in a SQL IN() clause

We can use expressions as well in ...READ MORE

answered May 31 in Others by Sohail
• 2,960 points
28 views
0 votes
1 answer
0 votes
1 answer

How to change the default value and to alter a column in sql?

Hi, You can try this: ALTER TABLE foobar_data CHANGE ...READ MORE

answered Jun 24, 2019 in Big Data Hadoop by Gitika
• 65,870 points
391 views
0 votes
1 answer

Does Java have a "IN" operator or function like SQL?

You can use java.util.Collection.contains() for collections.  If a non-null ...READ MORE

answered May 31 in Others by nisha
• 2,180 points
24 views
0 votes
1 answer

How to generate the "create table" sql statement for an existing table in postgreSQL

Create a table for a demo: CREATE TABLE ...READ MORE

answered Jun 20 in Others by nisha
• 2,180 points
19 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP