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

Member

by daisha , in category: MySQL , 24 days ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 23 days 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.