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:
If there is no general manager for that entity, for example, I'd like to still keep the same hierarchy and return:
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With