Re: Equivalence of CROSS JOIN and comma

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Adam Mackler <pgsql-novice(at)mackler(dot)org>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Equivalence of CROSS JOIN and comma
Date: 2012-10-15 13:52:37
Message-ID: 8177.1350309157@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Adam Mackler <pgsql-novice(at)mackler(dot)org> writes:
> The PostgreSQL manual [1] reads in part:
> "FROM T1 CROSS JOIN T2 is equivalent to FROM T1, T2."

That's true as far as it goes ...

> Yet here are two statements that are identical to each other except
> that one has a CROSS JOIN where the other has a comma:

> WITH t1 (val) AS ( VALUES (1) ),
> t2 (name) AS ( VALUES ('foo') ),
> t3 (num) AS ( VALUES (1) )
> SELECT * FROM t1 CROSS JOIN t2 JOIN t3 ON num=val;

> WITH t1 (val) AS ( VALUES (1) ),
> t2 (name) AS ( VALUES ('foo') ),
> t3 (num) AS ( VALUES (1) )
> SELECT * FROM t1, t2 JOIN t3 ON num=val;

> and one works but the other doesn't.

The issue there is that JOIN binds tighter than comma. The first one
means

((t1 CROSS JOIN t2) JOIN t3 ON num=val)

and the second one means

t1, (t2 JOIN t3 ON num=val)

which is equivalent to

(t1 CROSS JOIN (t2 JOIN t3 ON num=val))

so the reference to t1.val fails because t1 isn't part of the JOIN that
the ON condition is attached to.

People migrating from MySQL tend to get this wrong because MySQL gets it
wrong :-(, or at least it did in older versions --- I've not checked it
lately. The SQL standard is perfectly clear about this though.

regards, tom lane

In response to

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message groberge 2012-10-15 17:52:16 Beginner's question about ODBC and/or foreign data sources
Previous Message Adam Mackler 2012-10-15 04:39:35 Equivalence of CROSS JOIN and comma