postgresqlHow do I use PostgreSQL UNION to combine the results of two queries?
The PostgreSQL UNION statement is used to combine the results of two or more queries into a single result set.
SELECT column_name(s)
FROM table1
UNION
SELECT column_name(s)
FROM table2;
For example, if you have two tables table1 and table2 with the same columns, you can combine the results of both tables into a single result set like this:
SELECT column_name
FROM table1
UNION
SELECT column_name
FROM table2;
The output of the query would look like this:
column_name
-----------
value1
value2
value3
value4
The UNION statement can also be used to combine results from multiple tables with different columns, but the number of columns and data types must be the same for each query.
You can also use the UNION ALL statement to combine multiple queries and include duplicate rows in the results.
Helpful links
More of Postgresql
- How can I set a PostgreSQL interval to zero?
- How can Zalando use PostgreSQL to improve its software development?
- How can I integrate PostgreSQL with Yii2?
- How do I parse XML data using PostgreSQL?
- How can I monitor PostgreSQL performance using Zabbix?
- How can I use PostgreSQL and ZFS snapshots together?
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How do I use PostgreSQL and ZFS together?
- How can I use PostgreSQL with Zabbix?
- How can I use PostgreSQL for my project?
See more codes...