GETSET(3valkey)

πŸ“¦
version 9.0.6 Β· 2 versions
, in fedora 44

✨ GETSET ✨

okay so bestie, this is valkey's GETSET β€” it's giving "swap the vibes and tell me what was there before". Manual page? we're in the 3valkey manual, obvs πŸ’…


πŸ’– NAME πŸ’–

getset β€” returns the previous string value of a key after setting it to a new value. like, it hands you the old thing and then replaces it. iconic behavior fr fr πŸŽ€


πŸ¦‹ SYNOPSIS πŸ¦‹

GETSET key value

🌸 DESCRIPTION 🌸

So basically: GETSET atomically sets key to value and returns the old value that was chillin' at key. Atomic. No cap. It all happens in one go, no sneaky middle state. ✨

🚨 But listen β€” it returns an error when key exists but does not hold a string value. So if you're pointing this at a list or a hash or whatever, bestie, it's gonna yell at you. πŸ’€

Also: any previous time to live associated with the key is discarded on a successful SET operation. Your TTL? gone. evaporated. not invited to the function. 😭

🌈 Design pattern 🌈

GETSET can be used together with INCR for counting with atomic reset. Obsessed with this one actually.

So like, a process may call INCR against the key mycounter every time some event occurs, but from time to time we need to get the value of the counter and reset it to zero atomically. That's the whole vibe. This can be done using GETSET mycounter "0":

127.0.0.1:6379> INCR mycounter
(integer) 1
127.0.0.1:6379> GETSET mycounter "0"
"1"
127.0.0.1:6379> GET mycounter
"0"

read it and reset it, no race condition, main character energy only πŸ‘‘

πŸ’œ Alternative πŸ’œ

SET with the GET argument. (iykyk β€” the new hotness, but GETSET still ate, don't worry.)


πŸŽ€ REPLY πŸŽ€

πŸ’… RESP2

One of the following:

🫢 RESP3

One of the following:


⭐ COMPLEXITY ⭐

O(1)

constant time, babe. fastest girl in the room. πŸ”₯


πŸ‘‘ ACL CATEGORIES πŸ‘‘

@fast @string @write


πŸ¦„ HISTORY πŸ¦„

  • Available since: 1.0.0

like... ancient. a legend. the blueprint. 🌈


πŸ“ EXAMPLES πŸ“

127.0.0.1:6379> SET mykey "Hello"
OK
127.0.0.1:6379> GETSET mykey "World"
"Hello"
127.0.0.1:6379> GET mykey
"World"

see how it gave you back "Hello" and left "World" behind? that's the whole trick. ate and left no crumbs πŸ’–


πŸ’œ SEE ALSO πŸ’œ

append(3valkey), decr(3valkey), decrby(3valkey), delifeq(3valkey), get(3valkey), getdel(3valkey), getex(3valkey), getrange(3valkey), incr(3valkey), incrby(3valkey), incrbyfloat(3valkey), lcs(3valkey), mget(3valkey), mset(3valkey), msetnx(3valkey), psetex(3valkey), set(3valkey), setex(3valkey), setnx(3valkey), setrange(3valkey), strlen(3valkey), substr(3valkey)

go read the whole friend group, they're all slaying in their own way 🧚


and that's the page, bestie!! this was version 9.0.0, dated 2025-10-21, from the GETSET(3valkey) manual β€” mwah, ily, go reset some counters atomically πŸ’–βœ¨πŸŽ€

πŸ“¦ where this page comes from