Question

I am working with Postgresql database. I have one database which is - db1 and I have one table inside this database which is App1.

I need to make a select query against this App1 table which is in db1 and then whatever results I am getting back, I need to insert them in App2 table as it is which is in another database db2.

Below is my query which I am running against App1 table which is in db1 -

select col1, col2 from App1 limit 5

Now is there any way I can use Insert statement along with above SELECT statement which can insert into App2 table for me automatically which is in db2?

Something along this line -

Insert into … values ( SELECT … FROM … )

Is this possible to do in Postgresql as both the tables are in different database?

Was it helpful?

Solution

To do this between databases you must use the foreign data wrapper postgres_fdw or use dblink. See the documentation. PostgreSQL doesn't support cross-database SELECT.

Often, if you find yourself wanting to do this, you should be using separate schemas in a single database instead.


BTW, it's generally:

INSERT INTO ... SELECT ...

i.e. there's no subquery, no parentheses. That's because the VALUES clause is actually a standalone statement too:

INSERT INTO ... VALUES ...

observe:

regress=> VALUES (1,2), (2,3);
 column1 | column2 
---------+---------
       1 |       2
       2 |       3
(2 rows)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top