0
0
Redisquery~10 mins

ZCARD for set size in Redis - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - ZCARD for set size
Start
Call ZCARD with key
Check if key exists
Count elements
Return count
The ZCARD command checks if the sorted set key exists, counts its elements if yes, or returns 0 if no.
Execution Sample
Redis
ZADD myset 1 one 2 two 3 three
ZCARD myset
ZCARD unknownset
Add three elements to a sorted set 'myset', then get its size with ZCARD, and check size of a non-existing set.
Execution Table
StepCommandKeyKey Exists?ActionOutput
1ZADDmysetNoCreate 'myset' and add 3 elements3
2ZCARDmysetYesCount elements in 'myset'3
3ZCARDunknownsetNoReturn 0 because key does not exist0
💡 Execution stops after returning the count or 0 for each ZCARD command.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
mysetdoes not existsorted set with 3 elementsunchangedunchanged
unknownsetdoes not existdoes not existdoes not existdoes not exist
Key Moments - 2 Insights
Why does ZCARD return 0 for a key that does not exist?
Because as shown in execution_table row 3, when the key is missing, Redis returns 0 instead of an error.
Does ZCARD count the number of elements or sum their scores?
ZCARD counts the number of elements only, not their scores, as shown in row 2 where output is 3 for three elements.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output of ZCARD for 'myset' at step 2?
AError
B0
C3
D1
💡 Hint
Check the 'Output' column in execution_table row 2.
At which step does Redis create the sorted set 'myset'?
AStep 3
BStep 1
CStep 2
DNo creation happens
💡 Hint
Look at the 'Action' column in execution_table row 1.
If 'unknownset' existed with 5 elements, what would ZCARD return at step 3?
A5
B0
CError
D1
💡 Hint
ZCARD returns the count of elements if the key exists, see execution_table row 2 for example.
Concept Snapshot
ZCARD key
- Returns the number of elements in a sorted set.
- If key does not exist, returns 0.
- Does not sum scores, only counts elements.
- Useful to check size of sorted sets quickly.
Full Transcript
The ZCARD command in Redis returns the number of elements in a sorted set stored at the given key. If the key does not exist, it returns 0 instead of an error. For example, after adding three elements to 'myset', ZCARD 'myset' returns 3. If you call ZCARD on a non-existing key like 'unknownset', it returns 0. This command helps you quickly find out how many members are in a sorted set without retrieving the elements themselves.