# Connections vs. transactions

A connection is one thread of communication between a client (our application) and the database. Within a connection, we can be either sending or receiving data related to one query at a time. Sometimes in the official documentation, an incoming connection is referred to as a "session".

If you wanted to run two queries simultaneously, then you'd have to open two connections or sessions to the database.

So what about transactions?

In PostgreSQL, all queries run within a transaction. The transaction life cycle is that it starts, runs the queries it contains, and ends. Transactions are linear and synchronous, which means the queries contained within them run from top to bottom, one by one.

Similarly, transactions within a connection must also be linear and synchronous because each connection can only handle one query at a time.

To summarise:

  • A connection can be either sending or receiving data at any point in time (or idle, of course).
  • You can use a connection to open a transaction, and in it run one or more queries. These run one at a time.
  • When the transaction has ended, you can open another one. You can't have two transactions open at the same time in the same connection.

You can begin, commit, and rollback transactions manually as well[1]. We touched on this briefly when we learned about stored procedures.

# Running queries simultaneously (opening multiple connections)

Any client can open multiple connections to a database if they want to have multiple threads of communication open. For example, one connection to handle writing some data, and 10 connections to handle reading data (if the client is very read-heavy).

However as with most things, there are compromises to be had[2]. Whether you'll see a speedup or a slowdown depends on many things, such as whether the database can handle keeping all those connections open (usually won't have trouble until you get into the hundreds or thousands, depending on RAM).


  1. How to work with PostgreSQL transactions (EnterpriseDB) (opens new window) ↩︎

  2. PostgreSQL - If I run multiple queries concurrently... (StackOverflow) (opens new window) ↩︎