Redis SETRANGE Command Explained

In Redis, the SETRANGE command allows us to overwrite part of a string at a given key, starting at a specified offset. It overwrites the old value from the specified offset, for the entire length of the new value.

Syntax

The syntax goes like this:

SETRANGE key offset value

Where key is the key to set, offset is where the new string will start, and value is the new value to start at that offset.

Example

Suppose we set a key to the following value:

SET country "New Zealand"

Result:

OK

And we confirm that it holds that value:

GET country

Result:

"New Zealand"

Let’s now use SETRANGE to update that value:

SETRANGE country 4 "Caledonia"

Result:

(integer) 13

The command returns an integer reply that specifies the length of the string after it was modified by the SETRANGE command.

Now let’s get the value again:

GET country

Result:

"New Caledonia"

It has updated the string as expected.

When the Offset is Larger than the Original String

If the offset is larger than the length of the original string, the string is padded with zero-bytes to make the offset fit.

Example:

SETRANGE country 20 "Thailand"

Result:

(integer) 28

Now let’s get the value:

GET country

Result:

"New Caledonia\x00\x00\x00\x00\x00\x00\x00Thailand"

The string has been padded with zero-bytes to make the offset fit. Depending on where you run it, you may see the same result as above, or you may see the following:

"New CaledoniaThailand"

Non Existent Keys

Non-existent keys are considered empty strings, so the SETRANGE command will make sure it holds a string large enough to be able to set the value at the specified offset.

Example:

SETRANGE city 10 "Bangkok"

Result:

(integer) 17

Now let’s get the value:

GET city

Result:

"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Bangkok"

Again, given the string has been padded with zero-bytes, you might see this:

"Bangkok"

Negative Offset

Using a negative value for the offset produces an error:

SETRANGE city -3 "Los Angeles"

Result:

(error) ERR offset is out of range