Skip to content

Ask the HotKV docs

Answers come only from these docs and can be wrong; check the linked pages before you rely on them.

EXPIRE

Last updated
EXPIRE key seconds [NX | XX | GT | LT]
Group
Keys
Complexity
O(1)
Arity
-3 (at least 3 words, counting the command name)
Flags
write, fast
Keys
first 1, last 1, step 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 without KEEPTTL) clear it. Use PERSIST to remove it.

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

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.

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.
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

Same options, replies and errors as Redis 7 and Valkey 8. For nanosecond precision, see NEXPIRE.

PEXPIRE, EXPIREAT, TTL, EXPIRETIME, PERSIST, NEXPIRE