Re: insert into... - Mailing list pgsql-general

From Tom Lane
Subject Re: insert into...
Date
Msg-id 13128.1197223703@sss.pgh.pa.us
Whole thread Raw
In response to insert into...  ("Alain Roger" <raf.news@gmail.com>)
List pgsql-general
>
"Alain Roger" <raf.news@gmail.com> writes:
> i would like to understand why the following INSERT INTO statement works :

> INSERT INTO mytable
>    SELECT nextval('my_sequence'),
>    'myname',
>    'myfirstname'
> ;

This is a perfectly standard INSERT ... SELECT query.

> whereas usually we should do :

> INSERT INTO mytable
> VALUES
> (
>    SELECT nextval('my_sequence'),
>    'myname',
>    'myfirstname'
> );

If you'd tried that, you would find that it *does not* work:

regression=# INSERT INTO mytable
regression-# VALUES
regression-# (
regression(#    SELECT nextval('my_sequence'),
regression(#    'myname',
regression(#    'myfirstname'
regression(# );
ERROR:  syntax error at or near "SELECT"
LINE 4:    SELECT nextval('my_sequence'),
           ^

You could make it work by turning the SELECT into a parenthesized
sub-SELECT:

INSERT INTO mytable
VALUES
(
   (SELECT nextval('my_sequence')),
   'myname',
   'myfirstname'
);

but this is just pointless complexity.  The standard idiom is

INSERT INTO mytable
VALUES
(
   nextval('my_sequence'),
   'myname',
   'myfirstname'
);

or as already noted, leave out the column entirely and rely on
the default expression.

            regards, tom lane

pgsql-general by date:

Previous
From: Dave Cramer
Date:
Subject: Re: insert into...
Next
From: "x asasaxax"
Date:
Subject: Problems with acessing xml functions on other database