Search Postgresql Archives

Re: insert into...

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




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



---------------------------(end of broadcast)---------------------------
TIP 6: explain analyze is your friend

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux