Re: INSERT ... SELECT problem in Mysql - Mailing list pgsql-sql

From Tom Lane
Subject Re: INSERT ... SELECT problem in Mysql
Date
Msg-id 8818.1057355146@sss.pgh.pa.us
Whole thread Raw
In response to INSERT ... SELECT problem in Mysql  (Evil Azrael <evilazrael@evilazrael.de>)
Responses Re: INSERT ... SELECT problem in Mysql  (Evil Azrael <evilazrael@evilazrael.de>)
List pgsql-sql
Evil Azrael <evilazrael@evilazrael.de> writes:
> I have a problem with this part in the text
> ----
> The target table of the INSERT statement cannot appear in the FROM
> clause of the SELECT part of the query because it's forbidden in
> standard SQL to SELECT from the same table into which you are
> inserting.

This is just MySQL's self-serving reading of the spec.  What SQL92
actually says is (section 13.8)
        1) The following restrictions apply for Intermediate SQL:
           a) The leaf generally underlying table of T shall not be gen-             erally contained in the <query
expression>immediately             contained in the <insert columns and source> except as the             <qualifier>
ofa <column reference>.
 

SQL99 puts it a little differently:
        Conformance Rules
        1) Without Feature F781, "Self-referencing operations", no leaf           generally underlying table of T shall
begenerally contained in           the <query expression> immediately contained in the <insert           columns and
source>except as the <table or query name> or           <correlation name> of a column reference.
 

In other words, the behavior is perfectly standard, it's just not
required for minimal SQL implementations to support it.

What the standard behavior is is defined by this rule, earlier in the
same section:
        3) The <query expression> is effectively evaluated before inserting           any rows into B.

that is, the SELECT doesn't see any rows that are being inserted into
the target table during the same command.  There would not be any need
for that rule if selecting from the same table you're inserting into
were flat-out forbidden, as the MySQL docs claim.
        regards, tom lane


pgsql-sql by date:

Previous
From: Evil Azrael
Date:
Subject: INSERT ... SELECT problem in Mysql
Next
From: Evil Azrael
Date:
Subject: Re: INSERT ... SELECT problem in Mysql