0
0
RedisHow-ToBeginner · 3 min read

How to Use MSET in Redis: Set Multiple Keys at Once

Use the MSET command in Redis to set multiple key-value pairs at once by listing keys and values alternately. This command is atomic, meaning all keys are set together or none at all.
📐

Syntax

The MSET command sets multiple keys to their respective values in one atomic operation.

Syntax:

MSET key1 value1 key2 value2 ... keyN valueN

Each key is followed by its value. You can set as many pairs as you want in a single command.

redis
MSET key1 value1 key2 value2 key3 value3
Output
"OK"
💻

Example

This example shows how to set three keys with their values using MSET and then retrieve one of them.

redis
127.0.0.1:6379> MSET name "Alice" age "30" city "Paris"
"OK"
127.0.0.1:6379> GET name
"Alice"
Output
"OK" "Alice"
⚠️

Common Pitfalls

Common mistakes when using MSET include:

  • Not providing an even number of arguments (keys and values must come in pairs).
  • Expecting partial success; MSET is atomic, so if the command fails, no keys are set.
  • Using MSET for very large numbers of keys can impact performance; consider pipelining for bulk operations.
redis
127.0.0.1:6379> MSET key1 value1 key2
(error) ERR wrong number of arguments for 'mset' command

-- Correct usage --
127.0.0.1:6379> MSET key1 value1 key2 value2
"OK"
Output
(error) ERR wrong number of arguments for 'mset' command "OK"
📊

Quick Reference

CommandDescriptionExample
MSETSet multiple keys to multiple values atomicallyMSET key1 val1 key2 val2
GETGet the value of a keyGET key1
MSETNXSet multiple keys only if none existMSETNX key1 val1 key2 val2

Key Takeaways

Use MSET to set multiple keys and values in one atomic command.
Always provide an even number of arguments: key followed by value.
MSET either sets all keys or none, ensuring atomicity.
For large bulk sets, consider pipelining to improve performance.
Use GET to verify values after setting them with MSET.