Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering results by multiple values of same column

Tags:

mysql

I have a query that gets contacts from a database based on their title. It looks for multiple titles and if multiple contacts get returned from the same query, I'd like them to come in a specific order. Here's what I mean:

This is an example of the table:

id   | name      | title              | email
-----+-----------+--------------------+------------------
1    | Bob       | General Manager    | [email protected]
2    | John      | President          | [email protected]
3    | Sue       | Owner              | [email protected]

My query is something like this:

SELECT * FROM tbl_contacts WHERE title IN ('General Manager', 'Owner', 'President')

How can I made the query return the results in a specific order (or hierarchy of titles in my case)?

I'd like the results of always being in the order:

  1. General Manager
  2. Owner
  3. President

If there is no general manager for that entity, for example, I'd like to still keep the same hierarchy and return:

  1. Owner
  2. President
like image 374
eeetee Avatar asked Dec 19 '22 09:12

eeetee


2 Answers

You want to use FIELD function. It returns position of the search string in the set of given strings.

select *
from tbl_contacts
where title in ('General Manager', 'Owner', 'President')
order by field(title, 'General Manager', 'Owner', 'President')
like image 150
Gurwinder Singh Avatar answered Jan 08 '23 04:01

Gurwinder Singh


Set your own order:

SELECT * FROM tbl_contacts 
WHERE title IN ('General Manager', 'Owner', 'President')
ORDER BY CASE
              WHEN title = 'Owner' THEN 0
              WHEN title = 'President' THEN 1
              WHEN title = 'General Manager' THEN 2
          END
like image 42
McNets Avatar answered Jan 08 '23 04:01

McNets