sqlite
  1. sqlite-union

SQLite Union

In SQLite, UNION is a clause that is used to combine the results of two or more SELECT statements into a single result set. The UNION operator can be used to remove duplicates from the result set.

Syntax

The syntax for the UNION statement is as follows:

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

Example

Suppose we have two tables employees and customers, both of which have a column called name. We can use the UNION clause to combine the results of two SELECT statements to get a list of unique names from both tables.

SELECT name FROM employees
UNION
SELECT name FROM customers;

Output

The output of the above query would be a single list of unique names from both tables.

name
---------------
John Smith
Jane Doe
Bob Johnson
Mary Smith
Tom Lee

Explanation

In the example above, we use the UNION clause to combine the results of two SELECT statements that select the name column from the employees and customers tables separately. Because the UNION operator removes duplicates from the result set, the output will be a list of unique names from both tables.

Use

The UNION clause is used to combine the results of two or more SELECT statements into a single result set. It is useful in scenarios where data is spread out across multiple tables or when you need to perform complex queries.

Important Points

  • The UNION operator only selects unique values from both SELECT statements.
  • The number of columns and their data types in both SELECT statements must be the same.
  • The UNION operator sorts the final result set in ascending order by default.
  • To sort the result set in descending order, use the ORDER BY clause at the end of the query.

Summary

In this tutorial, we learned about the UNION clause in SQLite and how to use it to combine the results of two or more SELECT statements into a single result set. We saw an example of using the UNION clause to get a list of unique names from two tables and discussed some important points to keep in mind while using the UNION operator. The UNION clause is a useful tool for combining data from multiple tables and performing complex queries.

Published on: