views:

295

answers:

2

Is it possible to impose conditions on a SQL query to the greater of two conditions?

For example, imagine a site that has Posts. Is there a way to request posts such that the result will be guaranteed to contain both of at least all posts made in the past 24 hours, and at least 10 posts, but not unnecessarily exceeding either limit?

I.e., if it already has all posts made in the past 24 hours, but not 10 posts, it will continue adding posts until it reaches 10, or if it already has 10 posts, but not all posts made in the past 24 hours, it will continue until it covers the past 24 hours, but it will not ever have both posts from 25 hours ago and more than 10 posts.

Edit: In response to request to post my model. I'm not exactly sure how to post the model, since my models are created by Rails. However, in short, a Post has a created_at datetime row, and there is an index on it.

+1  A: 

I think LIMIT requires a constant, but if you have an index on the created field, pulling a few records from one end will be pretty efficient, right? What about something like (in SQL-ish pseudocode):

select * from posts
where created > min(one_day_ago,
                    (select created from posts
                     order by created desc
                     limit 1 offset 10));
Ken
I can't find anything in the Postgres docs, is it generally defined what happens if the offset is greater than the actual number of records, or what happens if there are insufficient number of records to meet min?
WIlliam Jones
Oh, good call. The inner SELECT would return the empty set, so you'd need to add something to handle that.
Ken
A: 

Probably the clearest solution is to make a select that returns the most recent 10, another select that returns everything for the last day and use the union of these two selects.

One of these unioned selects is always going to completely contain the other, so it may not be the most efficient, but I think it's what I would do.

Don Roby