Open In App

PostgreSQL – INSERT

In PostgreSQL, the INSERT statement is used to add new rows to a database table. As one creates a new database, it has no data initially. PostgreSQL provides the INSERT statement to insert data into the database.

Syntax:
INSERT INTO table(column1, column2, …)
VALUES
    (value1, value2, …);

The below rules must be followed while using the PostgreSQL INSERT statement:



Let’s set up a sample database and table for the demonstration of INSERT statement.

Example 1:
Here we will add some employee data to the table using the below command:



INSERT INTO employee (
    employee_id,
    first_name,
    last_name,
    manager_id
)
VALUES
    (1, 'Sandeep', 'Jain', NULL),
    (2, 'Abhishek ', 'Kelenia', 1),
    (3, 'Harsh', 'Aggarwal', 1),
    (4, 'Raju', 'Kumar', 2),
    (5, 'Nikhil', 'Aggarwal', 2),
    (6, 'Anshul', 'Aggarwal', 2),
    (7, 'Virat', 'Kohli', 3),
    (8, 'Rohit', 'Sharma', 3);

Output:
Use the below command to verify the inserted data:

SELECT * FROM employee;


The overall hierarchy looks like the below image:

Example 2:
In the above example we inserted multiple rows to the company database, whereas in this example we will add a single row to the database.

INSERT INTO employee (
    employee_id,
    first_name,
    last_name,
    manager_id
)
VALUES
    (9, 'Mohit', 'Verma', 3);
Output:

Now check for the newly added employee using the below command:

SELECT * FROM employee;


Now the overall hierarchy looks like the below image:

Article Tags :