Re: insert into...

From: Michael Glaesemann <grzm(at)seespotcode(dot)net>
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 16:41:47
Message-ID: 7AD7D2CB-A7E4-48BD-8D1A-2E988AB3FE63@seespotcode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Dave Cramer 2007-12-09 17:02:03 Re: insert into...
Previous Message Alain Roger 2007-12-09 16:05:15 insert into...