Breaking out of a recursive query in Postgres 11
WITH RECURSIVE cte AS (
SELECT id, domain_name, valid
FROM domains
WHERE parent_id IS NULL
UNION ALL
SELECT domains.id, domains.domain_name, domains.valid
FROM domains
JOIN cte ON domains.parent_id = cte.id
WHERE NOT cte.valid -- stop recursion when valid node reached
)
SELECT id, domain_name
FROM cte
WHERE valid
fiddle