Set and Get String Values
Learn to set and get string values in Redis with a practical, step-by-step tutorial. Master the core concepts, hands-on exercises, troubleshooting, and next steps.
Focus: set and get string values
You've set up Redis, connected with redis-cli, and maybe even explored its structure. But the real power of Redis begins when you store a value, retrieve it in milliseconds, and use it to power a live application. Without mastering set and get string values, you're just staring at an empty database. This lesson gives you the foundational key-value operations that every Redis workflow—caching, session storage, rate limiting—relies on.
The problem this lesson solves
Every data store needs two basic operations: write and read. In Redis, these are SET and GET. Without them, you can't:
- Cache an expensive database query result.
- Store a user's session token for fast lookup.
- Persist a temporary state like a CAPTCHA string.
Many developers dive into complex Redis features like lists or streams without first understanding how to safely and predictably store a simple string. That leads to confusion when GET returns (nil) or when the value isn't what they expected. This lesson eliminates those early hurdles.
Core concept / mental model
Think of Redis as a giant dictionary (like Python's dict or JavaScript's Map). Each entry has a unique key (a string) and a value (also a string, in the simplest form). When you SET a key, you're inserting or overwriting that entry. When you GET a key, you're looking up the entry by its key and retrieving its value.
Mental model: Imagine a wall of lockers. Each locker has a label (key) and contains a single piece of paper (value). You can put a new note in a locker (
SET) and later open it to read the note (GET). If the locker is empty, you get nothing ((nil)).
This is the core of set and get string values—the simplest and fastest operations in Redis.
How it works step by step
Step 1: Connect to Redis
Launch redis-cli from your terminal. You'll see 127.0.0.1:6379> if it's running locally.
Step 2: Use SET to store a string
SET greeting "Hello, Redis!"
- The key is
greeting(a string). - The value is
"Hello, Redis!"(also a string). - Redis returns
OKon success.
Step 3: Use GET to retrieve the string
GET greeting
- Redis returns
"Hello, Redis!". - If the key did not exist, it returns
(nil)(empty bulk string in RESP protocol).
Step 4: Overwrite an existing key
SET greeting "Hi again!"
GET greeting
- The old value is replaced.
GETnow returns"Hi again!".
Step 5: Handle non‑existent keys
GET nonexistent
- Returns
(nil)(no error, just nothing).
Hands-on walkthrough
Example 1: Basic set and get
Open your terminal and run:
redis-cli
Then inside redis-cli:
SET username "alice"
GET username
Expected output:
OK
"alice"
Example 2: Overwrite and verify
SET username "bob"
GET username
Expected output:
OK
"bob"
Example 3: Storing an integer as a string (Redis always stores strings)
SET counter 100
TYPE counter
Expected output:
OK
string
Even though 100 looks like a number, Redis stores it as a string. The TYPE command confirms it's string.
Example 4: Using SET with spaces in the value
SET message "Hello world from Redis!"
GET message
Expected output:
OK
"Hello world from Redis!"
Pro tip: Always quote string values that contain spaces. If you forget, Redis may interpret the second word as a command or another argument.
Compare options / when to choose what
| Command | Purpose | Returns | Notes |
|---|---|---|---|
SET key value |
Store or overwrite a string | OK |
Simple, immediate |
GET key |
Retrieve a string | "value" or (nil) |
Key must exist, otherwise nil |
SETNX key value |
Set only if key does not exist | 1 (set) or 0 (not set) |
Useful for locking / optimistic writes |
MSET key1 val1 key2 val2 |
Set multiple keys atomically | OK |
Faster for bulk writes |
MGET key1 key2 |
Get multiple values | Array of values | Faster than multiple GET calls |
When to choose what:
- Use
SET+GETfor simple key‑value storage (caching, config, user data). - Use
SETNXwhen you need to ensure a key is set only once (e.g., first registration). - Use
MSET/MGETwhen you need to write or read many keys at once to reduce round trips.
Troubleshooting & edge cases
Common mistake 1: GET on a non‑string type
LPUSH mylist "item1"
GET mylist
Error: WRONGTYPE Operation against a key holding the wrong kind of value
- Redis types are strict.
GETworks only on string keys. UseLRANGEfor lists.
Common mistake 2: Forgetting quotes on values with spaces
SET name John Doe
- Redis interprets
Johnas the value andDoeas an extra command argument → syntax error.
Fix:
SET name "John Doe"
Common mistake 3: Expecting GET to return a numeric type
Even if you SET counter 100, GET counter returns the string "100". Use INCR to increment integers properly.
Common mistake 4: Case sensitivity
Keys are case‑sensitive in Redis.
SET User "alice"
GET user
- Returns
(nil)becauseuser≠User.
Edge case: Overwriting when you didn't mean to
SET always overwrites an existing key. If you intended to set only if absent, use SETNX.
Edge case: Very large values
Redis string values can be up to 512 MB. Storing large strings impacts memory and latency. For big blobs, consider compression or a different store.
What you learned & what's next
You now understand the set and get string values operations—the atomic building blocks of Redis. You can:
- Explain that
SETinserts or overwrites a string value, andGETretrieves it. - Use
SETandGETconfidently inredis-cli. - Avoid common pitfalls like forgetting quotes or mixing types.
- Choose between
SET,SETNX,MSET, andMGETfor different scenarios.
Next lesson: Set and get string values with expiration will teach you how to auto‑delete keys after a timeout—critical for caching and session management.
Practice recap
Open redis-cli and store your name using SET myname "Your Name". Retrieve it with GET myname. Then try SETNX myname "Another" and observe the result — note that SETNX returns 0 because the key already exists. Finally, check the value is unchanged with GET myname.
Common mistakes
- Using
GETon a key that holds a list or hash — Redis returnsWRONGTYPEerror. Check the type withTYPEfirst. - Writing
SET name John Doewithout quotes — Redis seesDoeas an extra argument and fails. Always quote values with spaces. - Assuming keys are case‑insensitive —
GET Userreturns(nil)if the key isuser. Keys are case‑sensitive. - Forgetting that
SEToverwrites without warning — useSETNXif you need to set only when the key does not exist.
Variations
- Use
SETEX key seconds valueto set a string value with an expiration time in one command (combinesSET+EXPIRE). - Use
PSETEXfor millisecond precision expiration. - Use
SETwith theNXorXXoption (Redis 2.6.12+) — e.g.,SET key value NXis equivalent toSETNXbut more flexible.
Real-world use cases
- Cache a database query result:
SET user:123:profile ‘{...}’andGET user:123:profileto avoid repeated heavy queries. - Store a user session token:
SET session:abc123token ‘user_id:42’and retrieve on each request to validate the session. - Implement a simple rate limiter:
SET rate_limit:user:42 0thenINCRper request, checking the value before allowing more requests.
Key takeaways
SET key valuestores a string;GET keyretrieves it. Both are the foundation of all Redis interactions.- Redis string values are always strings — even integers are stored as strings until you use numeric commands like
INCR. - Keys are case‑sensitive —
SET FooandGET fooare different keys. SEToverwrites an existing key without warning; useSETNXfor conditional setting.- Always quote string values containing spaces to avoid syntax errors.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.