Order By with Union’s in MySQL

I’ve you’re just starting to play with a Union, then you might have gotten the error message:

#1221 - Incorrect usage of UNION and ORDER BY

You might be thinking: Whoa, hang on there! Do you mean MySQL can't order a Union?! Oh, but it can! First little issue I had was in realizing that you can put parenthesis around the queries. So phrase your query thusly:

"(SELECT ...) UNION (SELECT ...) ORDER BY ..."

Just be sure that your Order By includes only the column name. Table.Column is going to get you another error!

6 thoughts on “Order By with Union’s in MySQL

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.