Question

I have a song database and need to implement a search.

I want to produce a list of results where the head of the list is the result of

like 'st%'

and the rest is the result of

like '%st%'

If I use UNION it will correctly produce a list with no duplicates, but not in the order I am wanting.

If I use UNION ALL, it will produce the list in the order I want, but having duplicates.

Am I able to use this sort of query, or will I need to do it another way ?

Was it helpful?

Solution

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).

OTHER TIPS

You can perform a query to search the database for likenesses of those elements and assign them to variables from that point you can sort them with the appropriate code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top