Reputation: 686
I am having this query for a photo contest:
SELECT * FROM `users` ORDER BY entry_id DESC
The result gives 10 records with entry_id 10, 9, 8, 7, ......1
What can I do to pick a specific entry on the top? As there is a requirement if there is a refer ID, entry show first.
So the expected result should be: 4,10,9,8,7,6,5,3,2,1 if 4 if a refer ID.
Upvotes: 1
Views: 489
Reputation: 29051
Try this:
SELECT *
FROM `users`
ORDER BY (CASE WHEN entry_id = 4 THEN 0 ELSE 1 END), entry_id DESC;
Upvotes: 4
Reputation: 2379
for more Dynamic Approach create table value Function
create function OrderData(@a int)
returns @t table ( id int)
as
begin
insert into @t
SELECT *
FROM ab
ORDER BY (CASE WHEN id = @a THEN 0 ELSE 1 END), id DESC
return;
end;
select * from dbo.abc(4)
output 4,10,9,8,7,6,5,3,2,1
select * from dbo.abc(5)
output 5,10,9,8,7,6,4,3,2,1
Upvotes: 0