Set operators
On this page
Combine the rows returned by two queries.
UNION ALL
UNION ALL combines two result sets and keeps duplicate rows. Columns are matched by position. Both sides must return the same number of columns with compatible types.
Syntax
<query> UNION ALL <query>Examples
Combine checkout events from two sources. One source sends event IDs as strings and the other as integers; cast the integers to strings before combining them:
(
VALUES ('17', 'payment_failed'), ('42', 'payment_completed')
SELECT $0 AS event_id, $1 AS event
UNION ALL (
VALUES (63, 'payment_failed')
SELECT $0::string AS event_id, $1 AS event
)
)
ORDER BY event_id+----------+-------------------+
| event_id | event |
+----------+-------------------+
| 17 | payment_failed |
| 42 | payment_completed |
| 63 | payment_failed |
+----------+-------------------+Without the cast, the query fails because the first column is string on one side and int on the other.
Place ORDER BY or LIMIT after the closing parenthesis to apply it to the combined result.