Distributed - across multiple databases or servers - Transactions I have some doubts related to transactions in SQL. I perform below steps.


Connection 1 open for DB1 database
Begin transaction for Connection 1
Run the commands on Connection 1
Connection 2 open for DB2 database
Begin transaction for Connection 2
Run the commands on Connection 2
Commit transaction for Connection 2
Commit transaction for Connection 1


If  commit transaction on Connection 1 fails(rollback) then transaction on connection 2 should rollback.
Is it possible? How it can be done?
Yes this can be done but you need a third party acting as a transaction coordinator. The standard protocol for this is called Two Phase Commit (2PC). This is usually done with a transaction manager acting as the coordinator.

This can also be generalized further to more than two databases. In fact it doesn't even have to be databases as the approach is generally applied to "transactional resources". Besides databases the other common transactional resource is a message queue. The usual example is to perform some work in a database (ex: update an account balance) and also send a message out on a message queue (ex: an outbound order).

For this to work your datasources need to support 2PC, usually via the XA protocol. How to do it depends on the specific type of datasource and programming language (ex: for Java you'd use an XADataSource).