UNION operator is one of the most frequent operators used in SQL Server scripting. As per MSDN it is used to combine the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union . But there is an issue with Union operator which prohibits order by for each table separately while using UNION / UNION ALL. It generates an error.
Let me explain this error in detail :
Message Number: 156
Severity : 15
Error Message: Incorrect syntax near the keyword ‘UNION’.
Error Generation:
Let me create a sample to demonstrate this error.
USE tempdb GO CREATE TABLE tbl_Sample1 ( [ID] INT, [Grade] VARCHAR(50) ) GO CREATE TABLE tbl_Sample2 ( [ID] INT, [Grade] VARCHAR(50) ) INSERT INTO tbl_Sample1 VALUES (1,'Grade A') INSERT INTO tbl_Sample1 VALUES (2,'Grade B') INSERT INTO tbl_Sample1 VALUES (3,'Grade C') INSERT INTO tbl_Sample1 VALUES (4,'Grade D') INSERT INTO tbl_Sample1 VALUES (5,'Grade E') INSERT INTO tbl_Sample1 VALUES (6,'Grade F') GO INSERT INTO tbl_Sample2 VALUES (1,'1st') INSERT INTO tbl_Sample2 VALUES (2,'2nd') INSERT INTO tbl_Sample2 VALUES (3,'3rd') INSERT INTO tbl_Sample2 VALUES (4,'4th') INSERT INTO tbl_Sample2 VALUES (5,'5th')
Once you created the above sample, lets make a UNION ALL query and try to ORDER BY each table separately.
USE tempdb GO SELECT [ID],[Grade] FROM tbl_Sample1 Order By [ID] UNION ALL SELECT [ID],[Grade] FROM tbl_Sample2 Order By [ID]
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword ‘UNION’.
Ooopps…… I am unable to execute it.
Resolution:
It is very simple to resolve, just add one more column with any sorting number… either 1,2,3 or A,B,C and order on the basis of this column. Let me demonstrate it.
USE tempdb GO SELECT 'A' AS [Order ID] , [ID] , [Grade] FROM tbl_Sample1 UNION ALL SELECT 'B' AS [Order ID] , [ID] , [Grade] FROM tbl_Sample2 Order By [Order ID] --OUTPUT
Remember, whenever you use UNION / UNION ALL and have to order by each table separately, just add one more column with any sorting value and order by on the basis of this column.
Leave a Reply