Question

I have a table "users" having data like

id   firstname  lastname
1    NULL       NULL
2    NULL       NULL
3    Tim        Kanter
4    John       Mathews
5    Brady      Allen

I need to get the records order by firstname but non null records should come first in ascending order. Therefore, How can i get the output like

id   firstname  lastname
5    Brady      Allen
4    John       Mathews
3    Tim        Kanter
1    NULL       NULL
2    NULL       NULL
Was it helpful?

Solution

Try this:

SELECT * FROM TableName 
ORDER BY CASE WHEN firstname IS NULL THEN 1 ELSE 0 END, firstname

Result:

ID  FIRSTNAME   LASTNAME
5   Brady       Allen
4   John        Mathews
3   Tim         Kanter
1   (null)      (null)
2   (null)      (null)

See result in SQL Fiddle.

OTHER TIPS

You can do it using UNION:

  SELECT * FROM (SELECT * FROM table WHERE firstname IS NOT null
  ORDER BY firstname) AS `t1`
  UNION
  SELECT * FROM table WHERE firstname IS  null      
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top