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 use PostgreSQL with YAML?
- How can I use PostgreSQL's "zero if null" feature?
- How do I use PostgreSQL's XMIN and XMAX features?
- How do I use regexp_replace in PostgreSQL?
- How can I set a PostgreSQL interval to zero?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can I use PostgreSQL and ZFS snapshots together?
- How can Zalando use PostgreSQL to improve its software development?
- How can I retrieve data from PostgreSQL for yesterday's date?
See more codes...