Redis STRLEN Command Explained

In Redis, the STRLEN command returns the length of the string stored at a given key.

Syntax

STRLEN key

The length of the string stored at key is returned.

Example

Suppose we set a key like this:

SET pet "Cat"

Result:

OK

And now we want to get the length of the value that’s stored at pet. In such cases, we can do this:

STRLEN pet

Result:

(integer) 3

We get an integer reply of 3, because that’s the length of the string stored at pet.

Let’s set the value to something longer:

SET pet "Parastratiosphecomyia stratiosphecomyioides"

Result:

OK

That’s the scientific name for the South East Asian soldier fly (which has the longest scientific binomial name given to any animal).

Let’s get the length:

STRLEN pet

Result:

(integer) 43

This time we get an integer reply of 43, because that’s the length of the string. Note that this includes the space, so there are 42 letters and one space.

Empty Strings

If the key contains the empty string, then the result is 0.

Let’s set it to the empty string:

SET pet ""

Result:

OK

Now let’s check its length:

STRLEN pet

Result:

(integer) 0

As expected, it’s zero.

When the Key Doesn’t Exist

If the key doesn’t exist, 0 is returned.

Let’s delete the key:

DEL pet

Result:

(integer) 1

Now let’s try to check the length of the key that we just deleted:

STRLEN pet

Result:

(integer) 0

Again, zero as expected.