The query burns down to just:
SELECT *
FROM (
SELECT DISTINCT ON (initial_record_id)
FROM marketplace_messages
ORDER BY initial_record_id, id DESC
) sub
ORDER BY id DESC;
The tricky bit is that leading ORDER BY
expressions must cover DISTINCT ON
expressions. So sort a second time in the outer query.
See: