ZADD
ZADD key [NX | XX] [GT | LT] [CH] [INCR] score member [score member ...]
- Group
- Sorted set
- Complexity
- O(log(N)) for each member added or updated, where N is the size of the sorted set
- Arity
- -4 (at least 4 words, counting the command name)
- Flags
- write, fast
- Keys
- first 1, last 1, step 1
- HotKV Cloud
- All plans
- On-Premise
- no license needed
ZADD adds each member with its score to the sorted set stored at key,
creating the sorted set if the key does not exist. If a member is already
present, its score is updated and it moves to its new position.
Scores are double-precision floating-point numbers. You can write them as
integers, decimals, with an exponent, or as inf, +inf and -inf. Members
with equal scores are ordered lexicographically.
Options
Section titled “Options”| Option | Effect |
|---|---|
NX |
Only add new members; never update existing ones. |
XX |
Only update existing members; never add new ones. |
GT |
Only update an existing member if the new score is greater. New members are still added. |
LT |
Only update an existing member if the new score is less. New members are still added. |
CH |
Return the number of members added or whose score changed, instead of only the number added. |
INCR |
Add score to the member’s current score, like ZINCRBY. Only one score/member pair is allowed. |
NX and XX cannot be combined, and neither can GT and LT, or NX with
GT or LT. Options come before the first score/member pair.
Return value
Section titled “Return value”| Case | RESP2 | RESP3 |
|---|---|---|
Without INCR |
Integer: the number of members added (with CH, added or changed) |
Same |
With INCR |
Bulk string: the new score | Double: the new score |
With INCR, blocked by NX, XX, GT or LT |
Nil bulk string | Null |
Errors:
WRONGTYPEifkeyholds a value that is not a sorted set.ERR XX and NX options at the same time are not compatible.ERR GT, LT, and/or NX options at the same time are not compatible.ERR syntax errorif a score has no member.ERR value is not a valid floatif a score is not a number.ERR INCR option supports a single increment-element pair.ERR resulting score is not a number (NaN)ifINCRwould produce NaN (for example adding-inftoinf).
Examples
Section titled “Examples”127.0.0.1:6379> ZADD board 100 "alice" 85 "bob"(integer) 2127.0.0.1:6379> ZADD board XX GT CH 90 "bob" 80 "alice"(integer) 1127.0.0.1:6379> ZADD board NX INCR 5 "carol""5"127.0.0.1:6379> ZADD board NX INCR 5 "alice"(nil)127.0.0.1:6379> ZRANGE board 0 -1 WITHSCORES1) "carol"2) "5"3) "bob"4) "90"5) "alice"6) "100"Compatibility
Section titled “Compatibility”Same options and replies as Redis 7.4 and Valkey 8. One ordering difference:
HotKV checks the key’s type first, so on a key of another type you get
WRONGTYPE even when the options conflict or a score is invalid, where Redis
and Valkey report the option or score error.
See also
Section titled “See also”Was this page helpful?
Thanks for the feedback.