Re: insert into...

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Alain Roger" <raf(dot)news(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: insert into...
Date: 2007-12-09 18:08:23
Message-ID: 13128.1197223703@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

>
"Alain Roger" <raf(dot)news(at)gmail(dot)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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message x asasaxax 2007-12-09 19:34:50 Problems with acessing xml functions on other database
Previous Message Vyacheslav Kalinin 2007-12-09 17:58:08 Re: Pg_catalog reference