Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by Specific id first then By rest

Consider a Sample Table with two Column RoleId and User Name

Role | Name
  1      AB
  3      A
  1      ABC
  2      D
  2      B
  3      Abb
  1      E
  4      TE

How can i use SQL queries to get following Output.

Role | Name
  3      A
  3      Abb
  1      AB
  1      ABC
  1      E
  2      B
  2      D
  4      TE

I just want to Order by Role Id 3 first then by remaining Roleid. Currently i am using Union to achieve so //

SELECT * FROM (SELECT * From @temp 
         Where roleid=3
UNION ALL
SELECT * From @temp 
         Where roleid != 3
 ) as X 
like image 531
Shekhar Pankaj Avatar asked Jan 05 '16 15:01

Shekhar Pankaj


People also ask

How do you SELECT ORDER BY specific ids?

The order by the statement is used in SQL to sort the result set in ascending or descending by mentioning it in the suffix as DESC (for descending) and for ASC(for ascending).

Which comes first ORDER BY or GROUP BY?

The GROUP BY clause is placed before the ORDER BY clause.

Does ORDER BY or limit come first?

Yes, it's after the ORDER BY.

Is ORDER BY ASC or DESC by default?

You can use the ASC and DESC keywords to specify ascending (smallest value first) or descending (largest value first) order. The default order is ascending.


2 Answers

You can use case to make more complex ordering:

select *
 from @temp
 order by case when Role = 3 then 0 else 1 end, Role, Name
like image 65
James Z Avatar answered Sep 20 '22 20:09

James Z


select *
from @temp
order by CASE WHEN Role = 3 THEN 0 ELSE Role END, Name
like image 37
strickt01 Avatar answered Sep 23 '22 20:09

strickt01