Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into … values ( SELECT … FROM … ) in postgresql?

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?

like image 716
AKIWEB Avatar asked Mar 03 '14 04:03

AKIWEB


People also ask

How do I insert data into another table in PostgreSQL?

PostgreSQL INSERT INTO table from another table You can populate data into a table from another table in PostgreSQL by using a SELECT statement with the INSERT INTO statement for specifying the values to the columns. The syntax is as follows: INSERT INTO table1 (primary_key_column1, column11, column12,...)

How to insert into table if not exists in PostgreSQL?

This is how to insert into table if not exists in PostgreSQL. You can populate data into a table in PostgreSQL by using a SELECT query to select the data from some table to be returned as the VALUES in the INSERT INTO statement. The syntax is as follows:

How do I insert data into a PostgreSQL table with auto increment?

PostgreSQL INSERT INTO table with auto_increment You can insert data into a table having a column auto_increment by using the DEFAULT keyword in place of the value in the value-list corresponding to the autoincrement column in the column list in the INSERT INTO statement. The syntax is as follow:

How to use upsert in PostgreSQL?

You can use UPSERT in PostgreSQL by adding the ON CONFLICT clause in the INSERT INTO statement to perform the task. The syntax is as follow: INSERT INTO table_name (column1, column2, ...)


1 Answers

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)
like image 99
Craig Ringer Avatar answered Sep 22 '22 09:09

Craig Ringer