📜  SQLite Union All(1)

📅  最后修改于: 2023-12-03 15:20:18.231000             🧑  作者: Mango

SQLite Union All

UNION ALL is a useful SQL operator that allows you to combine the result sets of two or more SELECT statements. It returns all the rows from all the SELECT statements included in the query, with duplicates rows included.

Syntax

The basic syntax for UNION ALL is as follows:

SELECT column1, column2, ... FROM table1
UNION ALL
SELECT column1, column2, ... FROM table2
[UNION ALL
SELECT column1, column2, ... FROM table3];
Example

Suppose you have two tables, Employee1 and Employee2, with the following data:

Employee1
+------+-------+--------+
| ID   | Name  | Salary |
+------+-------+--------+
| 101  | John  | 2500   |
| 102  | Jane  | 3000   |
| 103  | Mary  | 2000   |
+------+-------+--------+

Employee2
+------+-------+--------+
| ID   | Name  | Salary |
+------+-------+--------+
| 104  | Mark  | 3500   |
| 105  | Lisa  | 1500   |
| 106  | Mike  | 4000   |
+------+-------+--------+

To select all employees from both tables, you can use the UNION ALL operator as follows:

SELECT ID, Name, Salary FROM Employee1
UNION ALL
SELECT ID, Name, Salary FROM Employee2;

This will return the following result set:

+------+-------+--------+
| ID   | Name  | Salary |
+------+-------+--------+
| 101  | John  | 2500   |
| 102  | Jane  | 3000   |
| 103  | Mary  | 2000   |
| 104  | Mark  | 3500   |
| 105  | Lisa  | 1500   |
| 106  | Mike  | 4000   |
+------+-------+--------+

Notice that the UNION ALL operator combines the rows from both tables, including duplicate rows, if any.

Use Cases

The UNION ALL operator can be useful in many scenarios, such as:

  • Combining data from multiple tables that have the same structure.
  • Joining data from different databases or data sources.
  • Creating virtual tables or views that combine data from multiple tables.
Conclusion

In summary, the UNION ALL operator is a versatile tool in SQL that allows you to combine the result sets of multiple SELECT statements. It is useful for various scenarios where data needs to be merged or combined from different sources.