How to Use SET Command in Redis: Syntax and Examples
In Redis, use the
SET command to store a string value under a key. The syntax is SET key value, which saves the value so you can retrieve it later with GET key.Syntax
The basic syntax of the SET command is:
SET key value: Stores the stringvalueunder the specifiedkey.- You can optionally add flags like
EX secondsto set an expiration time orNX/XXto set the key only if it does not exist or only if it exists.
redis
SET key value
SET key value EX 10
SET key value NXExample
This example shows how to set a key and then get its value:
redis
SET greeting "Hello, Redis!"
GET greetingOutput
"Hello, Redis!"
Common Pitfalls
Common mistakes when using SET include:
- Forgetting that
SEToverwrites existing values without warning. - Not using expiration flags when temporary data is needed, causing keys to persist indefinitely.
- Using
NXorXXincorrectly, which can cause the command to do nothing if conditions are not met.
redis
/* Wrong: overwrites without check */ SET user "Alice" SET user "Bob" /* Right: only set if key does not exist */ SET user "Alice" NX
Quick Reference
| Option | Description |
|---|---|
| key | The name of the key to set |
| value | The string value to store |
| EX seconds | Set key expiration in seconds |
| PX milliseconds | Set key expiration in milliseconds |
| NX | Set only if key does not exist |
| XX | Set only if key already exists |
Key Takeaways
Use
SET key value to store string data in Redis.Add
EX or PX to set expiration times for keys.Use
NX or XX to control when keys are set.Remember
SET overwrites existing keys unless flags are used.Retrieve stored values with
GET key.