Postgres: left join with order by and limit 1

Use a dependent subquery with max() function in a join condition.
Something like in this example:

FROM companies c
LEFT JOIN relationship r
ON c.company_id = r.company_id
   AND r."begin" = (
        SELECT max("begin")
        FROM relationship r1
        WHERE c.company_id = r1.company_id
INNER JOIN addresses a
ON a.address_id = r.address_id 


Leave a Comment