You are on page 1of 9
07/01/2028 15:56 UNION (Transact-SOL) - SAL Server | McrosoflLearn Set Operators - UNION (Transact-SQL) Article + 12/30/2022 + 7 minutes to read Applies to: © SQL Server (all supported versions) @ Azure SQL Database @ Azure SQL Managed Instance @ Azure Synapse Analytics © Analytics Platform System (PDW) Concatenates the results of two queries into a single result set. You control whether the result set includes duplicate rows: UNION ALL - Includes duplicates. * UNION - Excludes duplicates. AUNION operation is different from a JOIN: * AUNION concatenates result sets from two queries. But a UNION does not create individual rows from columns gathered from two tables. * AJOIN compares columns from two tables, to create result rows composed of columns from two tables. The following are basic rules for combining the result sets of two queries by using UNION: © The number and the order of the columns must be the same in all queries. * The data types must be compatible. Transact-SQL syntax conventions Syntax syntaxsal { | ( ) } {UNION [ ALL ] { | ( ) } [een] © Note To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation. hitps:flearn.microsof.comven-usisalt-sqllanguage-elomentsisetoperators-union-ransact-sql?viewssqh-server-verl6 19 ono va02s 1588 UNION (Tansee SAL) - SOL Server | Merosc Lea Arguments | ( ) Is a query specification or query expression that returns data to be combined with the data from another query specification or query expression. The definitions of the columns that are part of a UNION operation don't have to be the same, but they must be compatible through implicit conversion. When data types differ, the resulting data type is determined based on the rules for data type precedence. When the types are the same but differ in precision, scale, or length, the result is based on the same rules for combining expressions. For more information, see Precision, Scale, and Length (Transact-SQL) Columns of the xml data type must be equal. All columns must be either typed to an XML schema or untyped. If typed, they must be typed to the same XML schema collection, UNION Specifies that multiple result sets are to be combined and returned as a single result set. ALL Incorporates all rows into the results, including duplicates. If not specified, duplicate rows are removed. Examples A. Using a simple UNION In the following example, the result set includes the contents of the ProductmodelzD and Name columns of both the ProductModel and Gloves tables. sau -- Uses AdventureWorks IF OBJECT_ID (‘dbo.Gloves', ‘U") IS NOT NULL DROP TABLE dbo.Gloves; 60 -- Create Gloves table. SELECT ProductModelID, Name INTO dbo.Gloves FROM Production. ProductNodel WHERE ProductModel1D IN (3, 4); 60 Here is the simple union. Uses AdventureWorks hitps:llearn.microsof.comven-usisalt-sqllanguage-elomentsisetoperatrs-union-ransact-sql?viewssqh-server-verl6 219 7701/2028 15:56 UNION (Transact-SOL) - SAL Server | McrosoflLearn SELECT ProductModelID, Name FROM Production.ProductModel WHERE ProductModelID NOT IN (3, 4) UNION SELECT ProductModelID, Name FROM dbo.Gloves ORDER BY Names co B. Using SELECT INTO with UNION In the following example, the 1NTo clause in the second seLecr statement specifies that the table named ProductResults holds the final result set of the union of the selected columns of the ProductModel and Gloves tables. The Gloves table is created in the first SELECT statement. sat -- Uses AdventureWorks IF OBJECT_ID (‘dbo.ProductResults’, 'U") IS NOT NULL DROP TABLE dbo.ProductResults; 0 IF OBJECT_ID (‘dbo.Gloves*, ‘U') IS NOT NULL DROP TABLE dbo. Gloves; 60 -- Create Gloves table. SELECT ProductModelID, Name INTO dbo.Gloves FROM Production.ProductModel WHERE ProductModelID IN (3, 4); 0 -- Uses AdventureWorks SELECT ProductModelID, Name INTO dbo.ProductResults FROM Production.ProductNodel WHERE ProductModelID NOT IN (3, 4) UNION SELECT ProductModelID, Name FROM dbo.Gloves; co SELECT ProductModelID, Name FROM dbo.ProductResults; hitps:flearn.microsof.comven-usisalt-sqllanguage-elomentsisetoperators-union-ransact-sql?viewssqh-server-verl6 38 o7iovanzs 1586 UNION (Transact-SQL) - SOL. Sewer | Microsoft Learn C. Using UNION of two SELECT statements with ORDER BY The order of certain parameters used with the UNION clause is important. The following example shows the incorrect and correct use of UNION in two SELECT statements in which a column is to be renamed in the output. sau -- Uses AdventureWorks IF OBJECT_ID (‘dbo.Gloves*, “U') IS NOT NULL DROP TABLE dbo.Gloves; 60 -- Create Gloves table. SELECT ProductModelID, Name INTO dbo.Gloves FROM Production. ProductModel WHERE ProductModelID IN (3, 4); co /* INCORRECT */ -- Uses AdventureWorks SELECT ProductModelID, Name FROM Production.ProductModel WHERE ProductModelID NOT IN (3, 4) ORDER BY Name UNION SELECT ProductModelID, Name FROM dbo.Gloves; Go 7* CORRECT */ -- Uses AdventureWorks SELECT ProductModelID, Name FROM Production.ProductModel WHERE ProductModelID NOT IN (3, 4) UNION SELECT ProductModelID, Name FROM dbo.Gloves ORDER BY Names Go D. Using UNION of three SELECT statements to show the effects of ALL and parentheses hitps:flearn.microsof.comven-usisalt-sqllanguage-elomentsisetoperators-union-ransact-sql?viewssqh-server-verl6 49 oriow2029 15:56 UNION (Transact-SQL) - SOL Server | Microsoft Learn The following examples use UNTON to combine the results of three tables that all have the same 5 rows of data, The first example uses UNION ALL to show the duplicated records, and returns all 15 rows. The second example uses unroN without aLt to eliminate the duplicate rows from the combined results of the three SELECT statements, and returns 5 rows. The third example uses ALL with the first uNtoN and parentheses enclose the second UNTON that isn't using ALL. The second UNION is processed first because it's in parentheses, and returns 5 rows because the ALL option isn't used and the duplicates are removed. These 5 rows are combined with the results of the first seLect by using the UNION ALL keywords. This example doesn't remove the duplicates between the two sets of five rows. The final result has 10 rows. sau -- Uses AdventureWorks IF OBJECT_ID (‘dbo.EmployeeOne’, ‘U') IS NOT NULL DROP TABLE dbo. EmployeeOne; 60 IF OBJECT_ID (‘dbo.EmployeeTwo', "U') IS NOT NULL DROP TABLE dbo. EmployeeTwo; co IF OBJECT_ID (‘dbo.EmployeeThree’, ‘U') IS NOT NULL DROP TABLE dbo. EmployeeThree; 60 SELECT pp.LastName, pp.FirstName, e.JobTitle INTO dbo. Employeeone FROM Person.Person AS pp JOIN HumanResources.émployee AS e ON e.BusinessEntityID = pp.BusinessEntity1D WHERE LastName = ‘Johnson’ ; 60 SELECT pp.LastName, pp.FirstName, e.JobTitle INTO dbo. EmployeeTwo FROM Person.Person AS pp JOIN HumanResources.émployee AS e ON e.BusinessEntityID = pp.BusinessEntity1D WHERE LastName = ‘Johnson’ ; 60 SELECT pp.LastName, pp.FirstName, e.JobTitle INTO dbo. EmployeeThree FROM Person.Person AS pp JOIN HumanResources.émployee AS e ON €.BusinessEntityID = pp.BusinessEntity1D WHERE LastName = ‘Johnson’ ; 60 == Union ALL SELECT LastName, FirstName, JobTitle FROM dbo. Employeeone UNTON ALL SELECT LastName, FirstName ,JobTitle hitps:llearn.microsof.comven-usisalt-sqllanguage-elomentsisetoperatrs-union-ransact-sql?viewssqh-server-verl6 5 7701/2028 15:56 UNION (Transact-SOL) - SAL Server | McrosoflLearn FROM dbo. EmployeeTwo UNION ALL SELECT LastName, FirstName, JobTitle FROM dbo. EmployeeThree; co SELECT LastName, FirstName, JobTitle FROM dbo. Employeeone UNTON SELECT LastName, FirstName, JobTitle FROM dbo. EmployeeTwo UNION SELECT LastName, FirstName, JobTitle FROM dbo. EmployeeThree; Go SELECT LastName, FirstName, JobTitle FROM dbo. Employeeone UNION ALL ( SELECT LastName, FirstName, JobTitle FROM dbo. EmployeeTwo UNION SELECT LastName, FirstName, JobTitle FROM dbo. EmployeeThree 6 Go Examples: Azure Synapse Analytics and Analytics Platform System (PDW) E. Using a simple UNION In the following example, the result set includes the contents of the customerkey columns of both the FactinternetSales and Dimcustoner tables. Since the ALL keyword isn't used, duplicates are excluded from the results. sau -+ Uses Adventureworks SELECT Customerkey FROM FactInternetSales UNION SELECT Customerkey FROM DimCustomer ORDER BY Customerkey; hitps:llearn.microsof.comven-usisalt-sqllanguage-elomentsisetoperatrs-union-ransact-sql?viewssqh-server-verl6 ee 7701/2028 15:56 UNION (Transact-SOL) - SAL Server | McrosoflLearn F. Using UNION of two SELECT statements with ORDER BY When any SELECT statement in a UNION statement includes an ORDER BY clause, that clause should be placed after all SELECT statements. The following example shows the incorrect and correct use of UNION in two SELECT statements in which a column is ordered with ORDER BY. sat -- Uses AdventureWorks -- INCORRECT SELECT Customerkey FROM FactInternetSales ORDER BY CustomerKey UNION SELECT Customerkey FROM DimCustomer ORDER BY CustomerKey; =~ CORRECT USE AdventureWorksPDW2012; SELECT Customerkey FROM FactInternetSales UNION SELECT Customerkey FROM DimCustomer ORDER BY Customerkey; G. Using UNION of two SELECT statements with WHERE and ORDER BY The following example shows the incorrect and correct use of UNION in two SELECT statements where WHERE and ORDER BY are needed. sau -- Uses AdventureWorks -- INCORRECT SELECT Customerkey FROM FactInternetSales WHERE Customerkey >= 11000 ORDER BY CustomerKey hitps:llearn.microsof.comven-usisalt-sqllanguage-elomentsisetoperatrs-union-ransact-sql?viewssqh-server-verl6 79 7701/2028 15:56 UNION (Transact-SOL) - SAL Server | McrosoflLearn UNION SELECT Customerkey FROM DimCustomer ORDER BY Customerkey; -- CORRECT USE AdventureWorksPDW2012; SELECT Customerkey FROM FactInternetSales WHERE Customerkey >= 11000 UNION SELECT Customerkey FROM DimCustomer ORDER BY Customerkey; H. Using UNION of three SELECT statements to show effects of ALL and parentheses The following examples use UNION to combine the results of the same table to demonstrate the effects of ALL and parentheses when using UNTON The first example uses UNION ALL to show duplicated records and returns each row in the source table three times. The second example uses UNION without ALL to eliminate the duplicate rows from the combined results of the three SELECT statements and returns only the unduplicated rows from the source table. The third example uses ALL with the first unzow and parentheses enclosing the second UNION that isn't using ALL. The second UNION is processed first because it is in parentheses. It returns only the unduplicated rows from the table because the ALL option isn’t used and duplicates are removed. These rows are combined with the results of the first SELECT by using the UNTON ALL keywords. This example doesn't remove the duplicates between the two sets. sau -- Uses AdventureWorks SELECT Customerkey, FirstName, LastName FROM DimCustomer UNION ALL SELECT Customerkey, FirstName, LastName FROM DimCustomer UNION ALL SELECT Customerkey, FirstName, LastName FROM DimCustomer; hitps:llearn.microsof.comven-usisalt-sqllanguage-elomentsisetoperatrs-union-ransact-sql?viewssqh-server-verl6 ae 7701/2028 15:56 SELECT Customerkey, FROM DimCustomer UNION SELECT Customerkey, FROM DimCustomer UNION SELECT Customerkey, FROM DimCustomer SELECT Customerkey, FROM DimCustomer UNION ALL ( SELECT Customerkey, FROM DimCustomer UNION SELECT Customerkey, FROM DimCustomer 6 See Also SELECT (Transact-SQL) UNION (Transact-SOL) - SAL Server | McrosoflLearn FirstName, FirstName, FirstName, FirstName, FirstName, FirstName, SELECT Examples (Transact-SQL) hitps:flearn.microsof.comven-usisalt-sqllanguage-elomentsisetoperators-union-ransact-sql?viewssqh-server-verl6 LastName LastName LastName LastName LastName LastName 9

You might also like