PostgreSQL INSERT INTO Statement
The PostgreSQL INSERT INTO statement is used to insert new records into a table.
We can insert either a single row or multiple rows at once.
Syntax
The syntax for the INSERT INTO statement is as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
- column1, column2,...columnN are the names of the fields in the table.
- value1, value2, value3,...valueN are the values corresponding to the fields.
When using the INSERT INTO statement, the number of columns must match the number of data values, and the order must also be consistent.
If we are inserting values into all fields of the table, we can omit specifying the fields and only specify the values:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
The following table lists the descriptions of the results returned after executing the insert operation:
No. | Output Message & Description |
---|---|
1 | INSERT oid 1 This message is returned if only one row is inserted and the target table has OIDs, where oid is the OID assigned to the inserted row. |
2 | INSERT 0 # This message is returned when multiple rows are inserted, where # is the number of inserted rows. |
Example
Create a COMPANY table in the tutorialprodb database:
tutorialprodb=# 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:
tutorialprodb=# 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:
tutorialprodb=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,JOIN_DATE) VALUES (2, 'Allen', 25, 'Texas', '2007-12-13');
INSERT 0 1
The following insert statement uses the DEFAULT clause for the JOIN_DATE field to set a default value instead of specifying a value:
tutorialprodb=# 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:
tutorialprodb=# 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
Query the table data using the SELECT statement:
tutorialprodb=# 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