w3resource logo


Redis Tutorial

Redis String: Set key value

Secondary Nav

Description

Redis SET command is used to set some string value in redis key. If the key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on a successful SET operation.

Syntax

Basic syntax of redis SET command is shown below:

redis 127.0.0.1:6379> SET KEY_NAME VALUE

Available since

1.0.0.

Return Value

Simple string reply. OK, if a value is set to key or Null, if the value does not set.

Return Value Type

String

Example

redis 127.0.0.1:6379> SET w3resource redis
OK

Options

In SET command there are many options available, that modify the behavior of command. Basic syntax of SET command with available options is shown below:

redis 127.0.0.1:6379> SET KEY VALUE [EX seconds] [PX milliseconds] [NX|XX]
(integer) 1
  • EX seconds - Set the specified expire time, in seconds.
  • PX milliseconds - Set the specified expire time, in milliseconds.
  • NX - Only set the key if it does not already exist.
  • XX - Only set the key if it already exist.

Example

redis 127.0.0.1:6379> SET w3resource redis EX 60 NX 
OK

Above example will set the key w3resource, with an expiry of 60 seconds, if the key does not exist.



Join our Question Answer community to learn and share your programming knowledge.