GETSET - Write Over a Key's Value

Feature thumb redis course thumb

The GETSET command writes over a pre-existing value for a key, while simultaneously returning the previous value. Imagine that you're building a scorecard application for a baseball team. Each time a new player comes to the plate, you can use GETSET to pre-load who the next batter will be, while simultaneously who the previous batter was:

127.0.0.1:6379> SET current_batter 'Altuve'
OK
127.0.0.1:6379> GETSET current_batter 'Bregman'
"Altuve"
127.0.0.1:6379> GET current_batter
"Bregman"

If you use GETSET on a key that has not been previously set, it will return nil and set the key to the new value:

127.0.0.1:6379> GETSET key_does_not_exist 'Hi there'
(nil)
127.0.0.1:6379> GET key_does_not_exist
"Hi there"