Incorrect usage of UNION and ORDER BY

by Carey on October 7, 2010

Post image for Incorrect usage of UNION and ORDER BY

A common problem when using the UNION command in MySQL is when you want to order the sets of data differently. If you do it incorrectly, you will see the error message:

Incorrect usage of UNION and ORDER BY

To solve the problem, wrap each individual SELECT statement in parenthesis as follows:

{code type=php}
(SELECT col1,col2,col3 FROM table1 ORDER BY col2)
(SELECT cola,colb,colc FROM table2 ORDER BY cola)

Nice and simple, all you have to do is remember the brackets!

{ 7 comments… read them below or add one }

jimbo_dk September 19, 2007 at 12:21 am

Thanks…I was having the same problem.


Anand Samyo August 1, 2008 at 5:14 pm

Thanks, i was looking for this


arun August 13, 2009 at 2:05 pm

thanks for sharing … saved time for me


Marco January 4, 2010 at 5:19 pm

Thank you also from me, I did appreciate the help!!


M Hussain April 22, 2010 at 10:55 am

Thanks, It solves my problem.


Ales May 11, 2010 at 10:14 am

This solved my problem.


Punit Raizada August 11, 2010 at 3:26 pm

Cool !!!! thanks a million.. solution was so darn simple :).


Cancel reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: