Order the query results in the same order as the IN operator

I have the following request

SELECT * FROM campaigns where campaign_id IN ( 'idStrOne', 'idStrTwo', 'idStrThree' );

      

The results of which are ordered by the primary key of the table campaigns, which is "id". This is not the order I want.

I want the results to return in the same order as the arguments to the IN function. So in this case I want to order

idStrOne, idStrTwo, idStrThree

      

How do I get this order?

-2


a source to share


1 answer


You can try adding a CASE expression to the ORDER BY clause



SELECT * 
FROM campaigns 
WHERE campaign_id IN ( 'idStrOne', 'idStrTwo', 'idStrThree' )
ORDER BY 
(CASE campaign_id WHEN 'idStrOne' THEN 1 WHEN 'idStrTwo' THEN 2 ELSE 3 END);

      

+2


a source







All Articles