Skip to content

SET & GET

SET key value stores a string. GET key retrieves it. If the key already exists, SET overwrites it unconditionally (unless you add a condition flag).

127.0.0.1:6379> SET city "Bangkok"
OK
127.0.0.1:6379> GET city
"Bangkok"
127.0.0.1:6379> SET city "Chiang Mai"
OK
127.0.0.1:6379> GET city
"Chiang Mai"

Redis 7 SET supports several options in one command:

OptionMeaning
EX secondsSet expiration in seconds
PX millisecondsSet expiration in milliseconds
EXAT unix-time-secondsExpire at a Unix timestamp (seconds)
PXAT unix-time-msExpire at a Unix timestamp (milliseconds)
NXOnly set if the key does not exist
XXOnly set if the key does exist
GETReturn the old value before overwriting
KEEPTTLRetain the existing TTL instead of resetting it
127.0.0.1:6379> SET token "abc123" EX 60
OK
127.0.0.1:6379> TTL token
(integer) 59
127.0.0.1:6379> SET counter 0 NX
OK
127.0.0.1:6379> SET counter 99 NX
(nil)
127.0.0.1:6379> GET counter
"0"
127.0.0.1:6379> SET city "Phuket" GET
"Chiang Mai"
127.0.0.1:6379> GET city
"Phuket"
SET token "abc123" EX 60
TTL token
SET counter 0 NX
SET counter 99 NX
GET counter
SET city "Phuket" GET
GET city

These are older convenience aliases — SET with EX or NX is preferred in Redis 7, but you will still see them in legacy code:

127.0.0.1:6379> SETEX session:user1 3600 "token-xyz"
OK
127.0.0.1:6379> TTL session:user1
(integer) 3599
127.0.0.1:6379> SETNX lock:job1 "worker-A"
(integer) 1
127.0.0.1:6379> SETNX lock:job1 "worker-B"
(integer) 0
127.0.0.1:6379> GET lock:job1
"worker-A"
SETEX session:user1 3600 "token-xyz"
TTL session:user1
SETNX lock:job1 "worker-A"
SETNX lock:job1 "worker-B"
GET lock:job1

Set or get many keys in a single round-trip. This is significantly faster than individual commands when you need multiple keys at once.

127.0.0.1:6379> MSET user:1:name "Ada" user:1:lang "Python" user:2:name "Bob" user:2:lang "Go"
OK
127.0.0.1:6379> MGET user:1:name user:1:lang user:2:name user:2:lang
1) "Ada"
2) "Python"
3) "Bob"
4) "Go"
127.0.0.1:6379> MGET user:1:name user:99:name
1) "Ada"
2) (nil)
MSET user:1:name "Ada" user:1:lang "Python" user:2:name "Bob" user:2:lang "Go"
MGET user:1:name user:1:lang user:2:name user:2:lang
MGET user:1:name user:99:name

APPEND adds to the end of an existing string value (or creates the key if absent). STRLEN returns the byte length of the value.

127.0.0.1:6379> SET log "2024-01-01 boot"
OK
127.0.0.1:6379> APPEND log " | 2024-01-01 ready"
(integer) 34
127.0.0.1:6379> GET log
"2024-01-01 boot | 2024-01-01 ready"
127.0.0.1:6379> STRLEN log
(integer) 34
SET log "2024-01-01 boot"
APPEND log " | 2024-01-01 ready"
GET log
STRLEN log
What does `SET key val NX` return when the key already exists?
Which command sets multiple keys in one round-trip?
What does `SET key val GET` do?
STRLEN returns the length of a string in what unit?