0
0
RedisHow-ToBeginner · 3 min read

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 string value under the specified key.
  • You can optionally add flags like EX seconds to set an expiration time or NX/XX to 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 NX
💻

Example

This example shows how to set a key and then get its value:

redis
SET greeting "Hello, Redis!"
GET greeting
Output
"Hello, Redis!"
⚠️

Common Pitfalls

Common mistakes when using SET include:

  • Forgetting that SET overwrites existing values without warning.
  • Not using expiration flags when temporary data is needed, causing keys to persist indefinitely.
  • Using NX or XX incorrectly, 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

OptionDescription
keyThe name of the key to set
valueThe string value to store
EX secondsSet key expiration in seconds
PX millisecondsSet key expiration in milliseconds
NXSet only if key does not exist
XXSet 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.