Connecting Tech Pros Worldwide Forums | Help | Site Map

UNION ignores my embedded ORDER clause

Newbie
 
Join Date: Oct 2008
Posts: 1
#1: Oct 28 '08
Hi everybody,
I've got a problem with this SQL-Statement:

Expand|Select|Wrap|Line Numbers
  1. (SELECT * FROM currencies WHERE name = 'EUR') UNION ALL (SELECT * FROM currencies WHERE  name = 'USD')
  2. UNION ALL (SELECT * FROM currencies WHERE name !='EUR' AND name != 'USD' ORDER BY name ASC)
The table "currencies" contains over 100 different currencies and I want get EUR first, then USD and at least the rest of the table in alphabetical order.

But the problem seems to be that the ORDER BY clause in the last SELECT is ignored. The Output is definitly not ordered in any way. I checked this by changing the order-direction to desc.
Am I just to stupid or is this a problem within MySQL ?

Greetz Piecko
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,747
#2: Oct 31 '08

re: UNION ignores my embedded ORDER clause


That's odd. I would have thought that should work.

I came up with an alternative tho.
You can simply add a integer column to your query and give that column a value that you can then sort the results based on. That is; if the name of the currency is 'EUR', then you give it the value 1. If it is 'USD', then you give it the value 2. If it is anything else, you give it the value 3.
Then you can simply have your ORDER BY clause sort the result by the integer column first, and then by then name column.

For example:
Expand|Select|Wrap|Line Numbers
  1. SELECT 
  2.     c.`Name`,
  3.     (CASE c.`Name`
  4.         WHEN 'EUR' THEN 1
  5.         WHEN 'USD' THEN 2
  6.         ELSE 3
  7.     END) AS `DisplayOrder`
  8. FROM `Currency` AS c
  9. ORDER BY `DisplayOrder`, `Name` DESC;
  10.  
Reply