MSET saves several keys in one command, and MGET reads several at once. This guide stores three fruits in Valkey®.
Type the commands at the valkey-cli prompt. To open it, run valkey-cli in a terminal.
Note: Every command and output on this page is real, run on Valkey 9.2 on an Apple silicon Mac with macOS 26.
Syntax
MSET key value [key value ...]
MGET key [key ...]
MSETNX key value [key value ...]
key value: a key and the value to save under it. Repeat the pair for more keys.MGET key ...: the keys to read, in the order you want the values back.MSETNX: likeMSET, but saves nothing if any of the keys already exists.
From the MSET (opens in a new tab), MGET (opens in a new tab) and MSETNX (opens in a new tab) documentation.
Step 1: Save Several Keys with MSET
MSET fruit:1 "apple" fruit:2 "banana" fruit:3 "cherry"
OK
Step 2: Read Several Keys with MGET
MGET fruit:1 fruit:2 fruit:3 fruit:4
1) "apple"
2) "banana"
3) "cherry"
4) (nil)
The values come back in the order of the keys. fruit:4 doesn’t exist, so its place holds (nil).
Step 3: Save Only If None Exist with MSETNX
MSETNX fruit:3 "grape" fruit:4 "kiwi"
(integer) 0
0: fruit:3 exists, so MSETNX saved nothing, not even fruit:4. With two new keys it saves both:
MSETNX fruit:4 "kiwi" fruit:5 "lemon"
(integer) 1
MGET fruit:3 fruit:4 fruit:5
1) "cherry"
2) "kiwi"
3) "lemon"

Clean Up
DEL fruit:1 fruit:2 fruit:3 fruit:4 fruit:5
(integer) 5
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Expecting MSETNX to save the keys that are free | It saves nothing if any key exists | Save the free keys with MSET, or check its reply |
Leaving out a value in MSET | The pairs shift and keys get the wrong values | Always give a key and a value for each pair |
FAQ
Is MSET all or nothing?
Yes. The MSET documentation (opens in a new tab) says it’s atomic: no client ever sees some keys changed and others not.
Why use MGET instead of several GET commands?
One MGET is one request to the server instead of one per key.
Conclusion
MSET saves several keys at once, MGET reads them back in order, and MSETNX saves only when none of the keys exist.
Related
- Valkey Tutorial — Part 4: Strings and Counters
- Valkey Tutorial — Part 2: Your First Valkey Commands with valkey-cli
Additional Resources
Valkey® is a registered trademark of LF Projects, LLC. Redis® is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with the Valkey project, LF Projects or Redis Ltd., and isn’t endorsed, supported or certified by them.
0 comments