Incorrect usage of UNION and ORDER BY

by Carey on October 7, 2010

Post image for Incorrect usage of UNION and ORDER BY
  • Share
  • CevherShare
  • Share

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:

(SELECT col1,col2,col3 FROM table1 ORDER BY col2)
UNION
(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.

Reply

Anand Samyo August 1, 2008 at 5:14 pm

Thanks, i was looking for this

Reply

arun August 13, 2009 at 2:05 pm

thanks for sharing … saved time for me

Reply

Marco January 4, 2010 at 5:19 pm

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

Reply

M Hussain April 22, 2010 at 10:55 am

Thanks, It solves my problem.

Reply

Ales May 11, 2010 at 10:14 am

This solved my problem.
Thanks.

Reply

Punit Raizada August 11, 2010 at 3:26 pm

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

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: