INSERT INTO adds a row to a table in PostgreSQL: name the table and its columns, then give the values in the same order. Here’s how to insert a row, with a small address book.
Every command and output on this page is real, from PostgreSQL 19 on macOS.
Syntax
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
table_name: the table to add the row to.(column1, column2, ...): the columns you’re giving values for. Columns you leave out get their default, which is empty (NULL) unless the table says otherwise.VALUES (...): the values, in the same order as the columns. Text goes in single quotes.
See INSERT (opens in a new tab) in the PostgreSQL documentation.
The Example
An address book with a name and a phone number for each contact.
Step 1: Create a Test Database
Open Terminal and connect to your PostgreSQL server with psql as the postgres user:
psql -U postgres
Type the user’s password when psql asks for it. psql connects you to the postgres database, and its prompt is postgres=#.
Create a database for the example and connect to it:
CREATE DATABASE addressbook;
CREATE DATABASE
\c addressbook
You are now connected to database "addressbook" as user "postgres".
Create the table:
CREATE TABLE contacts (name text, phone text);
CREATE TABLE
Step 2: Insert a Row
INSERT INTO contacts (name, phone) VALUES ('Ana', '555-0100');
INSERT 0 1
INSERT 0 1 means one row was inserted. The 0 is always 0 nowadays.
Step 3: Insert Only Some Columns
INSERT INTO contacts (name) VALUES ('Ben');
INSERT 0 1
Ben has no phone number, so that column stays empty. See both rows:
SELECT * FROM contacts;
name | phone
------+----------
Ana | 555-0100
Ben |
(2 rows)
Clean Up
To remove the example, connect to another database and drop the test database:
\c postgres
You are now connected to database "postgres" as user "postgres".
DROP DATABASE addressbook;
DROP DATABASE
Warning: DROP DATABASE deletes the database and everything in it, and it can’t be undone.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| More values than columns | ERROR: INSERT has more expressions than target columns | Give exactly one value for each column you list. |
| Leaving out the column list | The values fill the columns in the table’s order, so one can land in the wrong column without an error. | Always list the columns. |
FAQ
Why are the phone numbers in quotes?
They’re text: a phone number can start with 0 or contain a dash, and nobody adds them up.
Conclusion
INSERT INTO, the table, its columns and VALUES add a row. Columns you leave out stay empty.
Additional Resources
Postgres, PostgreSQL and the Slonik Logo are trademarks or registered trademarks of the PostgreSQL Community Association of Canada, and used with their permission.
0 comments