Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust SQL Query to force a record to appear first?

How can the below query be adjusted to return always the member with MemberID = 'xxx' as the first row

SELECT * FROM Members

like image 549
SShebly Avatar asked Feb 20 '12 20:02

SShebly


2 Answers

select * from Members
order by case when MemberID = XXX then 0 else 1 end
like image 78
Magnus Avatar answered Nov 04 '22 18:11

Magnus


This should work and it will also allow you to order the remaining items by MemberID (Assuming xxx=12 in this example)

SELECT *
FROM Members
ORDER BY CASE WHEN MemberID=12 THEN NULL ELSE isnull(MemberID,0) END

If the memberID column can't contain nulls, you can get away with this which might perform slightly better.

SELECT *
FROM Members
ORDER BY CASE WHEN MemberID=12 THEN NULL ELSE MemberID END
like image 36
JohnFx Avatar answered Nov 04 '22 18:11

JohnFx