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.
select name
from names
order 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With