How to Append a Value to a String in Redis

If we need to append a value to a string in Redis, we can use the APPEND command to do just that. All we need to do is call the command with the key name and the value to append.

Example

Suppose we have the following string:

GET pets

Result:

"Cat"

We can use the APPEND command to append a value to the end of that string:

APPEND pets "Dog"

Result:

(integer) 6

The command returns an integer reply with the length of the string after the append operation.

Now let’s return the updated value of the key:

GET pets

Result:

"CatDog"

When the Key Doesn’t Exist

If the key doesn’t exist it is created with the specified value.

Example:

APPEND nonexistentkey "Dog"

Result:

(integer) 3

Here, the nonexistentkey key didn’t exist and so it was created with the specified value.

Now let’s check the value of that key:

GET nonexistentkey

Result:

"Dog"

We can see that the key now exists with the specified value.

Now we can append values to that key if required:

APPEND nonexistentkey "Cat"

Result:

(integer) 6

And check its value:

GET nonexistentkey

Result:

"DogCat"