Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

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

Sponsored

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 OK on 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.
  • GET now 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 + GET for simple key‑value storage (caching, config, user data).
  • Use SETNX when you need to ensure a key is set only once (e.g., first registration).
  • Use MSET / MGET when 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. GET works only on string keys. Use LRANGE for lists.

Common mistake 2: Forgetting quotes on values with spaces

SET name John Doe
  • Redis interprets John as the value and Doe as 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) because userUser.

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 SET inserts or overwrites a string value, and GET retrieves it.
  • Use SET and GET confidently in redis-cli.
  • Avoid common pitfalls like forgetting quotes or mixing types.
  • Choose between SET, SETNX, MSET, and MGET for 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 GET on a key that holds a list or hash — Redis returns WRONGTYPE error. Check the type with TYPE first.
  • Writing SET name John Doe without quotes — Redis sees Doe as an extra argument and fails. Always quote values with spaces.
  • Assuming keys are case‑insensitive — GET User returns (nil) if the key is user. Keys are case‑sensitive.
  • Forgetting that SET overwrites without warning — use SETNX if you need to set only when the key does not exist.

Variations

  1. Use SETEX key seconds value to set a string value with an expiration time in one command (combines SET + EXPIRE).
  2. Use PSETEX for millisecond precision expiration.
  3. Use SET with the NX or XX option (Redis 2.6.12+) — e.g., SET key value NX is equivalent to SETNX but more flexible.

Real-world use cases

  • Cache a database query result: SET user:123:profile ‘{...}’ and GET user:123:profile to 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 0 then INCR per request, checking the value before allowing more requests.

Key takeaways

  • SET key value stores a string; GET key retrieves 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 Foo and GET foo are different keys.
  • SET overwrites an existing key without warning; use SETNX for conditional setting.
  • Always quote string values containing spaces to avoid syntax errors.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.