Ben
Ben

Reputation: 609

Postgres UNION with ORDER BY and LIMIT

Is it possible to do this:

SELECT * FROM public."LamcApiCalls" WHERE generalstatuscode=0 AND sendondate < NOW() AND push = 1
UNION ALL
SELECT * FROM public."LamcApiCalls" WHERE generalstatuscode=0 AND sendondate < NOW() AND push IS NULL ORDER BY random() LIMIT 50

It's failing because of the ORDER BY and LIMIT on the second query. Is there anyway to do that?

Thanks

Upvotes: 0

Views: 340

Answers (1)

S-Man
S-Man

Reputation: 23746

You can put the second query into a subquery:

SELECT * FROM public."LamcApiCalls" WHERE generalstatuscode=0 AND sendondate < NOW() AND push = 1

UNION ALL

SELECT 
    * 
FROM (
    SELECT * FROM public."LamcApiCalls" WHERE generalstatuscode=0 AND sendondate < NOW() AND push IS NULL ORDER BY random() LIMIT 50
) s

Upvotes: 1

Related Questions