Back to interview-question
interview-question
8/20/2026
2 min read

PostgreSQL Transactions, explained with a real-life example

In my last interview for a full stack engineering job, the interviewer asked me about transaction. He asked, "Do you know transaction?" I was like, what transaction? The payment I just made for a sunglasses? Seems inappropriate to answer this in an Interview. Ha ha! NO, I didn't answer this. But really, that's all about Transactions.

PostgreSQL Transactions, explained with a real-life example

So what actually happens when you use a transaction?

Let's take the same example.

Suppose you're buying a Ray-Ban sunglasses from their Official Website. You wanna make the payment through your Visa card. The amount is $500.

You click the "Pay Now" button.

Now a few things need to happen.

The payment gets processed, the money gets deducted from your account, the seller receives the money and your order gets confirmed.

But what if there was an error somewhere in the middle?

What if your API crashed? Or the payment provider had some issue? Or the seller's bank provider didn't respond?

You don't want this to happen:

Money deducted from your account 

No Order confirmed 


Now let's bring this into a database.

Suppose you're placing an order and your system needs to do these things:

- Create the order

- Create order items

- Reduce the inventory

- Create payment record


What if the first three operations were completed but the last one failed?

Now your database is in a weird state.

The order is there.

The inventory is already reduced.

But there is no payment record.

That's where a transaction comes in.

You basically tell the database, These operations are related to each other. Either complete all of them or don't apply any of them."

In PostgreSQL, you can do something like this:

BEGIN;


-- Create order

-- Create order items

-- Reduce inventory

-- Create payment record


COMMIT;


If everything goes well, COMMIT saves the changes.

But if something goes wrong, you can do:

ROLLBACK;


And the changes made inside that transaction will be undone.

So basically, that's what a transaction does.

It prevents your database from ending up in a half-completed state.

Pretty simple concept when you see a real-life example, but it's something you'll use a lot when building real-world applications.



Tags

["interview-question","postgresql","transaction"]