# EXPIRE

> Set a key's time to live in seconds.

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

```
EXPIRE key seconds [NX | XX | GT | LT]
```

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

`EXPIRE` makes `key` expire after `seconds`. When the time is up the key is
deleted. Setting a new time replaces the old one, and commands that overwrite
the value (such as [SET](https://docs.hotkv.com/commands/set/index.md) without `KEEPTTL`) clear it. Use
[PERSIST](https://docs.hotkv.com/commands/persist/index.md) to remove it.

A time of zero or less deletes the key at once, and the command still replies
`1`.

## Options

| Option | Effect |
| --- | --- |
| `NX` | Set the time only if the key has none. |
| `XX` | Set the time only if the key already has one. |
| `GT` | Set the time only if it is later than the current one. A key with no time to live counts as never expiring, so `GT` never applies to it. |
| `LT` | Set the time only if it is earlier than the current one. A key with no time to live always accepts `LT`. |

`NX` cannot be combined with `XX`, `GT` or `LT`, and `GT` cannot be combined
with `LT`. The options are checked before `seconds` is parsed.

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| The time was set (or the key was deleted) | Integer `1` | Integer `1` |
| The key does not exist, or an option prevented the change | Integer `0` | Integer `0` |

Errors:

- `ERR value is not an integer or out of range` when `seconds` is not an
  integer.
- `ERR invalid expire time in 'expire' command` when the resulting time
  overflows.
- `ERR Unsupported option` followed by the option, for an unknown option.
- `ERR NX and XX, GT or LT options at the same time are not compatible` and
  `ERR GT and LT options at the same time are not compatible`.

## Examples

```
127.0.0.1:6379> SET session "abc"
OK
127.0.0.1:6379> EXPIRE session 120
(integer) 1
127.0.0.1:6379> TTL session
(integer) 120
127.0.0.1:6379> EXPIRE session 60 GT
(integer) 0
127.0.0.1:6379> EXPIRE session 300 GT
(integer) 1
127.0.0.1:6379> EXPIRE session 10 NX
(integer) 0
127.0.0.1:6379> EXPIRE missing 10
(integer) 0
```

## Compatibility

Same options, replies and errors as Redis 7 and Valkey 8. For nanosecond
precision, see [NEXPIRE](https://docs.hotkv.com/commands/nexpire/index.md).

## See also

[PEXPIRE](https://docs.hotkv.com/commands/pexpire/index.md), [EXPIREAT](https://docs.hotkv.com/commands/expireat/index.md),
[TTL](https://docs.hotkv.com/commands/ttl/index.md), [EXPIRETIME](https://docs.hotkv.com/commands/expiretime/index.md),
[PERSIST](https://docs.hotkv.com/commands/persist/index.md), [NEXPIRE](https://docs.hotkv.com/commands/nexpire/index.md)