SQL syntax error at or near 'union'

Padagomez picture Padagomez · Jun 3, 2014 · Viewed 14.6k times · Source

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>
From <Table1> 
<Some joins in there>
Where <conditions>
group by <column2>
order by <column2>

union

select <column2>
      ,<column3>
      ,<column4>
From <Table2>
<Some more joins here>
Where <conditions>
group by <column2>
order by <column2>

This is the Error I receive

ERROR: Syntax error at or near 'union'

Answer

Padagomez picture Padagomez · Jun 3, 2014

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.