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?
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,...)
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:
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:
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, ...)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With