SQL Tutorial SQL Advanced SQL Database SQL References

SQL UNION ALL Keyword



The SQL UNION ALL keyword is used to combine the result-set of two or more SQL SELECT statements. While using UNION ALL keyword, the following criteria must be satisfied:

  • Number of columns in each SELECT statement should equal.
  • Datatype of columns in each SELECT statement should match.
  • Order of columns in each SELECT statement should match.

Syntax

The syntax for using UNION ALL keyword is given below:

SELECT column1, column2, ... FROM table1
UNION ALL
SELECT column1, column2, ... FROM table2

Note: UNION ALL keyword combines all values (allows duplicate values). To combine only distinct values, UNION keyword can be used.

Example:

Consider database tables called Employee and Vendor with the following records:

Table 1: Employee table

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryLondon242750
3JoParis272800

Table 2: Vendor table

EmpIDNameCityAge
1KimLondon30
2RameshNew Delhi28
3SureshNew Delhi31

  • To fetch all cities from tables Employee and Vendor, the SQL code is given below:

    SELECT City FROM Employee
    UNION ALL
    SELECT City FROM Vendor
    ORDER BY City;
    

    This result of the above code will be:

    City
    London
    London
    London
    New Delhi
    New Delhi
    Paris
  • To fetch all cities from tables Employee and Vendor where age of the person is less than 30, the SQL code is given below:

    SELECT City FROM Employee
    WHERE Age < 30
    UNION ALL
    SELECT City FROM Vendor
    WHERE Age < 30
    ORDER BY City;
    

    This will produce the result as shown below:

    City
    London
    London
    New Delhi
    Paris

❮ SQL Keywords

5