Re: Targetlist lost when CTE join <targetlist lost when CTE join>

From: Julien Rouhaud <rjuju123(at)gmail(dot)com>
To: Zhang Mingli <zmlpostgres(at)gmail(dot)com>
Cc: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: Targetlist lost when CTE join <targetlist lost when CTE join>
Date: 2023-06-28 09:17:14
Message-ID: 20230628091714.7sn52ngxnoafnn6r@jrouhaud
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

On Wed, Jun 28, 2023 at 04:52:34PM +0800, Zhang Mingli wrote:
>
> Mini repo
>
> create table t1(c1 int, c2 int);
> CREATE TABLE
> create table t2(c1 int, c2 int);
> CREATE TABLE
> explain with cte1 as (insert into t2 values (1, 2) returning *) select * from cte1 join t1 using(c1);
>  QUERY PLAN
> ----------------------------------------------------------------
>  Hash Join (cost=0.04..41.23 rows=11 width=12)
>  Hash Cond: (t1.c1 = cte1.c1)
>  CTE cte1
>  -> Insert on t2 (cost=0.00..0.01 rows=1 width=8)
>  -> Result (cost=0.00..0.01 rows=1 width=8)
>  -> Seq Scan on t1 (cost=0.00..32.60 rows=2260 width=8)
>  -> Hash (cost=0.02..0.02 rows=1 width=8)
>  -> CTE Scan on cte1 (cost=0.00..0.02 rows=1 width=8)
> (8 rows)
>
> with cte1 as (insert into t2 values (1, 2) returning *) select * from cte1 join t1 using(c1);
>  c1 | c2 | c2
> ----+----+----
> (0 rows)
>
> truncate t2;
> TRUNCATE TABLE
> with cte1 as (insert into t2 values (1, 2) returning *) select cte1.*, t1.* from cte1 join t1 using(c1);
>  c1 | c2 | c1 | c2
> ----+----+----+----
> (0 rows)
>
> Table t1 and  t2 both has 2 columns: c1, c2, when CTE join select *, the result target list seems to lost one’s column c1.
> But it looks good when select cte1.* and t1.* explicitly .
>
> Is it a bug?

This is working as intended. When using a USING clause you "merge" both
columns so the final target list only contain one version of the merged
columns, which doesn't happen if you use e.g. ON instead. I'm assuming that
what the SQL standard says, but I don't have a copy to confirm.

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Zhang Mingli 2023-06-28 09:23:59 Re: Targetlist lost when CTE join <targetlist lost when CTE join>
Previous Message Zhang Mingli 2023-06-28 08:55:09 Re: Targetlist lost when CTE join <targetlist lost when CTE join>