Ahmad M. answered 01/17/24
Oracle Database & Infrastructure administrator 6+ years experience
To apply an Order By clause in a Union Query, you need to follow these simple steps:
- Write your first SELECT statement, and include the Order By clause in it.
- Write your second SELECT statement, and include the Order By clause in it.
- Combine the two SELECT statements using the Union or Union All clause, placing them inside parentheses.
- Add the Order By clause at the end of the entire query.
The syntax for applying Order By clause in a Union Query is:
(SELECT column1, column2, …FROM table1ORDER BY column1 ASC)UNION(SELECT column1, column2, …FROM table2ORDER BY column1 DESC)ORDER BY column1 ASC;
The above query will return the combined results of the two SELECT statements, sorted by column1 in ascending order.