Sets

Redis · Essentials · 7 min

Sets answer 'have we seen this?', 'who is online?' and 'what do these groups share?' in one command.

A set is an unordered collection of unique strings. SADD key m1 m2 adds members and returns how many were new, so adding a duplicate is a no-op. SISMEMBER key m (or SMISMEMBER for several) tests membership in O(1), SREM removes, SCARD counts and SMEMBERS returns everything.

Server-side set algebra is the standout feature:

  • SINTER a b members in both, SUNION a b in either, SDIFF a b in a but not b,
  • SINTERSTORE dest a b saves the result as a new set, and SINTERCARD just counts it.

That makes queries like "tags shared by two articles" or "friends of Ana who are online" one round trip with no data shipped to the app.

SRANDMEMBER key n samples members without removing them; SPOP removes and returns random ones, handy for lotteries or distributing work.

Typical uses: unique visitors per day (SADD visitors:2026-10-17 user42), tags, permissions, de-duplication of jobs, and online-user tracking.

SMEMBERS and large SINTER calls are O(N); on sets with millions of members iterate with SSCAN. When you only need an approximate count of unique items, a HyperLogLog uses a few kilobytes instead of memory proportional to the members.

Example

redis-cli SADD online ana ben cy            # (integer) 3
redis-cli SADD online ana                   # (integer) 0  already a member
redis-cli SISMEMBER online ben              # (integer) 1
redis-cli SADD friends:ana ben di cy        # (integer) 3
redis-cli SINTER online friends:ana         # 1) "ben" 2) "cy"  (order not guaranteed)
redis-cli SDIFF friends:ana online          # 1) "di"
redis-cli SCARD online                      # (integer) 3
redis-cli SREM online cy                    # (integer) 1

Remember

  • Sets hold unique members; SADD ignores duplicates
  • SISMEMBER is O(1)
  • SINTER, SUNION, SDIFF compute on the server
  • Members are unordered; use a sorted set when order matters

Watch out for

  • Relying on SMEMBERS returning members in insertion order.

Check yourself

  1. Which command returns the members of friends:ana who are also in online?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: redis.io/docs/latest/develop/data-types/sets/