\set ON_ERROR_STOP 1
\set ON_ERROR_ROLLBACK 1
rollback;
begin;
\ir pb-dump.sql
set search_path to public;

analyze foo;
analyze qux;
analyze baz;
analyze bar;
analyze baz_details;
set parallel_setup_cost to 9999999999;
set work_mem to '100MB';
--set enable_nestloop to off; set enable_mergejoin to off;

explain
SELECT foo.id,
       qux.id
FROM foo
LEFT JOIN qux ON qux.foo_id = foo.id
WHERE foo.tags LIKE '%foo%'
  AND foo.is_cursed
  AND (
       EXISTS (
               SELECT 1
               FROM baz
               JOIN bar ON bar.id = baz.bar_id
               JOIN baz_details bazd ON bazd.id = baz.id
               WHERE bazd.is_cool
                 AND bar.foo_id = foo.id
           )
       OR EXISTS (
               SELECT 1
               FROM baz
               JOIN bar ON bar.id = baz.bar_id
               JOIN baz_details bazd ON bazd.id = baz.id
               WHERE bazd.is_cool is not false
                 AND bar.foo_id = foo.id
           )
      );

explain analyze
SELECT foo.id,
       qux.id
FROM foo
LEFT JOIN qux ON qux.foo_id = foo.id
WHERE foo.tags LIKE '%foo%'
  AND foo.is_cursed
  AND (
       EXISTS (
               SELECT 1
               FROM baz
               JOIN bar ON bar.id = baz.bar_id
               JOIN baz_details bazd ON bazd.id = baz.id
               WHERE bazd.is_cool
                 AND bar.foo_id = foo.id
           )
       OR EXISTS (
               SELECT 1
               FROM baz
               JOIN bar ON bar.id = baz.bar_id
               JOIN baz_details bazd ON bazd.id = baz.id
               WHERE bazd.is_cool is not false
                 AND bar.foo_id = foo.id
           )
      );
