Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PostgreSQL INSERT INTO Statement

PostgreSQL INSERT INTO Statement

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

We can insert a single row or multiple rows at the same time.

Syntax

The syntax of the INSERT INTO statement is as follows:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)

VALUES (value1, value2, value3,...valueN);

When using the INSERT INTO statement, the number of column fields must be the same as the number of data values, and the order must correspond.

If we insert values into all fields of the table, we do not need to specify the fields, only the values to be inserted:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

The following table describes the results returned after performing an insert:

No. Output Message & Description
1

INSERT oid 1

When only one row is inserted and the target table has OIDs, the returned oid is the OID assigned to the inserted row.

2

INSERT 0 #

Information returned when multiple rows are inserted; # is the number of inserted rows.

Example

Create the COMPANY table in the runoobdb database:

runoobdb=# CREATE TABLE COMPANY(

   ID INT PRIMARY KEY     NOT NULL,

   NAME           TEXT    NOT NULL,

   AGE            INT     NOT NULL,

   ADDRESS        CHAR(50),

   SALARY         REAL,

   JOIN_DATE      DATE

);

Insert the following data into the COMPANY table:

runoobdb=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY,JOIN_DATE) VALUES (1, 'Paul', 32, 'California', 20000.00,'2001-07-13');

INSERT 0 1

The following insert statement omits the SALARY field:

runoobdb=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,JOIN_DATE) VALUES (2, 'Allen', 25, 'Texas', '2007-12-13');

INSERT 0 1

In the following insert statement, the JOIN_DATE field uses a DEFAULT clause to set the default value instead of specifying a value:

runoobdb=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY,JOIN_DATE) VALUES (3, 'Teddy', 23, 'Norway', 20000.00, DEFAULT );

INSERT 0 1

The following example inserts multiple rows:

runoobdb=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY,JOIN_DATE) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00, '2007-12-13' ), (5, 'David', 27, 'Texas', 85000.00, '2007-12-13');

INSERT 0 2

Use the SELECT statement to query the table data:

runoobdb=# SELECT * FROM company;



ID        NAME        AGE        ADDRESS     SALARY   JOIN_DATE

----      ----------  -----      ----------  -------      --------

1         Paul        32         California  20000.0      2001-07-13

2         Allen       25         Texas                    2007-12-13

3         Teddy       23         Norway      20000.0

4         Mark        25         Rich-Mond   65000.0      2007-12-13

5         David       27         Texas       85000.0      2007-12-13