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

From Michael Glaesemann
Subject Re: insert into...
Date
Msg-id 7AD7D2CB-A7E4-48BD-8D1A-2E988AB3FE63@seespotcode.net
Whole thread Raw
In response to insert into...  ("Alain Roger" <raf.news@gmail.com>)
List pgsql-general
On Dec 9, 2007, at 11:05 , Alain Roger wrote:

> Hi,
>
> i would like to understand why the following INSERT INTO statement
> works :
>
> INSERT INTO mytable
>    SELECT nextval('my_sequence'),
>    'myname',
>    'myfirstname'
> ;
>
> whereas usually we should do :
>
> INSERT INTO mytable
> VALUES
> (
>    SELECT nextval('my_sequence'),
>    'myname',
>    'myfirstname'
> );
>

Well, imho, if the sequence was set up via serial (or otherwise is
set as the default for the first column), I think the easiest way is :

INSERT INTO mytable (name, firstname)
   VALUES ('myname', 'myfirstname');

No need to include the nextval call at all.

If you look at the INSERT synoposis:

http://www.postgresql.org/docs/8.2/static/sql-insert.html

INSERT INTO table [ ( column [, ...] ) ]
     { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] )
[, ...] | query }
     [ RETURNING * | output_expression [ AS output_name ] [, ...] ]

you can see that a VALUES expression or a query are legitimate forms
for INSERT. The query form is particularly useful if you'd like to
insert a number of rows that are the result of a SELECT. For example,
when loading data from a temp table.

INSERT INTO mytable (name, firstname)
   SELECT name, firstname
      FROM temp_table;

Michael Glaesemannn
grzm seespotcode net



pgsql-general by date:

Previous
From: "Alain Roger"
Date:
Subject: insert into...
Next
From: Dave Cramer
Date:
Subject: Re: insert into...