Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..

like image 798
Aidan Ewen Avatar asked Nov 27 '12 12:11

Aidan Ewen


People also ask

How do I join two queries in PostgreSQL?

The UNION operator combines result sets of two or more SELECT statements into a single result set. To 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.

How do I limit query in PostgreSQL?

The LIMIT clause can be used with the OFFSET clause to skip a specific number of rows before returning the query for the LIMIT clause. Syntax:SELECT * FROM table LIMIT n OFFSET m; Let's analyze the syntax above. The LIMIT clause returns a subset of “n” rows from the query result.


1 Answers

Just checked that this will work:

(SELECT * FROM catalog_productimage ORDER BY date_modified LIMIT 10) UNION SELECT * FROM catalog_productimage WHERE id=5; 
like image 198
sufleR Avatar answered Sep 16 '22 15:09

sufleR