Query to retrieve records by aplhabetic order, except for n predefined items which must be on top
Posted
by
Ashraf Bashir
on Stack Overflow
See other posts from Stack Overflow
or by Ashraf Bashir
Published on 2014-08-18T15:58:11Z
Indexed on
2014/08/18
16:22 UTC
Read the original article
Hit count: 261
I need to retrieve all records ordered alphabetically. Except for a predefined list of record's columns which their records should appear first in a given predefined order, then all other records should be sorted alphabetically based on the same column
For instance, assume we have the following table which is called Names
Lets assume the predefined list is ("Mathew", "Ashraf", "Jack")
.
I.e. these are the names of whom their records should be listed first as in the predefined order.
So the desired query result should be:
Which query could retrieve this custom order ?
P.S, I'm using MySQL.
Here's my trial based on comments' request:
(SELECT * FROM Names WHERE Name in ('Mathew', 'Ashraf', 'Jack'))
UNION
(SELECT * FROM Names WHERE Name NOT IN ('Mathew', 'Ashraf', 'Jack') ORDER BY Name ASC);
the first query result wasn't ordered as required.
© Stack Overflow or respective owner