Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

union & order by

Posted on 2013-11-17
1
Medium Priority
?
416 Views
Last Modified: 2013-11-18
Hi there,
There are 2 SELECT statements joined by UNION.
The ORDER BY comes at the end.
The question is:  Can I  also put an ORDER BY after every SELECT? If I can, does that help the performance?

eg:

SELECT * FROM (SELECT  * FROM TABLE1  ) ORDER BY ID DESC LIMIT 500 ) AS T1
UNION ALL
SELECT * FROM (SELECT  * FROM TABLE2  ) ORDER BY ID  DESC LIMIT 500 ) AS T2
ORDER BY DATETIME DESC
0
Comment
Question by:myyis
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 51

Accepted Solution

by:
Steve Bink earned 2000 total points
ID: 39655363
MySQL 5.5 Reference Manual :: 13.2.9.4. UNION Syntax

Most of that article pertains to the use of ORDER BY with UNION.

As a sidenote, if you want to improve performance, remove the double-SELECT from your statements:
(SELECT * FROM TABLE1 ORDER BY ID DESC LIMIT 500)
UNION ALL
(SELECT * FROM TABLE2 ORDER BY ID DESC LIMIT 500)
ORDER BY DATETIME DESC

Open in new window

To further improve performance, don't "SELECT *" - identify the columns you need and include only those columns in your field list.
0

Featured Post

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
In this blog post, we’ll look at how ClickHouse performs in a general analytical workload using the star schema benchmark test.
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question