Redis Command Basics - Part 3


In this third installment of this multi-part article we’ll show you more essential Redis command basics. These Redis commands tend to build on each other so please keep following along and running them yourself in your local environment is a great for cementing the concepts.

More Essential Redis Commands

Note: We are going to run a FLUSHALL command between each demo so we start with a blank slate.


The GETSET command is a little nuanced. What it does is it SETS a key to a value and then returns the previous value. Let’s see it in action:> SET str1 initialvalue
OK> GETSET str1 newvalue


The SETEX command is a combination of the SET and EXPIRE commands, so it will set s key to a string value that will expire after a specified amount of seconds. Let’s see an example:> SETEX key1 60 "hi"
OK> GET key1
// Waited 60 seconds> GET key1

This is the equivalent to:> SET key1 "hi"
OK> EXPIRE key1 60
(integer) 1


PSETEX is exactly like SETEX except it takes the expire time in milliseconds. So to expire a value after one minute you’d execute this:> PSETEX key1 60000 "hi"

To get the time until expiration you use the PTTL command.> PTTL key1
(integer) 17905


If you’ve set a key value to expire and you no longer want to expire you can do so by using the PERSIST command like so:> SETEX key1 100 "hi"
OK> TTL key1
(integer) 95> PERSIST key1
(integer) 1> TTL key1
(integer) -1

We used the TTL command to show that at first it had an expiration and after the PERSIST it no longer did (-1).


If you only want to set a key value if the key does not exist use SETNX.> SET key1 "hi"
OK> SETNX key1 "bye"
(integer) 0> SETNX key2 "bye"
(integer) 1

Notice that only the second SETNX set a value. The first one did not because key1 already existed.


We’ve covered a few more essential Redis commands including SETNX, PERSIST, PSETEX, SETEX, and GETSET. We hope you have a fuller understanding of the basic Redis commands.

If you need help setting up Redis or managing Redis please don’t hesitate to reach out to us at Object Rocket and ask us questions about your specific application. We’re always glad to help.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed Redis,
MongoDB & Elasticsearch

Get Started


Try CockroachDB
in Beta

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.