What is Insert query in PostgreSQL?

Insert is one of the commands of PostgreSQL that allows you to insert single or multiple rows in the table of your database.

Syntax

INSERT INTO tablename
(column1, column2, column3, column4...columnN)
VALUES
(value1, value2, value3, value4,...valueN)

Parameters

tablename: This specifies the name of the table in which you need to insert a row.

column 1,..column N: This specifies the columns in which you need to insert the values.

value 1,...value N: This specifies the values that need to be inserted in the mentioned columns.

Code

Suppose you have the following table of people working in your business, who you have named as users in your database:

CNIC  NAME  DOB   CITY 
3513  sam   1992  seattle
3521  tom   1995  paris

You want to insert a new person in your table. Here is how:

INSERT INTO users
(cnic, name, dob, city)
VALUES
(35202, 'john', '1998', 'venice')

The above query will add a new person in your above table.

The new table will look like:

CNIC  NAME  DOB   CITY 
3513  sam   1992  seattle
3521  tom   1995  paris
35202 john  1998  venice

Inserting a row using DEFAULT VALUES

It is not necessary to always provide new values while inserting a row. You can also insert a new row by simply adding the default values of each column in the row.

The insert query for the default values will look like this:

INSERT INTO tablename
(column1, column2, ... columnN)
DEFAULT VALUES

Inserting a row using SUBQUERY

We can insert a row or multiple rows into a table by using subquery.

The syntax for it will be:

INSERT INTO tablename
(column1, column2)
SELECT column1, column2
FROM tablename2
WHERE expression

Free Resources