Combine two sql select queries (in postgres) with LIMIT statement

Aidan Ewen picture Aidan Ewen · Nov 27, 2012 · Viewed 16.9k times · Source

I've got a table and I want a query that returns the last 10 records created plus the record who's id is x.

I'm trying to do -

SELECT * FROM catalog_productimage
ORDER BY date_modified
LIMIT 10
UNION
SELECT * FROM catalog_productimage
WHERE id=5;

But it doesn't look like I can put LIMIT in there before UNION. I've tried adding another column and using it for sorting -

SELECT id, date_modified, IF(false, 1, 0) as priority FROM catalog_productimage
UNION
SELECT, id, date_modified, IF(true, 1, 0) as priority FROM catalog_productimage
WHERE id=5
ORDER BY priority, date_modified
LIMIT 10;

but I'm not making much progress..

Answer

sufleR picture sufleR · Nov 27, 2012

Just checked that this will work:

(SELECT * FROM catalog_productimage
ORDER BY date_modified
LIMIT 10)
UNION
SELECT * FROM catalog_productimage
WHERE id=5;