How to Use SCARD Command in Redis: Count Set Members
Use the
SCARD command in Redis to get the number of elements in a set stored at a given key. It returns an integer representing the set's cardinality. For example, SCARD myset returns how many members are in the set named myset.Syntax
The SCARD command syntax is simple:
SCARD key: Returns the number of elements in the set stored atkey.- If the key does not exist, it returns 0.
- If the key exists but is not a set, it returns an error.
redis
SCARD key
Example
This example shows how to add members to a set and then use SCARD to count them.
redis
SADD myset apple banana cherry SCARD myset
Output
3
Common Pitfalls
Common mistakes when using SCARD include:
- Using
SCARDon a key that is not a set, which causes an error. - Expecting
SCARDto return members instead of count. - Not checking if the key exists, which returns 0 but might be mistaken for an empty set.
redis
/* Wrong: Using SCARD on a string key */ SET mykey "hello" SCARD mykey /* Right: Use SCARD only on set keys */ SADD myset apple SCARD myset
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
1
Quick Reference
| Command | Description | Return Value |
|---|---|---|
| SCARD key | Returns the number of elements in the set at key | Integer count or 0 if key does not exist |
| SADD key member [member ...] | Adds one or more members to a set | Number of elements added |
| SMEMBERS key | Returns all members of the set | Array of members |
Key Takeaways
SCARD returns the count of members in a Redis set stored at the given key.
If the key does not exist, SCARD returns 0, not an error.
Using SCARD on a non-set key causes an error.
SCARD only counts members; it does not return the members themselves.
Always ensure the key is a set before using SCARD to avoid errors.