I want to run this query:
SELECT DISTINCT ON (address_id) purchases.address_id, purchases.*
FROM purchases
WHERE purchases.product_id = 1
ORDER BY purchases.purchased_at DESC
But I get this error:
PG::Error: ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
Adding address_id
as first ORDER BY
expression silences the error, but I really don't want to add sorting over address_id
. Is it possible to do without ordering by address_id
?
Best Answer
Documentation says:
Official documentation
So you'll have to add the
address_id
to the order by.Alternatively, if you're looking for the full row that contains the most recent purchased product for each
address_id
and that result sorted bypurchased_at
then you're trying to solve a greatest N per group problem which can be solved by the following approaches:The general solution that should work in most DBMSs:
A more PostgreSQL-oriented solution based on @hkf's answer:
Problem clarified, extended and solved here: Selecting rows ordered by some column and distinct on another