# SET

> Set string value.

Use `SET` to store a string value at a key, replacing whatever was there before, whatever its type.

By default the value is written unconditionally and the key's previous time to live is discarded. `KEEPTTL` preserves it, while `EX`, `PX`, `EXAT`, and `PXAT` attach a new lifetime in seconds or milliseconds, or an absolute deadline as a Unix timestamp. Setting the value and its expiration in one command is what keeps a key from ever existing without one.

The condition decides whether the write happens at all. `NX` writes only when the key does not exist, which combined with an expiration is the standard way to acquire a lock, and `XX` writes only when it already exists, which refreshes a value without creating it. `IFEQ` and `IFNE` compare the current value with the one you supply, and `IFDEQ` and `IFDNE` compare its digest as returned by [`DIGEST`](/redis/commands/string/digest), so a large value can be checked without sending it; these conditional forms are implemented by this Upstash deployment and give you compare-and-set semantics in a single command. `IFEQ` and `IFDEQ` require the key to exist, while `IFNE` and `IFDNE` also write when it does not.

`GET` makes the reply the previous value instead of `OK`, which is how you swap a value and read what it replaced in one atomic step. When a condition prevents the write, the reply is null.

## Syntax

```redis
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]
```

## Arguments

| Argument | Required | Repeatable | Description |
| --- | --- | --- | --- |
| `<key>` | Yes | No | Redis key targeted by the command. |
| `<value>` | Yes | No | String value to store. |
| `(NX \| XX \| IFEQ <ifeq-value> \| IFNE <ifne-value> \| IFDEQ <ifdeq-digest> \| IFDNE <ifdne-digest>)` | No | No | Choose one form: `NX` (only when the key does not exist); `XX` (only when it already exists); `IFEQ` (only when the current value equals `<ifeq-value>`); `IFNE` (only when it differs); `IFDEQ` (only when the current value's digest equals `<ifdeq-digest>`); `IFDNE` (only when it differs). |
| `GET` | No | No | Also return the previous value. |
| `(EX <seconds> \| PX <milliseconds> \| EXAT <unix-time-seconds> \| PXAT <unix-time-milliseconds> \| KEEPTTL)` | No | No | Choose one form: `EX` (set a lifetime in seconds); `PX` (set a lifetime in milliseconds); `EXAT` (expire at a Unix timestamp in seconds); `PXAT` (expire at a Unix timestamp in milliseconds); `KEEPTTL` (preserve the existing key lifetime). |

## Important points

- `NX` and `XX` are mutually exclusive.
- Choose at most one expiration form and at most one condition. `GET` changes a successful reply from `OK` to the previous value.
- `IFEQ`/`IFNE` compare the current value; `IFDEQ`/`IFDNE` compare its digest. These conditional forms are implemented by this Upstash deployment.

## Response

The reply reports the result of the operation. Error replies have the same shape in RESP2 and RESP3 and are surfaced as exceptions by the SDKs below.

| Protocol | Reply |
| --- | --- |
| RESP2 | Simple string `OK`; with `GET`, the previous value as a bulk string, or Null bulk string or null array when the key did not exist or a condition failed |
| RESP3 | Simple string `OK`; with `GET`, the previous value as a bulk string, or Null when the key did not exist or a condition failed |

<Note>
  Client libraries often decode bulk strings, maps, sets, and numeric strings into language-native values. The table describes the Redis wire reply.
</Note>

## Examples

TCP examples use the TLS `REDIS_URL` from the Upstash console. REST examples use `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.

<AccordionGroup>

<Accordion title="Redis CLI" icon="terminal">

```bash
SET my-key value
```

</Accordion>

<Accordion title="@upstash/redis" icon="node-js" iconType="brands">

```ts
import { Redis } from "@upstash/redis";

const redis = Redis.fromEnv();

await redis.set("my-key", {my: "value"});
```

</Accordion>

<Accordion title="upstash_redis" icon="python" iconType="brands">

```python
from upstash_redis import Redis

redis = Redis.from_env()
result = redis.set("my-key", "value")
print(result)
```

</Accordion>

<Accordion title="ioredis" icon="node-js" iconType="brands">

```ts
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL!);
const result = await redis.set("my-key", "value");
console.log(result);
```

</Accordion>

<Accordion title="node-redis" icon="node-js" iconType="brands">

```ts
import { createClient } from "redis";

const client = await createClient({ url: process.env.REDIS_URL })
  .on("error", console.error)
  .connect();
const result = await client.set("my-key", "value");
console.log(result);
```

</Accordion>

<Accordion title="redis-py" icon="python" iconType="brands">

```python
import os
import redis

client = redis.from_url(os.environ["REDIS_URL"])
result = client.set("my-key", "value")
print(result)
```

</Accordion>

<Accordion title="go-redis" icon="golang" iconType="brands">

```go
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/redis/go-redis/v9"
)

func main() {
    opts, err := redis.ParseURL(os.Getenv("REDIS_URL"))
    if err != nil {
        panic(err)
    }
    client := redis.NewClient(opts)
    result, err := client.Set(context.Background(), "my-key", "value", 0).Result()
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}
```

</Accordion>

<Accordion title="jedis" icon="java" iconType="brands">

```java
import java.net.URI;

import redis.clients.jedis.Jedis;

try (Jedis jedis = new Jedis(new URI(System.getenv("REDIS_URL")))) {
  Object result = jedis.set("my-key", "value");
  System.out.println(result);
}
```

</Accordion>

<Accordion title="redis-rs" icon="rust" iconType="brands">

```rust
use redis::TypedCommands;

fn main() -> redis::RedisResult<()> {
    let url = std::env::var("REDIS_URL").expect("REDIS_URL is not set");
    let client = redis::Client::open(url)?;
    let mut connection = client.get_connection()?;

    let result = connection.set("my-key", "value")?;
    println!("{result:?}");
    Ok(())
}
```

</Accordion>

</AccordionGroup>
