Post­gr­eSQL’s INSERT INTO is used to add one or more new rows to a table. When adding rows, you also need to add values for the cor­res­pond­ing columns as well.

What is the INSERT INTO command in Post­gr­eSQL?

The INSERT INTO command allows you to add new rows to a table in Post­gr­eSQL. You can either insert a single row or multiple rows at once. When using the INSERT command in Post­gr­eSQL, you need to specify which columns you want to insert data into as well as the cor­res­pond­ing values.

What is the syntax for Post­gr­eSQL’s INSERT command?

The basic syntax of INSERT INTO is as follows:

INSERT INTO table_name (column1, column2, column3, …, columnN)
VALUES (value1, value2, value3, …, valueN);
post­gr­esql

When using Post­gr­eSQL’s INSERT INTO, you first need to identify the table where the rows should be added. Then, list the columns you want to update. If you’re adding values for all the columns in the table, you don’t have to specify the columns. Here’s what the syntax looks like:

INSERT INTO table_name
VALUES (value1, value2, value3, …, valueN);
post­gr­esql

The values must be entered in the correct order, matching the sequence of the table’s columns from left to right.

Post­gr­eSQL INSERT INTO example

Here’s an example of how Post­gr­eSQL INSERT INTO works in practice. First, we’re going to create a table named customer_list with four columns: id, name, city and address. Here’s how to do this:

CREATE TABLE customer_list(
id INT PRIMARY KEY NOT NULL,
name VARCHAR(50) NOT NULL,
city VARCHAR(50),
address VARCHAR(255)
);
post­gr­esql

To add a row to this table, use the Post­gr­eSQL INSERT INTO command as shown below:

INSERT INTO customer_list (id, name, city, address)
VALUES (1, 'Smith', 'London', '123 High Street');
post­gr­esql

In the next example, we don’t know the customer’s address, so we’re going to leave this field empty. The default value that is defined in the table will be used. If a default value hasn’t been set, NULL will be used. Here’s the code:

INSERT INTO customer_list (id, name, city)
VALUES (2, 'Johnson', 'Glasgow');
post­gr­esql

Adding multiple rows with Post­gr­eSQL INSERT

Post­gr­eSQL also allows you to add multiple rows at once using the INSERT command. Here’s how to insert two customers at the same time:

INSERT INTO customer_list (id, name, city, address)
VALUES 
(3, 'Williams', 'Cardiff', '45 Oak Avenue'), 
(4, 'Brown', 'Southampton', '78 Pine Road');
post­gr­esql

Each row is enclosed in brackets and separated by commas.

Tip

If you need to delete a row, you can use the Post­gr­eSQL DELETE command.

Go to Main Menu