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 troubleshoot zero damaged pages in PostgreSQL?
- How can I set a PostgreSQL interval to zero?
- How do I use PostgreSQL and ZFS together?
- How do I use PostgreSQL's XMLTABLE to parse XML data?
- How can I monitor PostgreSQL performance using Zabbix?
- How do I use PostgreSQL with Qt?
- How can I use PostgreSQL's "zero if null" feature?
- How do I parse XML data using PostgreSQL?
- How can I use PostgreSQL and ZFS snapshots together?
- How do I access the PostgreSQL wiki?
See more codes...