# Roll back SQL and Redis together

> Use one PostgreSQL transaction for a business row and a Redis key.

---

LLMS index: [llms.txt](/llms.txt)

---

Use the `pgredis_demo` database and `pgredis_app` role from [Quick start](/docs/redis/quickstart/). Connect with `psql` as the application role:

```sh
psql -h 127.0.0.1 -p 5432 -U pgredis_app -d pgredis_demo
```

## Run and roll back a transaction {#transaction}

Create a temporary SQL table, then start a transaction that inserts a business row and sets a Redis key before rolling back:

```sql
CREATE TEMP TABLE pgredis_demo_row(id integer PRIMARY KEY, state text);
BEGIN;
INSERT INTO pgredis_demo_row VALUES (42, 'ready');
SELECT redis.command(ARRAY['SET', 'pgredis:demo:42', 'ready']);
SELECT redis.command(ARRAY['GET', 'pgredis:demo:42']);
ROLLBACK;

SELECT count(*) FROM pgredis_demo_row;
SELECT convert_from(redis.command(ARRAY['EXISTS', 'pgredis:demo:42']), 'UTF8');
```

After `ROLLBACK`, `SELECT count(*) FROM pgredis_demo_row;` returns `0` and the decoded `EXISTS` reply is `:0\r\n` (the key does not exist). The temporary table remains because it was created before `BEGIN`, while both the SQL row insert and the Redis `SET` were rolled back together.

## How it works {#result}

`redis.command` and `redis.command_bin` execute inside the caller's PostgreSQL transaction (`READ COMMITTED` isolation level) and write directly to the extension's WAL-logged tables. Separate requests sent over a RESP gateway connection run in their own transactions and do not join an open `psql` transaction.

Clean up the temporary table when finished:

```sql
DROP TABLE pgredis_demo_row;
```

Next, see [Transactional outbox](/docs/redis/tutorial/outbox/) to commit business rows and Redis Stream events together.

---

Backlinks:

- [SQL API](/docs/redis/reference/sql/)
- [Transactions and retries](/docs/redis/reference/transactions/)
- [Tutorials](/docs/redis/tutorial/)
