I have a small query, and a union to put another small query next to it. However, the union has a syntax error in it.
Select <column1>
,<column2>
,<column3>
From <Table1>
<Some joins in there>
where <conditions>
order by <column2>
union
select <column2>
,<column3>
,<column4>
from <Table2>
<Some more joins here>
where <conditions>
order by <column2>
This is the Error I receive
ERROR: Syntax error at or near 'union'
The PostgreSQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.
Introduction to PostgreSQL UNION operatorTo combine the result sets of two queries using the UNION operator, the queries must conform to the following rules: The number and the order of the columns in the select list of both queries must be the same. The data types must be compatible.
UNION or UNION ALL have the same basic requirements of the data being combined: There must be the same number of columns retrieved in each SELECT statement to be combined. The columns retrieved must be in the same order in each SELECT statement. The columns retrieved must be of similar data types.
I see what was wrong. You have to place the order by at the end of the query, and only at the end. It gave me an error because it thought the query had eneded.
Select <column1>
,<column2>
,<aggregate column3>
From <Table1>
<Some joins in there>
Where <conditions>
group by <column2>, <column1>
union
select <column2>
,<column3>
,<aggregate column4>
From <Table2>
<Some more joins here>
Where <conditions>
group by <column2>, <column3>
order by <column2>
That did the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With