Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a record into a table with a column declared with the SERIAL function

My database is using PostgreSQL. One table is using the serial auto-increment macro. If I want to insert a record into the table, do I still need to specify that value, or it is be automatically assigned for me?

CREATE TABLE dataset (     id serial NOT NULL,     age integer NOT NULL,     name character varying(32) NOT NULL,     description text NOT NULL DEFAULT ''::text     CONSTRAINT dataset_pkey PRIMARY KEY (id) ); 
like image 635
AntiGMO Avatar asked Oct 11 '12 09:10

AntiGMO


People also ask

How can you insert a new record into the table?

To insert records into a table, enter the key words insert into followed by the table name, followed by an open parenthesis, followed by a list of column names separated by commas, followed by a closing parenthesis, followed by the keyword values, followed by the list of values enclosed in parenthesis.

Which command is used for inserting record?

The INSERT INTO statement is used to insert new records in a table.

What is the SQL clause for inserting a record to a table?

The SQL INSERT statement is used to insert a one or more records into a table.


2 Answers

Using the DEFAULT keyword or by omitting the column from the INSERT list:

INSERT INTO dataset (id, age, name, description) VALUES (DEFAULT, 42, 'fred', 'desc');  INSERT INTO dataset (age, name, description) VALUES (42, 'fred', 'desc'); 
like image 66
Craig Ringer Avatar answered Oct 24 '22 05:10

Craig Ringer


If you create a table with a serial column then if you omit the serial column when you insert data into the table PostgreSQL will use the sequence automatically and will keep the order.

Example:

skytf=> create table test_2 (id serial,name varchar(32)); NOTICE:  CREATE TABLE will create implicit sequence "test_2_id_seq" for serial column "test_2.id" CREATE TABLE  skytf=> insert into test_2 (name) values ('a'); INSERT 0 1 skytf=> insert into test_2 (name) values ('b'); INSERT 0 1 skytf=> insert into test_2 (name) values ('c'); INSERT 0 1  skytf=> select * From test_2;  id | name  ----+------   1 | a   2 | b   3 | c (3 rows) 
like image 35
francs Avatar answered Oct 24 '22 05:10

francs