Sam Arul Raj T
Sam Arul Raj T

Reputation: 1770

Particular Id at First

Actually I have a car table as CAR it has 3 fields:

Car table has 15 records,, I just want to have the 5th record at first rest of the records at any order as DESC, ASC.

My main aim is to have the particular carId at first all other records as DESC or ASC one by one!

I think I am clear to you.

Upvotes: 0

Views: 68

Answers (2)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125204

Although @Mahmoud answer works perfectly, a case in the order by can make it difficult for the engine to optimize the query. You can avoid it like this:

select carid, carname, carprice
from car 
order by carid != 5, carid

In mysql a comparison will return 0 or 1 hence no need to wrap it in a case statement:

mysql> select 1 = 0;
+-------+
| 1 = 0 |
+-------+
|     0 |
+-------+

mysql> select 1 = 1;
+-------+
| 1 = 1 |
+-------+
|     1 |
+-------+

Upvotes: 2

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79909

You can use the CASE expression in the ORDER BY clause something like this:

SELECT carId ,carName,carPrice
FROM Car 
ORDER BY CASE WHEN carId = @th5thid THEN 0 ELSE 1 END, Carid

Upvotes: 3

Related Questions