SET log_error_verbosity = verbose;
drop table if exists r;
create table r
(
	a  int, 
	ts int, 
	te int
);
insert into r values
(1,1,8), 
(2,2,6), 
(1,8,12),
(3,10,15),
(2,5,9);
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
insert into r select (select max(a) from r) + a a, (select max(ts) from r) + ts, (select max(te) from r) + te from r;
set enable_mergejoin=false;
create index r_a_index on r (a);
explain select * from (	r align r r2 on r.a=r2.a with (ts,te,ts,te) ) x;
                                           QUERY PLAN                                           
------------------------------------------------------------------------------------------------
 Subquery Scan on x  (cost=20626.82..25578.41 rows=174762 width=12)
   ->  Adjustment(for ALIGN)  (cost=20626.82..23830.79 rows=174762 width=28)
         ->  Sort  (cost=20626.82..20772.46 rows=58254 width=28)
               Sort Key: (row_number() OVER (?)), (GREATEST(r.ts, r2.ts)), (LEAST(r.te, r2.te))
               ->  Nested Loop Left Join  (cost=0.29..16016.00 rows=58254 width=28)
                     ->  WindowAgg  (cost=0.00..286.40 rows=10240 width=12)
                           ->  Seq Scan on r  (cost=0.00..158.40 rows=10240 width=12)
                     ->  Index Scan using r_a_index on r r2  (cost=0.29..1.47 rows=6 width=12)
                           Index Cond: (r.a = a)
                           Filter: ((r.ts < te) AND (r.te > ts))
(10 rows)

