Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL syntax error at or near 'union'

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'
like image 680
Padagomez Avatar asked Jun 03 '14 16:06

Padagomez


People also ask

What is Union in PostgreSQL?

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.

How do I join two queries in PostgreSQL?

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.

Does Union all require same number of columns?

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.


1 Answers

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.

like image 186
Padagomez Avatar answered Sep 29 '22 22:09

Padagomez