You can use case statements in the order by
clause. Here is the SQL Standard way of doing this:
select *
from songs
where song like '%st%'
order by (case when song like 'st%' then 1 else 0 end) desc,
song
In MySQL, you can just use the expression:
order by (song like 'st%') desc, song
Because a boolean expression evaluates to 0 (false) or 1 (true). The desc
will put the matches first.
By the way, you CANNOT depend on the ordering after a union
or union all
. SQL tables are inherently unordered. SQL results sets are inherently unordered, unless explicitly ordered with an order by
clause (or a group by
clause in MySQL).