0
0
RedisHow-ToBeginner · 3 min read

How to Get Value in Redis: Simple Guide with Examples

To get a value in Redis, use the GET command followed by the key name. For example, GET mykey returns the value stored at mykey or (nil) if the key does not exist.
📐

Syntax

The basic syntax to get a value from Redis is:

  • GET key: Retrieves the value stored at the specified key.
  • If the key exists, Redis returns its value as a string.
  • If the key does not exist, Redis returns (nil).
redis
GET key
💻

Example

This example shows how to set a key and then get its value using Redis commands.

redis
SET favorite_color blue
GET favorite_color
GET missing_key
Output
"OK" "blue" (nil)
⚠️

Common Pitfalls

Common mistakes when getting values in Redis include:

  • Trying to get a value from a key that does not exist, which returns (nil).
  • Confusing data types: GET only works with string keys, not hashes or lists.
  • Not checking the response for (nil) which means the key is missing.
redis
GET myhash

# Correct way to get a field from a hash:
HGET myhash field1
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value "value1"
📊

Quick Reference

CommandDescriptionExample
GET keyGet the string value of a keyGET username
SET key valueSet the string value of a keySET username alice
HGET key fieldGet the value of a hash fieldHGET user:1 name
(nil)Returned when key does not existGET missing_key

Key Takeaways

Use the GET command followed by the key name to retrieve a value in Redis.
GET returns the string value or (nil) if the key does not exist.
GET only works with string keys; use HGET for hash fields.
Always check for (nil) to handle missing keys gracefully.