English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The PostgreSQL INSERT INTO statement is used to insert new records into a table.
We can insert one row at a time or multiple rows at the same time.
The syntax format of the INSERT INTO statement is as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1, value2, value3,...valueN);
column1, column2,...columnN is the field name in the table.
value1, value2, value3,...valueN is the value corresponding to the field.
When using the INSERT INTO statement, the number of field columns 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 can omit specifying the fields and just specify the values to be inserted:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
The following table lists the explanations of the returned results after the insertion operation:
Serial number | Output information & description |
---|---|
1 | INSERT oid 1 If only one row is inserted and the target table has an OID, then the OID is the one assigned to the inserted row. |
2 | INSERT 0 # Information returned after inserting multiple rows, # is the number of inserted rows. |
On w3Create the COMPANY table in the codeboxdb database:
w3codeboxdb=# 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:
w3codeboxdb=# 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 ignores the SALARY field:
w3codeboxdb=# 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 to set the default value for the JOIN_DATE field, rather than specifying a value:
w3codeboxdb=# 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:
w3codeboxdb=# 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 table data:
w3codeboxdb=# 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