0
0
RedisHow-ToBeginner · 3 min read

How to Set Value in Redis: Simple Guide with Examples

To set a value in Redis, use the SET command followed by the key and the value you want to store, like SET key value. This command saves the value under the given key so you can retrieve it later.
📐

Syntax

The basic syntax to set a value in Redis is:

  • SET key value: Stores the value under the specified key.
  • key: The name you want to assign to the stored data.
  • value: The data you want to save, which can be a string or number.

You can also add optional parameters like expiration time, but the simple form is just SET key value.

redis
SET mykey "Hello, Redis!"
💻

Example

This example shows how to set a value and then get it back from Redis.

redis
127.0.0.1:6379> SET greeting "Hello, Redis!"
OK
127.0.0.1:6379> GET greeting
"Hello, Redis!"
Output
OK "Hello, Redis!"
⚠️

Common Pitfalls

Some common mistakes when setting values in Redis include:

  • Forgetting to quote strings with spaces or special characters, which can cause errors.
  • Using keys that overwrite important data unintentionally.
  • Not checking the command response; SET returns OK on success.

Always verify your keys and values before setting them.

redis
Wrong:
SET mykey Hello Redis

Right:
SET mykey "Hello Redis"
📊

Quick Reference

CommandDescription
SET key valueSet the string value of a key
GET keyGet the value of a key
SET key value EX secondsSet value with expiration time in seconds
SET key value NXSet value only if key does not exist
SET key value XXSet value only if key exists

Key Takeaways

Use the SET command followed by key and value to store data in Redis.
Always quote string values with spaces or special characters.
Check the command response; SET returns OK on success.
Avoid overwriting important keys by mistake.
Use optional parameters like EX for expiration when needed.