w3resource

PostgreSQL Insert Record: Insert rows from one table to another table


6. Write a SQL statement insert rows from the country_new table to countries table.

Here are the rows for country_new table. Assume that, the countries table is empty.

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

Sample Solution:

Code:

-- This SQL statement inserts data into the 'countries' table by selecting all rows from the 'country_new' table.

INSERT INTO countries
SELECT * FROM country_new;

Explanation:

  • The INSERT INTO ... SELECT statement allows inserting data into a table by selecting rows from another table or query result.
  • In this case, countries is the destination table where the data will be inserted.
  • SELECT * FROM country_new retrieves all columns and rows from the 'country_new' table.
  • This statement effectively copies all data from the 'country_new' table and inserts it into the 'countries' table.

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 3 rows by a single insert statement.
Next: Write a SQL statement to insert one row in the jobs table to ensure that no duplicate values will be entered into the job_id column.

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://w3resource.com/postgresql-exercises/insert-record/insert-records-exercise-6.php