Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of "WHERE field IN" SQL query?

I am using the following SQL to select records from MySQL database:

SELECT * FROM cms_product WHERE id IN (3,22,1);

The results order equals "ORDER BY id ASC", so as in example records 1,3,22 are returned. How can I get them ordered in the exact way as typed in IN clause? So ordered as 3,22,1 ? Thank you.

like image 276
Surla Avatar asked Oct 24 '10 23:10

Surla


People also ask

How do I query a specific row in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

How do you find the nth record in SQL?

ROW_NUMBER (Window Function) ROW_NUMBER (Window Function) is a standard way of selecting the nth row of a table. It is supported by all the major databases like MySQL, SQL Server, Oracle, PostgreSQL, SQLite, etc.

How do I select the second row in SQL?

For SQL Server, a generic way to go by row number is as such: SET ROWCOUNT @row --@row = the row number you wish to work on.


1 Answers

Numerous options -

CASE:

Preferred, being ANSI-92 it's portable to other databases.

  SELECT * 
    FROM cms_product 
   WHERE id IN (3,22,1)
ORDER BY CASE id
           WHEN 3 THEN 1
           WHEN 22 THEN 2
           WHEN 1 THEN 3
         END

FIND_IN_SET:

  SELECT * 
    FROM cms_product 
   WHERE id IN (3,22,1)
ORDER BY FIND_IN_SET(id, '3,22,1');

FIELD:

  SELECT * 
    FROM cms_product 
   WHERE id IN (3,22,1)
ORDER BY FIELD(id, 3, 22, 1);

Reference:

  • CASE
  • FIELD
  • FIND_IN_SET
like image 135
OMG Ponies Avatar answered Sep 19 '22 02:09

OMG Ponies