arul
arul

Reputation: 300

Sorting different rows based on multiple conditions

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

Answers (1)

CL.
CL.

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

Related Questions