Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use SQL to query in order except the first record

Tags:

sql

I have an idea, e.g. I have a table containing name(Ann, Ben, Chris, Tom, John),
I want to query it using sql from letter a first, z last.

But I have a condition that I want to put John in the first record.

like image 947
red23jordan Avatar asked Dec 15 '11 16:12

red23jordan


2 Answers

select name
from names
order by
  case when name = 'John' then 0 else 1 end,
  name
like image 138
GSerg Avatar answered Oct 20 '22 15:10

GSerg


  (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   
like image 34
Johan Avatar answered Oct 20 '22 14:10

Johan