0
0
RedisHow-ToBeginner · 3 min read

How to Use DISCARD Command in Redis Transactions

In Redis, DISCARD is used to cancel a transaction started with MULTI and discard all queued commands. It aborts the transaction without executing any commands, returning the connection to normal mode.
📐

Syntax

The DISCARD command is used after starting a transaction with MULTI. It cancels the transaction and clears all queued commands.

  • DISCARD: Cancels the current transaction.
redis
MULTI
DISCARD
Output
+OK
💻

Example

This example shows starting a transaction with MULTI, queuing commands, then cancelling the transaction with DISCARD. No commands are executed.

redis
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET key1 "value1"
QUEUED
127.0.0.1:6379> SET key2 "value2"
QUEUED
127.0.0.1:6379> DISCARD
OK
127.0.0.1:6379> GET key1
(nil)
Output
(nil)
⚠️

Common Pitfalls

One common mistake is to forget that DISCARD only works inside a transaction started by MULTI. Using DISCARD without MULTI returns an error. Also, after DISCARD, the transaction is cancelled and queued commands are lost.

Wrong usage example:

redis
127.0.0.1:6379> DISCARD
(error) ERR DISCARD without MULTI
Output
(error) ERR DISCARD without MULTI
📊

Quick Reference

CommandDescription
MULTIStart a transaction and queue commands
DISCARDCancel the transaction and discard queued commands
EXECExecute all queued commands in the transaction

Key Takeaways

Use DISCARD only after MULTI to cancel a Redis transaction.
DISCARD clears all queued commands without executing them.
Using DISCARD outside a transaction causes an error.
After DISCARD, the connection returns to normal command mode.