How to Use ZCOUNT in Redis: Syntax and Examples
Use the
ZCOUNT command in Redis to count the number of elements in a sorted set with scores between a minimum and maximum value. The syntax is ZCOUNT key min max, where min and max define the score range to count.Syntax
The ZCOUNT command counts members in a sorted set with scores between min and max.
- key: The name of the sorted set.
- min: The minimum score (inclusive or exclusive).
- max: The maximum score (inclusive or exclusive).
Use ( before a number to exclude it from the range (exclusive). Use -inf or +inf for infinite ranges.
redis
ZCOUNT key min max
Example
This example shows how to add members to a sorted set and count how many have scores between 10 and 20 inclusive.
redis
127.0.0.1:6379> ZADD myset 5 "one" 15 "two" 25 "three" (integer) 3 127.0.0.1:6379> ZCOUNT myset 10 20 (integer) 1
Output
(integer) 1
Common Pitfalls
Common mistakes when using ZCOUNT include:
- Using exclusive ranges without
(prefix, which changes the count. - Confusing score values with member names.
- Using string values instead of numeric scores.
Example of exclusive range usage:
redis
127.0.0.1:6379> ZCOUNT myset (5 20 (integer) 1 127.0.0.1:6379> ZCOUNT myset 5 20 (integer) 2
Output
(integer) 1
(integer) 2
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| key | Name of the sorted set | "myset" |
| min | Minimum score (inclusive or exclusive) | 10 or (10 |
| max | Maximum score (inclusive or exclusive) | 20 or (20 |
| -inf | Negative infinity for min score | -inf |
| +inf | Positive infinity for max score | +inf |
Key Takeaways
ZCOUNT counts members in a sorted set within a score range.
Use parentheses before min or max to make the range exclusive.
Scores must be numeric; member names are not used for counting.
Use -inf and +inf for open-ended ranges.
ZCOUNT returns an integer count of matching members.