Sobes.tech
Junior — Middle

Can you explain the purpose of the UNION operator in SQL and how it is used to combine the results of multiple queries?

sobes.tech AI

Answer from AI

The UNION operator in SQL is used to combine the results of two or more SELECT queries into a single dataset. It returns unique rows from all queries, excluding duplicates.

Usage features:

  • All SELECT queries must return the same number of columns.
  • Data types of corresponding columns must be compatible.
  • The order of columns is important.

Example:

SELECT name FROM employees WHERE department = 'Sales'
UNION
SELECT name FROM contractors WHERE department = 'Sales';

This query will return a list of unique names from the employees and contractors tables working in the sales department.

To preserve duplicates, UNION ALL is used.