{
  "schema_version": 2,
  "id": "commands/set",
  "title": "SET",
  "url": "https://redis.io/docs/latest/commands/set/",
  "summary": "Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.",
  "since": "1.0.0",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-09-18T16:45:12+01:00",
  "page_type": "content",
  "content_hash": "a3c29db62890298d08c621e74bb03832f6f051982dc8f8e27b5c62b720612095",
  "sections": [
    {
      "id": "required-arguments",
      "title": "Required arguments",
      "role": "content",
      "text": "<details open><summary><code>key</code></summary>\n\nThe name of the key.\n\n</details>\n\n<details open><summary><code>value</code></summary>\n\nThe string value to set.\n\n</details>"
    },
    {
      "id": "optional-arguments",
      "title": "Optional arguments",
      "role": "parameters",
      "text": "The following options modify the command's behavior. The condition options (`NX`, `XX`, `IFEQ`, `IFNE`, `IFDEQ`, `IFDNE`) are mutually exclusive, as are the expiration options (`EX`, `PX`, `EXAT`, `PXAT`, `KEEPTTL`).\n\n<details open><summary><code>NX</code></summary>\n\nOnly set the key if it does not already exist.\n\n</details>\n\n<details open><summary><code>XX</code></summary>\n\nOnly set the key if it already exists.\n\n</details>\n\n<details open><summary><code>IFEQ ifeq-value</code></summary>\n\nSet the key's value and expiration only if its current value is equal to `ifeq-value`. If the key doesn't exist, it won't be created.\n\n</details>\n\n<details open><summary><code>IFNE ifne-value</code></summary>\n\nSet the key's value and expiration only if its current value is not equal to `ifne-value`. If the key doesn't exist, it will be created.\n\n</details>\n\n<details open><summary><code>IFDEQ ifdeq-digest</code></summary>\n\nSet the key's value and expiration only if the hash digest of its current value is equal to `ifdeq-digest`. If the key doesn't exist, it won't be created. See the [Hash Digest](#hash-digest) section below for more information.\n\n</details>\n\n<details open><summary><code>IFDNE ifdne-digest</code></summary>\n\nSet the key's value and expiration only if the hash digest of its current value is not equal to `ifdne-digest`. If the key doesn't exist, it will be created. See the [Hash Digest](#hash-digest) section below for more information.\n\n</details>\n\n<details open><summary><code>GET</code></summary>\n\nReturn the old string stored at the key, or nil if the key did not exist. An error is returned and `SET` is aborted if the value stored at the key is not a string.\n\n</details>\n\n<details open><summary><code>EX seconds</code></summary>\n\nSet the specified expire time, in seconds (a positive integer).\n\n</details>\n\n<details open><summary><code>PX milliseconds</code></summary>\n\nSet the specified expire time, in milliseconds (a positive integer).\n\n</details>\n\n<details open><summary><code>EXAT unix-time-seconds</code></summary>\n\nSet the specified Unix time at which the key will expire, in seconds (a positive integer).\n\n</details>\n\n<details open><summary><code>PXAT unix-time-milliseconds</code></summary>\n\nSet the specified Unix time at which the key will expire, in milliseconds (a positive integer).\n\n</details>\n\n<details open><summary><code>KEEPTTL</code></summary>\n\nRetain the time to live associated with the key.\n\n</details>\n\nNote: Since the `SET` command options can replace [`SETNX`](https://redis.io/docs/latest/commands/setnx), [`SETEX`](https://redis.io/docs/latest/commands/setex), [`PSETEX`](https://redis.io/docs/latest/commands/psetex), [`GETSET`](https://redis.io/docs/latest/commands/getset), it is possible that in future versions of Redis these commands will be deprecated and finally removed."
    },
    {
      "id": "examples",
      "title": "Examples",
      "role": "example",
      "text": "Foundational: Set the string value of a key using SET (creates key if needed, overwrites existing value, supports expiration options)\n\n**Difficulty:** Beginner\n\n**Commands:** SET, GET\n\n**Complexity:**\n- SET: O(1)\n- GET: O(1)\n\n**Available in:** Redis CLI, C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), JavaScript (Node.js), PHP, Python, Ruby, Rust (Asynchronous), Rust (Synchronous)\n\n##### Redis CLI\n\n[code example]\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]\n\n##### Ruby\n\n[code example]\n\n##### Rust (Asynchronous)\n\n[code example]\n\n##### Rust (Synchronous)\n\n[code example]"
    },
    {
      "id": "details",
      "title": "Details",
      "role": "content",
      "text": ""
    },
    {
      "id": "hash-digest",
      "title": "Hash digest",
      "role": "content",
      "text": "A hash digest is a fixed-size numerical representation of a string value, computed using the XXH3 hash algorithm. Redis uses this hash digest for efficient comparison operations without needing to compare the full string content. You can retrieve a key's hash digest using the [`DIGEST`](https://redis.io/docs/latest/commands/digest) command, which returns it as a hexadecimal string that you can use with the `IFDEQ` and `IFDNE` options, and also the [`DELEX`](https://redis.io/docs/latest/commands/delex) command's `IFDEQ` and `IFDNE` options."
    },
    {
      "id": "patterns",
      "title": "Patterns",
      "role": "content",
      "text": "Note: The following pattern is discouraged in favor of [the Redlock algorithm](https://redis.io/docs/latest/develop/clients/patterns/distributed-locks) which is only a bit more complex to implement, but offers better guarantees and is fault tolerant.\n\nThe command `SET resource-name anystring NX EX max-lock-time` is a simple way to implement a locking system with Redis.\n\nA client can acquire the lock if the above command returns `OK` (or retry after some time if the command returns Nil), and remove the lock just using [`DEL`](https://redis.io/docs/latest/commands/del).\n\nThe lock will be auto-released after the expire time is reached.\n\nIt is possible to make this system more robust modifying the unlock schema as follows:\n\n* Instead of setting a fixed string, set a non-guessable large random string, called token.\n* Instead of releasing the lock with [`DEL`](https://redis.io/docs/latest/commands/del), send a script that only removes the key if the value matches.\n\nThis avoids that a client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later.\n\nAn example of unlock script would be similar to the following:\n\n    if redis.call(\"get\",KEYS[1]) == ARGV[1]\n    then\n        return redis.call(\"del\",KEYS[1])\n    else\n        return 0\n    end\n\nThe script should be called with `EVAL ...script... 1 resource-name token-value`"
    },
    {
      "id": "redis-software-and-redis-cloud-compatibility",
      "title": "Redis Software and Redis Cloud compatibility",
      "role": "content",
      "text": "| Redis<br />Software | Redis<br />Cloud | <span style=\"min-width: 9em; display: table-cell\">Notes</span> |\n|:----------------------|:-----------------|:------|\n| <span title=\"Supported\">&#x2705; Standard</span><br /><span title=\"Supported\"><nobr>&#x2705; Active-Active</nobr></span> | <span title=\"Supported\">&#x2705; Standard</span><br /><span title=\"Supported\"><nobr>&#x2705; Active-Active</nobr></span> |  |"
    },
    {
      "id": "return-information",
      "title": "Return information",
      "role": "returns",
      "text": "**RESP2:**\n\n* If `GET` was not specified, one of the following:\n  * [Null bulk string reply](../../develop/reference/protocol-spec#bulk-strings) in the following two cases.\n    * The key doesn’t exist and `XX/IFEQ/IFDEQ` was specified. The key was not created.\n    * The key exists, and `NX` was specified or a specified `IFEQ/IFNE/IFDEQ/IFDNE` condition is false. The key was not set.\n  * [Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK`: The key was set.\n* If `GET` was specified, one of the following:\n  * [Null bulk string reply](../../develop/reference/protocol-spec#bulk-strings): The key didn't exist before the `SET` operation, whether the key was created of not.\n  * [Bulk string reply](../../develop/reference/protocol-spec#bulk-strings): The previous value of the key, whether the key was set or not.\n\n**RESP3:**\n\n* If `GET` was not specified, one of the following:\n  * [Null reply](../../develop/reference/protocol-spec#nulls) in the following two cases.\n    * The key doesn’t exist and `XX/IFEQ/IFDEQ` was specified. The key was not created.\n    * The key exists, and `NX` was specified or a specified `IFEQ/IFNE/IFDEQ/IFDNE` condition is false. The key was not set.\n  * [Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK`: The key was set.\n* If `GET` was specified, one of the following:\n  * [Null reply](../../develop/reference/protocol-spec#nulls): The key didn't exist before the `SET` operation, whether the key was created of not.\n  * [Bulk string reply](../../develop/reference/protocol-spec#bulk-strings): The previous value of the key, whether the key was set or not."
    }
  ],
  "examples": [
    {
      "id": "examples-ex0",
      "language": "plaintext",
      "code": "> SET mykey \"Hello\"\nOK\n> GET mykey\n\"Hello\"\n> SET anotherkey \"will expire in a minute\" EX 60\nOK",
      "section_id": "examples"
    },
    {
      "id": "examples-ex1",
      "language": "csharp",
      "code": "using NRedisStack.Tests;\nusing StackExchange.Redis;\n\npublic class SetGetExample\n{\n    public void Run()\n    {\n        var muxer = ConnectionMultiplexer.Connect(\"localhost:6379\");\n        var db = muxer.GetDatabase();\n\n        bool status = db.StringSet(\"bike:1\", \"Process 134\");\n\n        if (status)\n            Console.WriteLine(\"Successfully added a bike.\");\n\n        var value = db.StringGet(\"bike:1\");\n\n        if (value.HasValue)\n            Console.WriteLine(\"The name of the bike is: \" + value + \".\");\n\n    }\n}",
      "section_id": "examples"
    },
    {
      "id": "examples-ex2",
      "language": "go",
      "code": "package example_commands_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/redis/go-redis/v9\"\n)\n\nfunc ExampleClient_Set_and_get() {\n\tctx := context.Background()\n\n\trdb := redis.NewClient(&redis.Options{\n\t\tAddr:     \"localhost:6379\",\n\t\tPassword: \"\", // no password docs\n\t\tDB:       0,  // use default DB\n\t})\n\n\n\n\terr := rdb.Set(ctx, \"bike:1\", \"Process 134\", 0).Err()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"OK\")\n\n\tvalue, err := rdb.Get(ctx, \"bike:1\").Result()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"The name of the bike is %s\", value)\n\n}",
      "section_id": "examples"
    },
    {
      "id": "examples-ex3",
      "language": "java",
      "code": "package io.redis.examples.async;\n\nimport io.lettuce.core.RedisClient;\nimport io.lettuce.core.api.async.RedisAsyncCommands;\nimport io.lettuce.core.api.StatefulRedisConnection;\n\nimport java.util.concurrent.CompletableFuture;\n\npublic class SetGetExample {\n\n    public void run() {\n        RedisClient redisClient = RedisClient.create(\"redis://localhost:6379\");\n\n        try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {\n            RedisAsyncCommands<String, String> asyncCommands = connection.async();\n\n\n            CompletableFuture<Void> setGetExample = asyncCommands.set(\"bike:1\", \"Process 134\")\n                    .thenCompose(res1 -> {\n                        System.out.println(res1); // >>> OK\n                        return asyncCommands.get(\"bike:1\");\n                    }).thenAccept(res2 -> {\n                        System.out.println(res2); // >>> Process 134\n                    }).toCompletableFuture();\n\n            setGetExample.join();\n        } finally {\n            redisClient.shutdown();\n        }\n    }\n}",
      "section_id": "examples"
    },
    {
      "id": "examples-ex4",
      "language": "java",
      "code": "package io.redis.examples.reactive;\n\nimport io.lettuce.core.RedisClient;\nimport io.lettuce.core.api.reactive.RedisReactiveCommands;\nimport io.lettuce.core.api.StatefulRedisConnection;\n\nimport reactor.core.publisher.Mono;\n\npublic class SetGetExample {\n\n    public void run() {\n        RedisClient redisClient = RedisClient.create(\"redis://localhost:6379\");\n\n        try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {\n            RedisReactiveCommands<String, String> reactiveCommands = connection.reactive();\n\n\n            Mono<Void> setGetExample = reactiveCommands.set(\"bike:1\", \"Process 134\")\n                    .doOnNext(res1 -> {\n                        System.out.println(res1); // >>> OK\n                    })\n                    .then(reactiveCommands.get(\"bike:1\"))\n                    .doOnNext(res2 -> {\n                        System.out.println(res2); // >>> Process 134\n                    })\n                    .then();\n\n            setGetExample.block();\n        } finally {\n            redisClient.shutdown();\n        }\n    }\n}",
      "section_id": "examples"
    },
    {
      "id": "examples-ex5",
      "language": "java",
      "code": "package io.redis.examples;\n\nimport redis.clients.jedis.RedisClient;\n\n\npublic class SetGetExample {\n\n  public void run() {\n\n    RedisClient jedis = RedisClient.create(\"redis://localhost:6379\");\n\n    String status = jedis.set(\"bike:1\", \"Process 134\");\n\n    if (\"OK\".equals(status)) System.out.println(\"Successfully added a bike.\");\n\n    String value = jedis.get(\"bike:1\");\n\n    if (value != null) System.out.println(\"The name of the bike is: \" + value + \".\");\n\n\n    jedis.close();\n  }\n}",
      "section_id": "examples"
    },
    {
      "id": "examples-ex6",
      "language": "javascript",
      "code": "import { createClient } from 'redis';\n\nconst client = createClient();\n\nclient.on('error', err => console.log('Redis Client Error', err));\n\nawait client.connect().catch(console.error);\n\nawait client.set('bike:1', 'Process 134');\nconst value = await client.get('bike:1');\nconsole.log(value);\n// returns 'Process 134'\n\nawait client.close();",
      "section_id": "examples"
    },
    {
      "id": "examples-ex7",
      "language": "javascript",
      "code": "import assert from 'node:assert';\nimport { Redis } from 'ioredis';\n\nconst redis = new Redis();\n\n\nconst res1 = await redis.set('bike:1', 'Process 134');\nconsole.log(res1); // >>> OK\n\nconst res2 = await redis.get('bike:1');\nconsole.log(res2); // >>> Process 134\n\n\nredis.disconnect();",
      "section_id": "examples"
    },
    {
      "id": "examples-ex8",
      "language": "javascript",
      "code": "import { createClient } from 'redis';\n\nconst client = createClient();\n\nclient.on('error', err => console.log('Redis Client Error', err));\n\nawait client.connect().catch(console.error);\n\nawait client.set('bike:1', 'Process 134');\nconst value = await client.get('bike:1');\nconsole.log(value);\n// returns 'Process 134'\n\nawait client.close();",
      "section_id": "examples"
    },
    {
      "id": "examples-ex9",
      "language": "javascript",
      "code": "import assert from 'node:assert';\nimport { Redis } from 'ioredis';\n\nconst redis = new Redis();\n\n\nconst res1 = await redis.set('bike:1', 'Process 134');\nconsole.log(res1); // >>> OK\n\nconst res2 = await redis.get('bike:1');\nconsole.log(res2); // >>> Process 134\n\n\nredis.disconnect();",
      "section_id": "examples"
    },
    {
      "id": "examples-ex10",
      "language": "php",
      "code": "<?php\nuse Predis\\Client as PredisClient;\n\nclass SetGetTest\n{\n    public function testSetGet() {\n        $r = new PredisClient([\n            'scheme'   => 'tcp',\n            'host'     => '127.0.0.1',\n            'port'     => 6379,\n            'password' => '',\n            'database' => 0,\n        ]);\n\n\n        $res1 = $r->set('bike:1', 'Process 134');\n        echo $res1 . PHP_EOL; // >>> OK\n\n        $res2 = $r->get('bike:1');\n        echo $res2 . PHP_EOL; // >>> Process 134\n\n    }\n}",
      "section_id": "examples"
    },
    {
      "id": "examples-ex11",
      "language": "python",
      "code": "\"\"\"\nCode samples for data structure store quickstart pages:\n    https://redis.io/docs/latest/develop/get-started/data-store/\n\"\"\"\n\nimport redis\n\nr = redis.Redis(host=\"localhost\", port=6379, db=0, decode_responses=True)\n\nres = r.set(\"bike:1\", \"Process 134\")\nprint(res)\n# >>> True\n\nres = r.get(\"bike:1\")\nprint(res)\n# >>> \"Process 134\"",
      "section_id": "examples"
    },
    {
      "id": "examples-ex12",
      "language": "ruby",
      "code": "require 'redis'\n\nr = Redis.new\n\n\nres1 = r.set('bike:1', 'Process 134')\nputs res1 # >>> OK\n\nres2 = r.get('bike:1')\nputs res2 # >>> Process 134",
      "section_id": "examples"
    },
    {
      "id": "examples-ex13",
      "language": "rust",
      "code": "mod set_and_get_tests {\n    use redis::AsyncCommands;\n\n    async fn run() {\n        let mut r = match redis::Client::open(\"redis://127.0.0.1\") {\n            Ok(client) => match client.get_multiplexed_async_connection().await {\n                Ok(conn) => conn,\n                Err(e) => {\n                    println!(\"Failed to connect to Redis: {e}\");\n                    return;\n                }\n            },\n            Err(e) => {\n                println!(\"Failed to create Redis client: {e}\");\n                return;\n            }\n        };\n\n\n        if let Ok(res1) = r.set(\"bike:1\", \"Process 134\").await {\n            let res1: String = res1;\n            println!(\"{res1}\"); // >>> OK\n        }\n\n        if let Ok(res2) = r.get(\"bike:1\").await {\n            let res2: String = res2;\n            println!(\"{res2}\"); // >>> Process 134\n        }\n\n    }\n}",
      "section_id": "examples"
    },
    {
      "id": "examples-ex14",
      "language": "rust",
      "code": "mod set_and_get_tests {\n    use redis::Commands;\n\n    fn run() {\n        let mut r = match redis::Client::open(\"redis://127.0.0.1\") {\n            Ok(client) => match client.get_connection() {\n                Ok(conn) => conn,\n                Err(e) => {\n                    println!(\"Failed to connect to Redis: {e}\");\n                    return;\n                }\n            },\n            Err(e) => {\n                println!(\"Failed to create Redis client: {e}\");\n                return;\n            }\n        };\n\n\n        if let Ok(res1) = r.set(\"bike:1\", \"Process 134\") {\n            let res1: String = res1;\n            println!(\"{res1}\"); // >>> OK\n        }\n\n        if let Ok(res2) = r.get(\"bike:1\") {\n            let res2: String = res2;\n            println!(\"{res2}\"); // >>> Process 134\n        }\n\n    }\n}",
      "section_id": "examples"
    }
  ]
}
