CREATE SCHEMA issue_6872;
SET search_path to 'issue_6872';

CREATE TABLE ref0(id int);
SELECT create_reference_table('ref0');

CREATE TABLE ref1(id int);
SELECT create_reference_table('ref1');

CREATE TABLE dist0(id int);
SELECT create_distributed_table('dist0','id');

CREATE TABLE dist1(id int);
SELECT create_distributed_table('dist1','id');

INSERT INTO dist0 SELECT i FROM generate_series(0,10) i;
INSERT INTO dist0 SELECT i FROM generate_series(1005,1025) i;
INSERT INTO dist0 SELECT * FROM dist0 ORDER BY id LIMIT 1;

INSERT INTO ref0 SELECT i FROM generate_series(0,10) i;
INSERT INTO ref0 SELECT i FROM generate_series(1010,1030) i;
INSERT INTO ref0 SELECT NULL FROM generate_series(0,1) i;
INSERT INTO ref0 SELECT * FROM ref0 ORDER BY id LIMIT 1;

INSERT INTO dist1 SELECT i FROM generate_series(0,10) i;
INSERT INTO dist1 SELECT i FROM generate_series(1015,1035) i;
INSERT INTO dist1 SELECT * FROM dist1 ORDER BY id LIMIT 1;

INSERT INTO ref1 SELECT i FROM generate_series(0,10) i;
INSERT INTO ref1 SELECT i FROM generate_series(1020,1040) i;
INSERT INTO ref1 SELECT NULL FROM generate_series(0,1) i;
INSERT INTO ref1 SELECT * FROM ref1 ORDER BY id LIMIT 1;

-- added to verify we fixed the issue https://github.com/citusdata/citus/issues/6872
-- generated by Citus query generator tool
WITH cte_0 AS (
  SELECT 
    table_0.id 
  FROM 
    dist0 AS table_0 
    INNER JOIN ref0 AS table_1 USING (id) 
  ORDER BY 
    id
) 
SELECT 
  avg(avgsub.id) 
FROM 
  (
    SELECT 
      table_2.id 
    FROM 
      (
        SELECT 
          table_3.id 
        FROM 
          cte_0 AS table_3 
        ORDER BY 
          id
      ) AS table_2 
    WHERE 
      table_2.id IN (
        SELECT 
          table_4.id 
        FROM 
          dist0 AS table_4 
          RIGHT JOIN (
            SELECT 
              table_6.id 
            FROM 
              dist0 AS table_6 
              INNER JOIN ref1 AS table_7 USING (id) 
            ORDER BY 
              id 
            LIMIT 
              28
          ) AS table_5 USING (id) 
          RIGHT JOIN dist1 AS table_8 USING (id) 
        WHERE 
          table_8.id = 6 
        ORDER BY 
          id
      )
  ) AS avgsub;

DROP SCHEMA issue_6872 CASCADE;
