Is there a way to keep the order when using SELECT WHERE IN()? For example, using the following query:
SELECT id FROM data_table WHERE id IN(56,55,54,1,7);
The results will come back using the default order by id. 1,7,54,55,56
When I want to keep the order used in the IN: 56,55,54,1,7
Is there a quick way to do this in MySQL or will I be forced to order it after in code?
You can use the WHERE clause with or without the ORDER BY statement. You can filter records by finite values, comparison values or with sub-SELECT statements.
WHERE clause Syntax. The basic syntax for the WHERE clause when used in a MySQL SELECT WHERE statement is as follows. “WHERE” is the keyword that restricts our select query result set and “condition” is the filter to be applied on the results. The filter could be a range, single value or sub query.
The ORDER BY clause is used to get the sorted records on one or more columns in ascending or descending order. The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query.
ORDER BY is always put at the very end of the query.Clauses like FROM , WHERE , GROUP BY , HAVING , etc. should be put before the ORDER BY keyword. To sort the output in ascending order, you may put the keyword ASC after the column name.
Use FIND_IN_SET:
ORDER BY FIND_IN_SET(id, '56,55,54,1,7')
You can also use FIELD:
ORDER BY FIELD(id, '56,55,54,1,7')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With