w3resource

Redis String: Set key value

Redis SET Command

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.

Here are some common uses and scenarios for the "SET" command:

  • Storing Data: Save strings, numbers, or other serialized data in Redis.
  • Cache Values: Store cached data with an optional expiration time.
  • Flags and Counters: Use as flags (e.g., feature toggles) or counters by combining with increment/decrement operations.
  • Session Storage: Store session data for web applications.

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.

Previous: WAIT
Next: GET



Follow us on Facebook and Twitter for latest update.