sql-server
  1. sql-server-union-operator

UNION Operator - SQL Server Operators

The UNION operator is used to combine the results of two or more SELECT statements into a single result set. In this page, we will discuss the syntax, example, output, explanation, use, important points, and summary of the UNION operator in SQL Server.

Syntax

The syntax for the UNION operator is as follows:

SELECT column1, column2, ... columnN FROM table1 WHERE condition1
UNION
SELECT column1, column2, ... columnN FROM table2 WHERE condition2
...
UNION
SELECT column1, column2, ... columnN FROM tableN WHERE conditionN

The ORDER BY clause can be used to sort the result set.

SELECT column1, column2, ... columnN FROM table1 WHERE condition1
UNION
SELECT column1, column2, ... columnN FROM table2 WHERE condition2
...
UNION
SELECT column1, column2, ... columnN FROM tableN WHERE conditionN
ORDER BY column1, column2, ... columnN

Example

Here is an example of using the UNION operator to combine the results of two SELECT statements:

SELECT first_name, last_name FROM customers WHERE age > 30
UNION
SELECT first_name, last_name FROM employees WHERE age > 30
ORDER BY last_name, first_name

This query selects the first_name and last_name columns from the customers and employees tables where the age is greater than 30. It then combines the two result sets into a single result set and sorts it by last_name and first_name.

Output

The result set of the UNION operator is a combination of the result sets of the SELECT statements that are being combined. The number and order of the columns in the result set are determined by the first SELECT statement.

Explanation

The UNION operator allows you to combine the results of two or more SELECT statements into a single result set. The ORDER BY clause can be used to sort the result set.

Use

The UNION operator is useful when you need to combine the results of two or more SELECT statements into a single result set. This can be useful when you need to query multiple tables or when you need to combine data from different parts of the same table.

Important Points

  • The number and order of columns in the result set are determined by the first SELECT statement.
  • The ORDER BY clause can be used to sort the result set.
  • The UNION operator can only be used to combine result sets that have the same number of columns.

Summary

In this page, we discussed the UNION operator in SQL Server. We covered the syntax, example, output, explanation, use, and important points of the UNION operator. The UNION operator is a useful tool for combining the results of two or more SELECT statements into a single result set.

Published on: