0
0
Redisquery~10 mins

Why sets store unique elements in Redis - Visual Breakdown

Choose your learning style9 modes available
Concept Flow - Why sets store unique elements
Add element to set
Check if element exists?
YesIgnore, no duplicate added
No
Insert element
Set updated with unique elements
When adding an element to a Redis set, it first checks if the element already exists. If yes, it ignores the addition to keep elements unique. Otherwise, it inserts the new element.
Execution Sample
Redis
SADD myset apple
SADD myset banana
SADD myset apple
Add 'apple' and 'banana' to set 'myset', then try adding 'apple' again which is ignored.
Execution Table
StepCommandElementSet BeforeElement Exists?ActionSet After
1SADD myset appleapple{}NoInsert 'apple'{apple}
2SADD myset bananabanana{apple}NoInsert 'banana'{apple, banana}
3SADD myset appleapple{apple, banana}YesIgnore duplicate{apple, banana}
💡 No more commands; set contains unique elements only
Variable Tracker
VariableStartAfter 1After 2After 3
myset{}{apple}{apple, banana}{apple, banana}
Key Moments - 2 Insights
Why doesn't the set add 'apple' the second time?
Because the set checks if 'apple' already exists (see step 3 in execution_table). Since it does, it ignores the duplicate to keep elements unique.
What happens if we add a new element not in the set?
The set inserts the new element (see step 2), expanding the set without duplicates.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the set content after step 2?
A{apple}
B{banana}
C{apple, banana}
D{}
💡 Hint
Check the 'Set After' column in row for step 2
At which step does the set ignore adding a duplicate element?
AStep 3
BStep 2
CStep 1
DNo step ignores duplicates
💡 Hint
Look at the 'Action' column for step 3 in execution_table
If we add 'cherry' after step 3, what will the set contain?
A{cherry}
B{apple, banana, cherry}
C{apple, banana}
D{}
💡 Hint
Adding a new unique element inserts it, as shown in steps 1 and 2
Concept Snapshot
Redis sets store only unique elements.
When adding, Redis checks if element exists.
If yes, it ignores duplicates.
If no, it inserts the element.
This ensures no repeated values in the set.
Full Transcript
In Redis, sets are collections that hold unique elements only. When you add an element using SADD, Redis first checks if the element is already in the set. If it is, Redis ignores the addition to prevent duplicates. If not, Redis inserts the new element. For example, adding 'apple' twice results in only one 'apple' in the set. This behavior keeps sets unique and efficient for membership checks.