Reputation: 300
I have a contacts table having two columns priority and name. Consider I have some 500 entries. I need to sort by following conditions
Can this be possible in a single query.
Upvotes: 0
Views: 63
Reputation: 180070
You can combine multiple queries with UNION. Additional subqueries are needed to be able to user ORDER BY/LIMIT (otherwise, ORDER BY would apply to the entire result of the UNION). The LIMIT 20 subquery must be repeated to exclude the top 20 rows from the second query:
SELECT *
FROM (SELECT *
FROM Contacts
ORDER BY priority DESC
LIMIT 20)
UNION ALL
SELECT *
FROM (SELECT *
FROM Contacts
WHERE ID NOT IN (SELECT ID
FROM Contacts
ORDER BY priority DESC
LIMIT 20)
ORDER BY name)
Upvotes: 1