Union in SQL |Union Command in SQL - sql - sql tutorial - learn sql
- The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.
- Column data types in the two queries must match.
- UNION combines by column position rather than column name.
Tags : sql tutorial , pl sql tutorial , mysql tutorial , oracle tutorial , learn sql , sql server tutorialThe SQL UNION syntax
The SQL UNION syntax
- The general syntax is:
SELECT column-names
FROM table-name
UNION
SELECT column-names
FROM table-name
| SUPPLIER |
|---|
| Id |
| CompanyName |
| ContactName |
| City |
| Country |
| Phone |
| Fax |
| CUSTOMER |
|---|
| Id |
| FirstName |
| LastName |
| City |
| Country |
| Phone |
Difference Between Union Unionall Except Intersect
SQL UNION Examples
- Problem: List all contacts, i.e., suppliers and customers.
SELECT 'Customer' As Type,
FirstName + ' ' + LastName AS ContactName,
City, Country, Phone
FROM Customer
UNION
SELECT 'Supplier',
ContactName, City, Country, Phone
FROM Supplier
- This is a simple example in which the table alias would be useful
Results:
| Type | Contact Name |
City | Country | Phone |
|---|---|---|---|---|
| Customer | Alejandra Camino |
Madrid | Spain | (91) 745 6200 |
| Customer | Alexander Feuer |
Leipzig | Germany | 0342-023176 |
| Customer | Ana Trujillo | México D.F. | Mexico | (5) 555-4729 |
| Customer | Anabela Domingues |
Sao Paulo | Brazil | (11) 555-2167 |
Union vs Union All
SQL Union Query Example