How to insert values from two tables into one in postgresql?

Member

by daisha , in category: MySQL , 8 months ago

How to insert values from two tables into one in postgresql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 8 months ago

@daisha 

To insert values from two tables into one in PostgreSQL, you can use the INSERT INTO SELECT statement. Here's an example:


Assuming you have two tables table1 and table2 with columns col1 and col2 respectively, and you want to insert values from both tables into a new table called combined_table with columns col1 and col2, you can use the following SQL query:

1
2
3
4
INSERT INTO combined_table (col1, col2)
SELECT col1, col2 FROM table1
UNION
SELECT col1, col2 FROM table2;


In this query:

  • INSERT INTO combined_table (col1, col2) specifies the table and the columns you want to insert the values into.
  • SELECT col1, col2 FROM table1 and SELECT col1, col2 FROM table2 are selecting the columns from each of the tables.
  • UNION is used to combine the results of the two SELECT queries into a single result set.


After running this query, the values from both table1 and table2 will be inserted into the combined_table.

Related Threads:

How to join two tables and group items based on latest date on postgresql?
How to count unique values across two columns with certain types in postgresql?
How to query from one to many tables in mysql?
How to join 3 tables in postgresql via with statement?
How to get values for time intervals of hours in one day in sparql?
How to work with more than one pivot tables in laravel?