SQL UNION ALL Keyword

The UNION ALL operator in SQL combines the result sets of two or more SELECT statements into a single result set. A key difference from the standard UNION operator is that UNION ALL includes duplicate rows.



UNION ALL: Definition and Usage

Use UNION ALL when you want to append the results of multiple queries together, keeping all rows, even if they are identical across different queries. This is faster than a regular UNION because it doesn't perform duplicate row removal.

Syntax

Syntax

SELECT column1, column2, ...
FROM table1
UNION ALL
SELECT column1, column2, ...
FROM table2
ORDER BY column_name;
      

Example

Combining City Data from Two Tables

This query combines city names from both the 'Customers' and 'Suppliers' tables, preserving duplicate cities.

Syntax

SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
      
Output

The output will be a list of all cities from both the 'Customers' and 'Suppliers' tables, sorted alphabetically. If a city appears in both tables, it will appear twice in the result.


City
-------
... (List of cities, with duplicates if present) ...

      

**Note:** The example output assumes that 'Customers' and 'Suppliers' tables exist and have a 'City' column. The `...` indicates that there will be multiple rows in the actual result, depending on the data in your tables. The order will be alphabetical due to the `ORDER BY City` clause.