Sort by where order

136 views Asked by At

I have query with a where clause like

SELECT 
    name
FROM
   adresses
WHERE
   (name ='Peter' AND
   surname = 'Miller') OR
   emailadress1 = '[email protected]' OR
   emailadress2 = '[email protected]'

Example Table

name    surname     emailadress1    emailadress2    
------------------------------------------------
Michael             [email protected]
Jim                                 [email protected]
Peter   Miller              

Resulting in:

Michael
Jim
Peter

Now it seams that the records are sorted as the come in, just like the sort order of the example table above.

But I want to get them in a list where they folow by the where clause order itself. Like

name & surname = sortorder 1 
emailadress1   = sortorder 2
emailsadress2  = sortorder 3

Example

Peter   
Michael
Jim
3

There are 3 answers

1
Whodiopolis On

If you are looking to sort them by reverse alphabetical then you would add ORDER BY name DESC to the end of your query.

If you are looking to sort your results by specific people then you would have to add some sort of identifier or ranking to them and then sort by that.

2
Gordon Linoff On

You an use a case statement:

order by (case when (name ='Peter' AND surname = 'Miller') then 1
               when emailadress1 = '[email protected]' then 2
               when emailadress2 = '[email protected]' then 3
               else 4
          end)
1
NickUpson On

Add

order by name, surname, emailadress1, emailadress2

to the query.