SQL Union All with order by and limit (Postgresql)

michael picture michael · May 20, 2016 · Viewed 12.3k times · Source

In the following query I get syntax error:

SELECT <property1>, <property2>
FROM <table1> 
ORDER BY <condition> LIMIT 1
UNION  ALL
SELECT <property1>, <property2>
FROM <table2> 
WHERE <condition> ORDER BY <condition> LIMIT 1;

syntax error at or near "UNION" LINE 4: UNION ALL

Each of the SELECT stand alone executes fine. My guess is about the ORDER BY... LIMIT 1 maybe?

Answer

Lukasz Szozda picture Lukasz Szozda · May 20, 2016

Wrap each query with ():

(SELECT <property1>, <property2>
FROM <table1> 
ORDER BY <condition> LIMIT 1)
UNION  ALL
(SELECT <property1>, <property2>
FROM <table2> 
WHERE <condition> ORDER BY <condition> LIMIT 1);

SqlFiddleDemo

You could also order final query:

(SELECT 'a' AS col
ORDER BY col LIMIT 1)
UNION ALL 
(SELECT 'b' AS col
ORDER BY col  LIMIT 1)
ORDER BY  col DESC