1

This works

SELECT * 
    FROM foo
UNION
SELECT *
    FROM bar

This gives me a "syntax error near UNION".

SELECT * 
    FROM foo
    ORDER BY random() LIMIT 1000
UNION
SELECT *
    FROM bar
    ORDER BY random() LIMIT 1000;

Why is that? How to UNION tables with ORDER BY and LIMIT?

four-eyes
  • 10,740
  • 29
  • 111
  • 220
  • Does this answer your question? [SQL Union All with order by and limit (Postgresql)](https://stackoverflow.com/questions/37352296/sql-union-all-with-order-by-and-limit-postgresql) – forpas Apr 16 '22 at 09:48

2 Answers2

1

You need to place each half of the union into a separate subquery:

(SELECT * FROM foo ORDER BY RANDOM() LIMIT 1000)
UNION ALL
(SELECT * FROM bar ORDER BY RANDOM() LIMIT 1000);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You can try this too, englobe your statement in a Select

SELECT *
FROM (SELECT * FROM foo ORDER BY random() limit 10) as dt1
UNION
SELECT *
FROM (SELECT * FROM bar ORDER BY random() limit 10) as dt2
Romylussone
  • 773
  • 1
  • 8
  • 19