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 I use PostgreSQL XOR to compare two values?
- How can Zalando use PostgreSQL to improve its software development?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How can I use PostgreSQL with YAML?
- How do I use PostgreSQL's XMLTABLE to parse XML data?
- How do I show tables in PostgreSQL?
- How do I rename a column in PostgreSQL?
- How do I store an array in a PostgreSQL database?
See more codes...