w3resource

PostgreSQL Insert Record: Insert a specific number of rows by a single insert statement


5. Write a SQL statement to insert 3 rows by a single insert statement.

Sample Solution:

Code:

-- This SQL statement inserts multiple new rows into the 'countries' table with specified values.

INSERT INTO countries 
VALUES
    ('C4','India',1001),  -- Inserting a row with country_id='C4', country_name='India', and region_id=1001
    ('C5','USA',1007),    -- Inserting a row with country_id='C5', country_name='USA', and region_id=1007
    ('C6','UK',1003);     -- Inserting a row with country_id='C6', country_name='UK', and region_id=1003

Explanation:

  • The INSERT INTO statement is used to add new rows into a table.
  • countries is the name of the table where the new rows will be inserted.
  • Each set of values enclosed in parentheses (country_id, country_name, region_id) represents a single row to be inserted into the table.
  • The values provided correspond to the columns of the table in the order they appear in the table's schema. In this case, 'C4' is inserted into the 'country_id' column, 'India' into the 'country_name' column, and 1001 into the 'region_id' column for the first row, 'C5' into 'country_id', 'USA' into 'country_name', and 1007 into 'region_id' for the second row, and 'C6' into 'country_id', 'UK' into 'country_name', and 1003 into 'region_id' for the third row.

Here is the command to see the list of inserting rows :

postgres=# SELECT * FROM countries;

 country_id | country_name | region_id
------------+--------------+-----------
 C1         | India        |      1002
 C2         | USA          |
 C3         | UK           |
 C4         | India        |      1001
 C5         | USA          |      1007
 C6         | UK           |      1003
(6 rows)

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a SQL statement to insert NULL values into region_id column for a row of countries table.
Next: Write a SQL statement insert rows from the country_new table to countries table.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/postgresql-exercises/insert-record/insert-records-exercise-5.php