i have this query to get 5 latest post of each user. it works fine on small amount of data. but on live where i have millions of data. it's not very fast. it's taking too long. if anyone have idea to optimize the query so it's fast on large amount of data.
select p.*
from posts p
where p.id >= (select p2.id
from posts p2
where p2.user_id = p.user_id
order by p2.id desc
limit 1 offset 4
)
order by p.user_id ;