I don't want to aggregate any columns. I just want the newest row for each foreign key in a table.
I've tried grouping.
# column "model.id" must appear in the GROUP BY clause
# SELECT DISTINCT ON expressions must match initial ORDER BY expressions
This is known as greatest-n-per-group, and for PostgreSQL you can use
DISTINCT ON, as in your second example:
SELECT DISTINCT ON (foreign_key_id) * FROM model ORDER BY foreign_key_id, created_at DESC;
In your attempt, you were missing the
DISTINCT ON column in your
ORDER BY list, so all you had to do was: