0
0
Redisquery~5 mins

Why sets store unique elements in Redis

Choose your learning style9 modes available
Introduction

Sets in Redis store unique elements to avoid duplicates. This helps keep data clean and makes checking for membership fast and simple.

When you want to keep a list of unique user IDs who liked a post.
When you need to track unique visitors to a website.
When you want to store tags or categories without repeats.
When you want to quickly check if an item is already in a collection.
When you want to perform operations like finding common or different items between groups.
Syntax
Redis
SADD key member [member ...]
SMEMBERS key
SISMEMBER key member
SREM key member

SADD adds unique members to a set.

SMEMBERS returns all members of the set.

Examples
Adds 'apple' and 'banana' to 'myset'. The second 'apple' is ignored because sets store unique elements.
Redis
SADD myset apple banana apple
Returns all unique members of 'myset'.
Redis
SMEMBERS myset
Checks if 'banana' is in 'myset'. Returns 1 if yes, 0 if no.
Redis
SISMEMBER myset banana
Removes 'apple' from 'myset'.
Redis
SREM myset apple
Sample Program

This adds 'apple', 'banana', and 'orange' to the set 'fruits'. The duplicate 'apple' is ignored. Then it lists all unique fruits.

Redis
SADD fruits apple banana apple orange
SMEMBERS fruits
OutputSuccess
Important Notes

Sets automatically ignore duplicate entries, so you don't have to check before adding.

Checking membership in a set is very fast, even with many elements.

Summary

Sets store only unique elements to keep data clean.

This makes adding, checking, and removing items efficient.

Use sets when you need to avoid duplicates and quickly check membership.