Robbie Robbie - 22 days ago 7
SQL Question

How to combine two SELECT statements

I have two queries I am trying to combine into one. A simplified version of what I am doing:

SELECT * FROM table WHERE `id` = '1' ORDER BY `name`
SELECT * FROM table WHERE `id` = '2' ORDER BY `age`


I have looked into unions but the examples I find online are less than helpful.

Answer

You might be looking for something like this:

SELECT * FROM YourTable 
WHERE id in('1','2') 
ORDER BY id,CASE WHEN id=1 THEN age END,CASE WHEN id=2 THEN name END

As the id is part of the resultset, there is no need for UNION or other complicated tricks.

I'm quite sure, that age and name are not the same type. One single CASE WHEN might get into troubles here.

In my suggestion the ORDER BY uses three columns. This will translate to

ORDER BY 1,age,NULL

or to

ORDER BY 2,NULL,name
Comments