Manikandan
Manikandan

Reputation: 1816

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','745','954').

but it giving the output rows order by id_product. OUTPUT:

id_product,Name
123        ,abc
675        ,xzy
745        ,bsh
954        ,dsh

I want the result should come like this, without default order.

 id_product,Name
 675        ,xzy
123        ,abc    
745        ,bsh
954        ,dsh

any help would be appreciated.

Upvotes: 1

Views: 817

Answers (5)

Salman Arshad
Salman Arshad

Reputation: 272446

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)
ORDER BY FIND_IN_SET(id_product, '675,123,745,954')

Demo

Upvotes: 3

Ravinder Reddy
Ravinder Reddy

Reputation: 24022

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

Upvotes: 0

sdemonti
sdemonti

Reputation: 21

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

Upvotes: 2

ciruvan
ciruvan

Reputation: 5213

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') 
ORDER BY NEWID()

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75645

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.

Upvotes: 5

Related Questions