# SQL API

> redis.command, redis.command_bin, sessions for blocking and Pub/Sub, errors and savepoints.

---

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

---

The `pg_redis` extension exposes SQL functions in schema `redis` so PostgreSQL transactions, stored procedures, and triggers can execute Redis commands in the same transaction as relational tables. Every function returns wire-formatted RESP replies as `bytea`.

For step-by-step examples, see [SQL rollback](/docs/redis/tutorial/sql-rollback/), [Binary keys and values](/docs/redis/tutorial/binary-data/), and [Transactional outbox](/docs/redis/tutorial/outbox/).

## Command functions {#commands}

{.wide}
| Function | Arguments | Description |
| --- | --- | --- |
| `redis.command(text[], integer DEFAULT 0)` | Command and arguments as `text[]`, followed by logical database number (`0..15`) | Executes one command and returns a RESP2 reply as `bytea`. |
| `redis.command_bin(bytea[], integer DEFAULT 0)` | Command and arguments as `bytea[]`, followed by logical database number (`0..15`) | Binary-safe entry point for `NUL` (`\x00`) bytes or non-UTF-8 payloads; returns a RESP2 reply as `bytea`. |
{.wide .expand}

```sql
SELECT encode(redis.command(ARRAY['PING']), 'hex');
-- 2b504f4e470d0a (+PONG\r\n)

SELECT convert_from(redis.command(ARRAY['GET', 'example:key'], 1), 'UTF8');
-- Reads example:key from logical database 1
```

Calling `redis.command` invokes `redis.command_bin` internally, so the calling PostgreSQL role requires `USAGE ON SCHEMA redis`, `EXECUTE` on both functions, and `EXECUTE` on the required capability marker (`redis._read()`, `redis._write()`, or `redis._admin()`). See [Authentication and permissions](/docs/redis/operations/security/#permissions) for the complete `GRANT` list.

## Errors, savepoints, and transaction scope {#errors}

- **Shared transaction:** Both functions execute inside the caller's `READ COMMITTED` PostgreSQL transaction (`REPEATABLE READ` and `SERIALIZABLE` are rejected). Even when invoked from a SQL `SELECT`, a mutating command such as `SET` writes rows and requires `redis._write()`.
- **SQLSTATE codes:** Redis command errors (such as `WRONGTYPE` or syntax errors) raise SQLSTATE `RD001`. Commands blocked by `CLIENT PAUSE` raise SQLSTATE `RD002`. PostgreSQL engine errors (such as deadlocks or constraint failures) retain their native PostgreSQL SQLSTATE codes.
- **Savepoint recovery:** Because an unhandled `RD001` aborts the current SQL transaction block, wrap fallible Redis calls in a `SAVEPOINT` (or a PL/pgSQL `BEGIN ... EXCEPTION WHEN SQLSTATE 'RD001' THEN ... END` block) to recover without losing earlier SQL work.
- **Per-call database index:** The `db` parameter applies only to that function call. Executing `SELECT` inside `redis.command` does not change the logical database for subsequent SQL calls.

## Blocking and Pub/Sub session API {#sessions}

Ordinary SQL calls cannot hold a transaction open while waiting for another transaction to publish a message or push a list item. For blocking commands (`BLPOP`, `BLMOVE`, `BZPOPMIN`, `XREAD BLOCK`, `XREADGROUP BLOCK`, `WAIT`) and Pub/Sub subscriptions across multiple SQL transactions, use the session functions:

{.wide}
| Function | Positional parameters | Return value (`bytea`) |
| --- | --- | --- |
| `redis.blocking_begin(bytea[], bytea, integer DEFAULT 0)` | `args, token, db=0` | Registers a blocking command with RESP2 reply encoding; returns a 2-element RESP2 array `[flag, result]`. |
| `redis.blocking_begin(bytea[], bytea, integer, integer)` | `args, token, db, protocol` | Registers a blocking command with explicit reply protocol (`2` or `3`); returns `[flag, result]`. |
| `redis.blocking_poll(bytea, integer DEFAULT 0)` | `token, db=0` | Polls for completion and renews the lease; returns `[flag, result]`. |
| `redis.blocking_cancel(bytea, integer DEFAULT 0)` | `token, db=0` | Deletes the registration and returns `+OK\r\n`. |
| `redis.pubsub_open(bytea, integer DEFAULT 2)` | `token, protocol=2` | Opens a Pub/Sub session with protocol `2` or `3`; returns `+OK\r\n`. |
| `redis.pubsub_change(bytea, bytea[])` | `token, args` | Applies a subscription command (`SUBSCRIBE`, `UNSUBSCRIBE`, `PSUBSCRIBE`, `SSUBSCRIBE`, etc.); returns `[count, frames]`. |
| `redis.pubsub_poll(bytea)` | `token` | Dequeues pending messages in the current transaction; returns `[count, frames]`. |
| `redis.pubsub_cancel(bytea)` | `token` | Closes the Pub/Sub session and deletes queued messages; returns `+OK\r\n`. |
{.wide .expand}

Parameter and lifecycle rules:

- `token` is a unique 32-byte `bytea` generated by the caller for each blocking wait or Pub/Sub session. All subsequent `poll`, `change`, and `cancel` calls must use the same `LOGIN` and active role.
- For blocking operations, `[flag, result]` has `flag = 0` (with a null bulk string) while waiting, and `flag = 1` once fulfilled. Register with `blocking_begin` and commit first, then call `blocking_poll` in subsequent transactions. Repeated polls after completion return the fixed result without popping a second element.
- For Pub/Sub, `pubsub_poll` deletes delivered rows from `redis._pubsub_event` inside the caller's transaction; rolling back that transaction restores the messages to the queue.

---

Backlinks:

- [Reference](/docs/redis/reference/)
- [Pub/Sub and keyspace events](/docs/redis/reference/pubsub/)
- [Streams and consumer groups](/docs/redis/reference/streams/)
