Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs

SQL UNION ALL

by suresh

The SQL UNION ALL is used to combine two or more SELECT statements, and returns a single result set. The Union ALL in Sql Server will select all the records (including duplicate records) from all queries. The syntax behind the Union All in SQL Server is

-- SQL Server UNION ALL Syntax
SELECT Column1, Column2 ......., ColumnN FROM Table1
UNION ALL
SELECT Column1, Column2 ......., ColumnN FROM Table2

The basic rules to use this Union ALL in SQL Server are:

  1. The number of columns and its order must be the same in all the queries.
  2. The column data types should be compatible with each other.

For this SQL SQL Union All operator Query demonstration, We are going to use two tables (Employ, and Employees 2015) present in our [SQL Tutorial] Database.

From the below figure you can observe that, [Employ] table have ten records

SQL UNION ALL 5

And [Employees 2015] table has six records. Notice that there are only two distinct records ((2, SQL, Server), and (2, Rob, Johnson)), and the remaining records are the same.

SQL UNION Example 1

SQL Union All example

The following SQL Query will return all the records (including duplicate records) from Employ table, Employees 2015 table, and display the result

-- Example for SQL Server Union ALL
SELECT [ID]
      ,[FirstName]
      ,[LastName]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
FROM [SQL Tutorial].[dbo].[Employ]
UNION ALL
SELECT [ID]
      ,[FirstName]
      ,[LastName]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
FROM [SQL Tutorial].[dbo].[Employees 2015]
SQL UNION ALL 1

SQL Union All along with Where

How to use the UNION ALL operator along with the where clause and ORDER BY Clause?. In this example, we are combining two Select statements:

  • The first SQL Server result set – It will select all the records from Employ, whose Sales amount is greater than 500
  • The second result set – It will select the records from Employees 2015 whose yearly income is greater than or equal to 70000
  • and the Union All operator will select all the records (including duplicates) from both the first result set and the second result set.
-- Example for SQL Server Union ALL
SELECT [ID]
      ,[FirstName]
      ,[LastName]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
FROM [SQL Tutorial].[dbo].[Employ]
WHERE [Sales] > 500
  UNION ALL
SELECT [ID]
      ,[FirstName]
      ,[LastName]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
FROM [SQL Tutorial].[dbo].[Employees 2015]
WHERE [YearlyIncome] >= 70000
ORDER BY [ID]
SQL UNION ALL 2

SQL Union All Errors

The following Query will display the common error that we face while working with the SQL Union All operators. For this, We use two tables (Employee and Employees 2015) available in our [SQL Tutorial] Database. From the below screenshot, you can observe that the [Employee] table has 7 columns and 14 rows.

SQL UNION ALL 7

Let us see what happens when we use the Sql Server UnionAll operator on the unequal length of columns.

-- SQL UNION ALL Example
SELECT [FirstName]
      ,[LastName]
      ,[Education]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
      ,[HireDate]
  FROM [SQL Tutorial].[dbo].[Employee]
UNION 
SELECT [FirstName]
      ,[LastName]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
  FROM [SQL Tutorial].[dbo].[Employees 2015]
SQL UNION ALL 3

I hope you can read the above message. All queries combined using a SQL UNION operator must have an equal number of expressions in their target lists. Now, let us change the query to select an equal number of columns

-- Example for SQL Server Union ALL
SELECT [FirstName]
      ,[LastName]
      ,[Occupation]
      ,[YearlyIncome], [Sales]
FROM [SQL Tutorial].[dbo].[Employee]
  UNION ALL
SELECT [FirstName]
      ,[LastName]
      ,[Occupation]
      ,[YearlyIncome], [Sales]
FROM [SQL Tutorial].[dbo].[Employees 2015]
ORDER BY [YearlyIncome] DESC

As you can observe that union all query is returning 20 records, i.e., 14 from Employee table + 6 from Employees 2015 table.

SQL UNION ALL 4

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW

Copyright © 2021· All Rights Reserved.
About | Contact | Privacy Policy