I have the following query:
SELECT SUM(data), foreign_key
FROM (SELECT *
FROM really_big_table
ORDER BY auto_incremented_id DESC
LIMIT reasonable_number)
WHERE inserted_timestamp > now() - INTERVAL '1 hour'
GROUP BY foreign_key
This query successfully averts running a sequential scan over inserted_timestamp, but it will utterly fail if there is more than a reasonable number of rows that I need to retrieve. Since inserted_timestamp is not indexed, but follows the same sequence as auto_incremented_id, I feel like I can make this query even more efficient without causing an hour's downtime creating a new index.
I would like to do something like this:
SELECT SUM(data), foreign_key
FROM really_big_table
ORDER BY id DESC
STOP WHEN created < now() - INTERVAL '1 hour'
GROUP BY foreign_key
In other words, I want the syntax so that my query will run an index scan of my table, and stop when the data is too old.