Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge two tables in postgresql?

Tags:

I have two tables

table 1:

name| count xxx  | 1 yyyy | 2 zzzz | 3 

table 2:

name |count xxx  | 1 aaa  | 5 

I want the resulting table to be like the following table:

name | count xxx  | 1 yyyy | 2 zzzz | 3 aaa  | 5 

Does anyone know how to do this?

like image 258
user1897937 Avatar asked Dec 28 '12 06:12

user1897937


People also ask

Does Postgres have a merge command?

PostgreSQL Merge is used to merge two table, to implement merge table we need to have unique index on table using unique index duplication record checking is easily performed. Merge table is also possible without unique index but we need to lock the table before merging two table in PostgreSQL.

How do I join two tables from another database Postgres?

Basically you just need to create the extension (requires “contrib”), declare a named connection and then use the dblink function to specify a query, including a list of output columns and their datatypes.

How do I join two tables without common column in PostgreSQL?

Using the “FROM Table1, Table2” Syntax One way to join two tables without a common column is to use an obsolete syntax for joining tables. With this syntax, we simply list the tables that we want to join in the FROM clause then use a WHERE clause to add joining conditions if necessary.


2 Answers

You should use UNION.

select * from table1 union select * from table2 

To insert into table 1:

INSERT INTO TABLE1 select * from table2      where not exists(             select * from table1                   where name=TABLE2.Name                         and count=TABLE2.Count                      ) 
like image 96
valex Avatar answered Oct 25 '22 13:10

valex


We don't need any special MERGE/UPSERT Command.

  1. To merge rows from one table into the other.

    INSERT INTO table1   (SELECT * FROM table2    WHERE name NOT IN        (SELECT name FROM table1)); 
  2. For creating new table from old tables.

    CREATE TABLE new_table AS (SELECT * FROM table1 UNION SELECT * FROM table2); 
like image 25
Sandeep Avatar answered Oct 25 '22 12:10

Sandeep