Skip to content Skip to sidebar Skip to footer

Mysql Query To Return Results In Specific Order Without Order By

Is it possible to make a mysql query returning values without default order.for example am using the below query select id_product,name from sample where id_product in ('675','123'

Solution 1:

There's always an order. If you do not specify any particular using ORDER BY then rows can be returned in the order they are stored in the database.

Solution 2:

I suggest adding a Sort column in the database to force a custom order. Anyway, you can use a little trick using the FIND_IN_SET function:

SELECT id_product, name
FROM sample
WHERE id_product IN (675,123,745,954)
ORDERBY FIND_IN_SET(id_product, '675,123,745,954')

Demo

Solution 3:

If you want random order : "order by rand()";

Solution 4:

If you would like a random order, you could do this:

SELECT id_product,name FROM sample WHERE id_product IN ('675','123','745','954') 
ORDERBY NEWID()

Solution 5:

You might have defined an ordered index on id_product column of the table. Please check it.

Otherwise, the select will result in the default order of rows insertion.

Refer to: Create Index - MySQL

Post a Comment for "Mysql Query To Return Results In Specific Order Without Order By"