Use SQL to query in order except the first record Use SQL to query in order except the first record sql sql

Use SQL to query in order except the first record


select namefrom namesorder by  case when name = 'John' then 0 else 1 end,  name


  (SELECT * FROM atable WHERE username = 'John')UNION ALL  (SELECT * FROM atable WHERE username <> 'John' ORDER BY username)

Or more general:

  (SELECT * FROM atable ORDER BY username DESC LIMIT 1)UNION ALL  (SELECT * FROM atable WHERE id NOT IN (     SELECT id FROM atable ORDER BY username DESC LIMIT 1)   ORDER BY username)

If you have to avoid the union for some reason, this slower code will also work:

SELECT * FROM atable ORDER BY    CASE WHEN id IN (SELECT id FROM atable ORDER BY username DESC LIMIT 1)   THEN 0 ELSE 1 END  , username

In SQL-server the syntax is slightly different, the subquery is:

SELECT TOP 1 id FROM atable ORDER BY username DESC   


It is simple:

(SELECT NameFROM UsersWHERE Name = 'John')UNION ALL(SELECT *FROM UsersWHERE Name <> 'John'ORDER BY Name)