Insert-if-absent initialization
Create a value only when no value is present, avoiding an overwrite.
Redis · Command
Sets a key to a string, creating it or replacing its current value. Conditions, expiration controls, and GET support conditional writes, lifetimes, and retrieval of the previous string.
SET writes a string value to a key, creating it when absent or replacing its existing value regardless of the existing type. Optional conditions control whether the write occurs, while expiration options assign or preserve a lifetime; GET can return the previous string value instead of the normal status response.
SET key value [NX | XX | IFEQ ifeq-value | IFNE ifne-value | IFDEQ ifdeq-digest | IFDNE ifdne-digest] [GET] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL]| Name | Type | Description |
|---|---|---|
key | Redis key | Name of the key. |
value | string | The string value to set. |
Without GET, OK on success; with NX or XX when the condition fails, nil; with GET, the old string or nil. An error occurs with GET if the existing value is not a string.
SET session:user:42 active EX 300 NX
GET session:user:42Creates the key only when absent and sets a five-minute expiration.
Create a value only when no value is present, avoiding an overwrite.
Attach a lifetime directly to a cache entry during the write.
Replace an existing value only when the key is already present.
SET stores a string at the specified key. It creates a missing key and overwrites an existing value regardless of its type; a successful ordinary write returns OK.
Follow-up: How can a write be conditional? Use NX for an absent key or XX for an existing key, with the condition options mutually exclusive.
EX and PX specify relative expiration in seconds or milliseconds. EXAT and PXAT specify absolute Unix expiration times, while KEEPTTL preserves the existing lifetime.
Follow-up: What happens if multiple expiration options are supplied? They are mutually exclusive, so the command must select only one.
GET makes SET return the old string stored at the key, or nil when the key did not exist. If the existing value is not a string, Redis returns an error and aborts SET.
Follow-up: Does GET make SET type-safe for other Redis data types? No; it errors on a non-string existing value rather than converting or replacing it.
GETSETNXSETEXPSETEXTTLEXPIRE