Think that you can not use a clause ORDER BY
partially in any% common%, the order applies to the whole query, although in your case use SELECT
the final result is still a single query. The UNION
is always resolved by the engine at the end of everything, when you have already solved the rest of the sentences, the other limitation you have is that you can not sort by a column that only exists in a part of ORDER
.
Also, a secondary fact, which is not worth commenting on: it is that the engine does not guarantee a natural order when a UNION
is not specified, that is to say that without this clause, we will never be guaranteed that the rows have the same order always.
To do what you want, you can try:
Using subqueries
In this way the engine "understands" that it must first process a subquery, which in this case can have a ORDER
. For example:
SELECT Campo
FROM (SELECT Campo, calldate FROM Tabla1 ORDER BY calldate) T
UNION
SELECT Campo FROM Tabla2
UNION
SELECT Campo FROM Tabla3;
However, whether or not it works depends on the engine, so before I said, since the final query does not have an order, do we have a guarantee that the data set of the first ORDER
will always be ordered in the same way? ?
Adding the field to the query
SELECT calldate, Campo FROM Tabla1
UNION
SELECT NULL, Campo FROM Tabla2
UNION
SELECT NULL, Campo FROM Tabla3
ORDER BY 1 DESC
This is the appropriate form, we must add the column to be sorted in the first query and return select
in the position of said column in the other queries, in this way we can apply the NULL
at the end and we end up insuring that the final result will have the rows of the first ORDER
at the beginning and sorted by SELECT
. (In a calldate
the ORDER
goes first, that's why we use NULL
)