0
0
Redisquery~10 mins

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

Choose your learning style9 modes available
Concept Flow - SCARD for set size
Start
Receive SCARD command with key
Check if key exists
Count members
Return count as result
End
The SCARD command checks if the set key exists, counts its members if yes, or returns 0 if no, then returns the count.
Execution Sample
Redis
SADD myset apple banana cherry
SCARD myset
Add three members to a set 'myset' and then get the count of members using SCARD.
Execution Table
StepCommandActionSet StateOutput
1SADD myset apple banana cherryAdd 'apple', 'banana', 'cherry' to 'myset'{myset: ['apple', 'banana', 'cherry']}3
2SCARD mysetCheck if 'myset' exists{myset: ['apple', 'banana', 'cherry']}3
3SCARD unknownsetCheck if 'unknownset' exists{myset: ['apple', 'banana', 'cherry']}0
💡 SCARD returns the number of members if set exists, otherwise 0 if set does not exist.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
mysetundefined['apple', 'banana', 'cherry']['apple', 'banana', 'cherry']['apple', 'banana', 'cherry']
unknownsetundefinedundefinedundefinedundefined
Key Moments - 2 Insights
Why does SCARD return 0 for a key that does not exist?
Because SCARD checks if the set exists first (see execution_table step 3). If the set is missing, it returns 0 instead of an error.
Does SCARD change the set contents?
No, SCARD only counts members without modifying the set, as shown in execution_table step 2 where the set remains unchanged.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output of SCARD for 'myset' at step 2?
A3
B0
CError
D1
💡 Hint
Check the Output column at step 2 in the execution_table.
At which step does the set 'myset' get its members added?
AStep 3
BStep 1
CStep 2
DNo step adds members
💡 Hint
Look at the Command and Action columns in execution_table step 1.
If the set 'unknownset' was created with 2 members before step 3, what would SCARD return at step 3?
AError
B0
C2
D1
💡 Hint
SCARD returns the count of members if the set exists, see execution_table step 3.
Concept Snapshot
SCARD key
- Returns the number of members in the set stored at key.
- If key does not exist, returns 0.
- Does not modify the set.
- Useful to quickly get set size.
- Example: SCARD myset -> returns count.
Full Transcript
The SCARD command in Redis returns the number of members in a set stored at a given key. When you run SCARD with a key, Redis first checks if the set exists. If it does, it counts the members and returns that number. If the set does not exist, SCARD returns 0 instead of an error. For example, after adding three members to 'myset', SCARD myset returns 3. If you ask for a set that does not exist, like 'unknownset', SCARD returns 0. SCARD does not change the set contents; it only counts members. This makes it a safe and fast way to get the size of a set.