6

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?

5
  • 1
    really? is it so very hard to look at the postgres docs? postgresql.org/docs/8.1/static/sql-insert.html Commented Mar 3, 2014 at 4:49
  • @MarcB: But both of the tables are in different database so this will still work? Commented Mar 3, 2014 at 4:50
  • as long as the user you're running this under has the appropriate rights, postgres won't care. Commented Mar 3, 2014 at 4:51
  • select db1.table1.field, db2.table2.otherfield is perfectly legitimate SQL in pretty much any sql database worth using. Commented Mar 3, 2014 at 4:51
  • @MarcB: please don't link to outdated versions (you can use current instead of the version number in the URL) Commented Mar 3, 2014 at 7:04

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for suggestion.. So what should I do for my use case? Should I get the data from db1 and put it in response object and then iterate the object and then insert into db2?
You can do it via the client side as you describe, or you can use dblink or postgres_fdw, as I linked to above, to do it via an INSERT INTO ... SELECT query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.