How to Use ZCARD in Redis: Syntax and Examples
Use the
ZCARD command in Redis to get the number of elements in a sorted set. The command takes the key of the sorted set and returns an integer count of its members.Syntax
The ZCARD command syntax is simple:
ZCARD key: Returns the number of elements in the sorted set stored atkey.
If the key does not exist, it returns 0.
redis
ZCARD mySortedSet
Example
This example shows how to add elements to a sorted set and then use ZCARD to count them.
redis
127.0.0.1:6379> ZADD mySortedSet 1 "apple" 2 "banana" 3 "cherry" (integer) 3 127.0.0.1:6379> ZCARD mySortedSet (integer) 3
Output
(integer) 3
Common Pitfalls
Common mistakes when using ZCARD include:
- Using
ZCARDon a key that is not a sorted set, which returns an error. - Expecting
ZCARDto return the count of elements in other data types like sets or lists. - Not handling the case when the key does not exist, which returns 0.
redis
127.0.0.1:6379> SET myKey "value" OK 127.0.0.1:6379> ZCARD myKey (error) WRONGTYPE Operation against a key holding the wrong kind of value -- Correct usage -- 127.0.0.1:6379> ZADD mySortedSet 1 "one" (integer) 1 127.0.0.1:6379> ZCARD mySortedSet (integer) 1
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
(integer) 1
Quick Reference
| Command | Description |
|---|---|
| ZCARD key | Returns the number of elements in the sorted set at key |
| Returns 0 if key does not exist | No error, just zero count |
| Error if key is not a sorted set | Wrong type error returned |
Key Takeaways
ZCARD returns the count of elements in a sorted set by key.
If the key does not exist, ZCARD returns 0 without error.
Using ZCARD on a non-sorted set key causes a type error.
ZCARD only works with sorted sets, not other Redis data types.