Optimeze Postgres query : Table with two columns (transaction_id, user_id), both with index. Approx 10M records in table.

transaction_id is unique

transaction_id count on user_id varies from very few to thousands.

What I need is to find the max(transaction_id), with respect to that the top25 transaction_id's on a given user must be ignored.

Eg a user_id with 21 transaction_id's will not be selected. A user_id with 47 transactions will return transction 26.

I have tried several ways by using offset, limit etc, but they all seem to be to slow (very high cost).

Help is very appriciated :)
