In my application every time I send a newsletter to a User, I create a NewsletterDelivery record. I frequently want to be able to query, for each user, what is the most recent newsletter delivery record. This is called a "last n per group" query and a LATERAL JOIN
is the best way to do it imo. But the query I've been using (and I've told people to use, and seen blogged about) is not very good, because the conditions don't get pushed down into the subselect which means that the query ends-up lateral-joining all the records before it applies the conditions for the association.
Instead of doing subselect_table.*
the better query does association.id AS assocation_id, subselect_table.id, subselect_table.title, ....
and enumerates over all of the columns. This allows the association query, which Active Record tacks on at the end as WHERE association_id = $1
or WHERE association_id IN ($1, $2, $3, ...)
to be pushed down c