Sobes.tech
Junior — Middle

How does the UNION operator work and how does it combine query results?

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 data set. It returns unique rows from all queries, excluding duplicates.

Main features of UNION:

  • The number and order of columns in the combined queries must match.
  • The data types of corresponding columns must be compatible.
  • By default, it removes duplicates (if you want all rows including duplicates, use UNION ALL).

Example:

SELECT name FROM employees
UNION
SELECT name FROM managers;

This query will return a list of unique names from the employees and managers tables.

Thus, UNION combines the results of queries into one set, ensuring row uniqueness.