SQL Union

In SQL, the UNION operator is used to combine the results of two or more SELECT queries into a single […]

In SQL, the UNION operator is used to combine the results of two or more SELECT queries into a single result set. The key thing to remember is that each SELECT statement within the UNION must have the same number of columns, with similar data types in the correspoding columns.

SQL Union Syntax

SQL



Tutorials dojo strip

SQL Union Basic Example

This query will return a list of distinct first names from both Patients and Doctors tables.

SQL




SQL Union ALL Example

This query returns all the first names, including duplicates, from both tables. For example, if a first name appears in both tables, it will be listed twice.

SQL




SQL Union with WHERE Example

This query will return a list of distinct first names, combining female patients from the Patients table and pediatric doctors from the Doctors table.

SQL




SQL Union ALL with WHERE Example

This query returns all male patients and all doctors who specialize in cardiology. It will include duplicates if a first name appears in both groups.

SQL




SQL Union Another Union Example

This query combines last names from the Patients and Doctors tables and names from the Students table.

SQL




SQL Union Visual Diagram



SQL Union Labs

Tutorials dojo strip