Redis ZCOUNT Command Explained

In Redis, the ZCOUNT command returns the number of elements in a sorted set with a score between two given values.

Syntax

The syntax goes like this:

ZCOUNT key min max

Example

Suppose we create a sorted set like this:

ZADD scores 220 user:1 110 user:2 330 user:3 550 user:4 440 user:5 660 user:6

Result:

(integer) 6

In my case the sorted set didn’t exist, and so it was created and the six elements were added as specified.

We can now use the ZCOUNT command to find out how many elements in the sorted set are within a certain range:

ZCOUNT scores 200 500

Result:

(integer) 3

This example tells us that there are three element with a score between 200 and 500.

Inclusive vs Exclusive

The min and max arguments have the same semantic as the ZRANGE command when using the BYSCORE argument (which is the same as the deprecated ZRANGEBYSCORE command). That is, we can use the ( character to make the range exclusive.

By default, the range is inclusive. Therefore, any element that has the exact min or max argument is included in the result:

ZCOUNT scores 220 550

Result:

(integer) 4

We can make this an exclusive range by incorporating the ( character. Here’s what happens when we prefix the min argument with the ( character:

ZCOUNT scores (220 550

Result:

(integer) 3

This example excluded the element with the score of exactly 220.

And here it is when we prefix both the min and max arguments:

ZCOUNT scores (220 (550

Result:

(integer) 2

In this case, it also excluded the element with the score of exactly 550.

When the Key Doesn’t Exist

If the key doesn’t exist, ZCOUNT returns zero:

ZCOUNT nonexistentkey 220 550

Result:

(integer) 0

In this case, nonexistentkey doesn’t exist and so the command returned zero.