# GETEX

> Return the string value of a key and optionally change its time to live.

URL: https://docs.hotkv.com/commands/getex/

```
GETEX key [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | PERSIST]
```

- Group: String
- Complexity: O(1)
- HotKV Cloud: all plans
- On-Premise: no license needed

`GETEX` returns the string at `key` like [GET](https://docs.hotkv.com/commands/get/index.md) and, in the
same step, sets or removes its time to live. Without an option it behaves like
`GET`. Use it for sliding expiry, where each read extends the key's life.

## Options

| Option | Effect |
| --- | --- |
| `EX seconds` | Expire after this many seconds. |
| `PX milliseconds` | Expire after this many milliseconds. |
| `EXAT unix-time-seconds` | Expire at this Unix time, in seconds. |
| `PXAT unix-time-milliseconds` | Expire at this Unix time, in milliseconds. |
| `PERSIST` | Remove the time to live. |

Only one option can be given. Times must be positive integers. An absolute
time that has already passed returns the value and deletes the key.

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| The key holds a string | Bulk string: the value | Bulk string |
| The key does not exist | Nil bulk string | Null |

Errors:

- `WRONGTYPE` when the key holds a value that is not a string.
- `ERR syntax error` for an unknown option, more than one option, or an option
  without its value.
- `ERR value is not an integer or out of range` when the time is not an
  integer.
- `ERR invalid expire time in 'getex' command` when the time is zero, negative
  or overflows.

## Examples

```
127.0.0.1:6379> SET session "user:7"
OK
127.0.0.1:6379> GETEX session EX 900
"user:7"
127.0.0.1:6379> TTL session
(integer) 900
127.0.0.1:6379> GETEX session PERSIST
"user:7"
127.0.0.1:6379> TTL session
(integer) -1
```

## Compatibility

Same as Redis 7 and Valkey 8.

## See also

[GET](https://docs.hotkv.com/commands/get/index.md), [GETDEL](https://docs.hotkv.com/commands/getdel/index.md),
[EXPIRE](https://docs.hotkv.com/commands/expire/index.md), [PERSIST](https://docs.hotkv.com/commands/persist/index.md),
[SET](https://docs.hotkv.com/commands/set/index.md)