Aren't CTEs still optimization barriers in Postgres, so wouldn't that make any subquert optimization problem worse?
I'm surprised that the problem stemmed from an index where the 'AND NOT NULL' took forevery to scan, and they didn't include a partial index, or an index in a different order since they are sorted.
[0] https://www.depesz.com/2019/02/19/waiting-for-postgresql-12-...
As a silly example, if the CTE materializes 1/100th of a table via table scan, scanning 1/100th of a table N times may be faster than scanning the entire table N times.