Site icon JD Bots

How to Insert a Row in PostgreSQL

Featured card for How to Insert a Row in PostgreSQL, with a terminal window listing INSERT INTO contacts, (name, phone), VALUES (‘Ana’, …) and INSERT 0 1.

How to insert a row in PostgreSQL.

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

Syntax

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

See INSERT 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:

Terminal

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:

postgres=#

CREATE DATABASE addressbook;

Output

CREATE DATABASE

postgres=#

\c addressbook

Output

You are now connected to database "addressbook" as user "postgres".

Create the table:

addressbook=#

CREATE TABLE contacts (name text, phone text);

Output

CREATE TABLE

Step 2: Insert a Row

addressbook=#

INSERT INTO contacts (name, phone) VALUES ('Ana', '555-0100');

Output

INSERT 0 1

INSERT 0 1 means one row was inserted. The 0 is always 0 nowadays.

Step 3: Insert Only Some Columns

addressbook=#

INSERT INTO contacts (name) VALUES ('Ben');

Output

INSERT 0 1

Ben has no phone number, so that column stays empty. See both rows:

addressbook=#

SELECT * FROM contacts;

Output

 name |  phone
------+----------
 Ana  | 555-0100
 Ben  |
(2 rows)

Clean Up

To remove the example, connect to another database and drop the test database:

addressbook=#

\c postgres

Output

You are now connected to database "postgres" as user "postgres".

postgres=#

DROP DATABASE addressbook;

Output

DROP DATABASE

Warning: DROP DATABASE deletes the database and everything in it, and it can’t be undone.

Common Mistakes

MistakeWhat happensDo this instead
More values than columnsERROR: INSERT has more expressions than target columnsGive exactly one value for each column you list.
Leaving out the column listThe 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.

Exit mobile version