sqlite
  1. sqlite-union-all

Union All

The UNION ALL clause in SQLite is used to combine the results of two or more SELECT statements into a single result set. It is used to combine the rows from two or more tables or SELECT statements.

Syntax

The basic syntax of the UNION ALL clause is as follows:

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

Example

Suppose you have two tables, table1 and table2, and you want to combine the rows from these two tables. You can use the UNION ALL clause as follows:

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

Output

The output of the SQL query with the UNION ALL clause is a result set that contains all the rows from both tables. The rows are combined and displayed in the order they are encountered.

Explanation

In the example above, we use the SELECT statement to retrieve data from two tables, table1 and table2. We use the UNION ALL clause to combine the data from these two tables into a result set. Note that we select the same columns in both SELECT statements.

The UNION ALL clause combines the rows from the two tables and creates a new result set that contains all the rows from table1 and table2. The UNION ALL clause does not eliminate duplicate rows, while the UNION clause does.

Use

The UNION ALL clause is useful when you want to combine the data from two or more tables or when you want to combine the results of two or more SELECT statements. This can be useful when you want to retrieve data from multiple sources or when you want to analyze data from different customers, suppliers, or manufacturers.

Important Points

  • The UNION ALL clause is used to combine the results of two or more SELECT statements into a single result set.
  • The columns in the SELECT statements must match in data type and order.
  • The UNION ALL clause does not eliminate duplicate rows, while the UNION clause does.
  • The number of columns and their order must be the same in all SELECT statements.
  • The data types of corresponding columns must match in all SELECT statements.

Summary

In this tutorial, we learned about the UNION ALL clause in SQLite and how it can be used to combine the rows from two or more tables or SELECT statements into a single result set. We saw examples of using UNION ALL to combine rows from two tables and how the UNION ALL clause differs from the UNION clause. We also learned about important points to keep in mind when using the UNION ALL clause.

Published on: