Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 42 ยท Core Data Types

Sets

Learn Redis sets: SADD, SREM, SISMEMBER, SINTER, SUNION, SDIFF, SPOP, SRANDMEMBER and SSCAN, with tags and unique visitors, using a live emulator.

A Redis set is an unordered collection of unique strings. Adding the same member twice does nothing the second time, checking whether a member is present is a constant-time operation, and you can combine sets with the same operations you know from school: intersection, union and difference. That makes sets the natural home for things like tags, "who liked this post", "which users visited today", or "which feature flags are on for this account".

A set has no positions and no duplicates. If you need an order, look at lists (order of insertion) or sorted sets (order by score). If you need a value attached to each member, a hash or a sorted set fits better.

Real Redis cannot run inside this page, so the redis-cli snippets are read-only. Every runnable example uses a small emulator written in plain JavaScript that implements the set commands with the same replies and rules (including the WRONGTYPE error and the fact that an empty set disappears). It is a teaching stand-in, not Redis: its random commands use a seeded generator, and it sorts SMEMBERS so the output stays the same on every run.

What a set gives you

Unique A member exists once or not at all.
Fast lookup SISMEMBER is O(1).
Unordered No index, no position.
Set algebra Intersect, union, subtract.
1 / 2

Adding, removing and testing members

SADD key member [member ...] adds one or more members and returns how many were new. SREM removes members and returns how many were actually removed. SISMEMBER answers 1 or 0, SMISMEMBER checks several members at once, SCARD returns the size and SMEMBERS returns everything.

Text
127.0.0.1:6379> SADD post:7:tags redis cache nosql redis
(integer) 3
127.0.0.1:6379> SISMEMBER post:7:tags cache
(integer) 1
127.0.0.1:6379> SCARD post:7:tags
(integer) 3

The duplicate redis in the first command was ignored, so only three members were new. A set is created by the first SADD and deleted automatically when its last member is removed, so you never see an empty set as a key.

The first TryIt defines the emulator and runs these commands. Read the replies the way redis-cli prints them: (integer) for numbers, quoted strings for members, (nil) for "nothing". Try changing the members, or add a SET followed by an SADD on the same key to trigger the type error.

JS Set basics in the emulator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

SMEMBERS returns the whole set in one reply, which is fine for ten tags and painful for ten million members. Section "Walking a big set with SSCAN" shows the safe alternative.

Set algebra: SINTER, SUNION and SDIFF

Three commands combine sets and return the result:

  • SINTER a b ... returns members present in every set.
  • SUNION a b ... returns members present in at least one set.
  • SDIFF a b ... returns members of the first set that are in none of the others. Order matters here: SDIFF a b is not SDIFF b a.

Each has a ...STORE variant (SINTERSTORE dest a b) that writes the result into a new set and returns its size, which is how you keep the answer for later without sending it to the client. SINTERCARD returns only the size of an intersection, with an optional LIMIT so Redis can stop early. A missing key counts as an empty set, which makes SINTER with a missing key empty and SDIFF with a missing second key simply the first set.

Text
SADD friends:ana bo cy dee
SADD friends:bo ana cy eve
SINTER friends:ana friends:bo      # mutual friends -> "cy"
SDIFF friends:ana friends:bo       # ana's friends that bo lacks -> "bo", "dee"

Cost matters. SINTER is roughly proportional to the size of the smallest set times the number of sets, so intersecting a small set with a huge one is cheap. SUNION and SDIFF touch every member of the sets involved, which can block the single-threaded server when the sets are large.

SMEMBERS, SUNION and friends are O(N) and run to completion before Redis serves anyone else. On sets with millions of members, use SSCAN, SINTERCARD ... LIMIT, or the ...STORE variants from a background job rather than from a request handler.

The second TryIt reuses the emulator (this time with the algebra commands added) to model friend lists and a tag search that finds every post carrying both tags.

JS Mutual friends and tag search

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real-world patterns

Tags and categories. Keep one set per post (post:7:tags) to answer "what tags does this post have", and one set per tag (tag:redis) to answer "which posts have this tag". Your application writes to both on every change, which is the usual Redis trade: duplicate the data so each question is one command. Finding posts with several tags at once is a single SINTER.

Unique visitors. SADD visitors:2026-11-08 user:42 counts a user only once no matter how often they come back, and SCARD gives the day's total. Combine days with SUNIONSTORE for a weekly figure. The cost is memory proportional to the number of distinct visitors. When you only need an approximate count of millions of visitors, a HyperLogLog uses about 12 KB no matter how many there are, and when the visitors are numbered users, a bitmap is even smaller.

Relationships. Followers and following are two sets per user. Mutual friends are an intersection and "people you may know" is a union minus what you already follow.

Random picks. SRANDMEMBER key [count] returns random members without removing them. A positive count returns up to that many distinct members; a negative count returns exactly that many and may repeat members. SPOP key [count] removes and returns random members, which fits a raffle or "deal a card" job where each item may be used only once. The third TryIt shows the difference.

Walking a big set with SSCAN

SSCAN key cursor [MATCH pattern] [COUNT n] visits a set in small steps. You start with cursor 0; each reply holds a new cursor and a batch of members, and you stop when the returned cursor is 0 again. Between calls the server is free to handle other clients, so no single call blocks it for long.

The guarantees are looser than SMEMBERS. A member that stayed in the set for the whole scan is returned at least once, but it may be returned more than once, and members added or removed during the scan may or may not appear. COUNT is a hint about the amount of work per call, not a promise about how many members you get back. Real Redis also uses a cursor value that is not a plain position; the emulator below uses a simple index to keep the idea visible. The same idea exists as SCAN, HSCAN and ZSCAN, covered in keys and expiry.

JS SPOP, SRANDMEMBER and SSCAN

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does SADD return?

    SADD replies with the count of members that were actually new, so adding an existing member counts as 0.
  2. 2. Which command returns the members of the first set that are not in any of the other sets?

    SDIFF subtracts the later sets from the first one, and the order of the keys changes the result.
  3. 3. What is the difference between SPOP and SRANDMEMBER?

    Both pick random members, but only SPOP deletes them. SRANDMEMBER with a negative count can also return the same member more than once.
  4. 4. Why prefer SSCAN over SMEMBERS for a set with millions of members?

    SMEMBERS builds one huge reply in a single blocking command. SSCAN splits the walk into small steps, at the price of possible duplicates and a loose view of concurrent changes.
  5. 5. After you remove the last member of a set with SREM, what does EXISTS return for that key?

    Redis never keeps empty collections. When the last member goes, the key disappears.

Summary

  • A set stores unique, unordered strings; SADD returns how many members were new and SISMEMBER checks membership in O(1).
  • SINTER, SUNION and SDIFF combine sets; the ...STORE variants save the result, and SINTERCARD returns only the size.
  • SPOP removes random members, SRANDMEMBER only reads them (a negative count allows repeats).
  • Tags, unique daily visitors and relationships are the classic uses; for huge counts consider HyperLogLog or bitmaps.
  • SMEMBERS and the algebra commands are O(N); walk big sets with SSCAN, accepting duplicates.
  • Empty sets are deleted automatically, and using a set command on a non-set key gives WRONGTYPE.

Next, add a score to every member in Sorted Sets.