I would combine DISTINCT ON
with NOT EXISTS
.
Assuming a proper boolean
type for active:
SELECT DISTINCT ON (user_id)
id, user_id, name, active
FROM profiles p
WHERE NOT EXISTS (
SELECT 1 FROM profiles
WHERE user_id = p.user_id
AND active -- exclude users with any active profiles
)
ORDER BY user_id, id DESC;
Probably fastest and cleanest.