Question: What is the difference between a Redis set and sorted set?


Redis provides two similar, but distinct, data structures for storing collections of unique elements: SET and SORTED SET. Understanding their differences can help in selecting the appropriate type based on your application's requirements.

Redis Set

A Redis SET is a collection of unique strings. It is unordered, which means that there is no specific arrangement of elements. Operations like adding, removing, and checking for the existence of elements are very efficient, typically O(1) complexity.

Example operations on a Redis Set:

SADD myset value1 value2 value3 SISMEMBER myset value1 SREM myset value1 SMEMBERS myset
  • SADD adds elements to the set.
  • SISMEMBER checks if an element is in the set.
  • SREM removes an element from the set.
  • SMEMBERS retrieves all elements of the set.

Redis Sorted Set

A Redis SORTED SET, also known as ZSET, is similar to a regular set because it stores unique elements. However, every element in a sorted set is associated with a floating point number called a score. This score is used to keep the elements in a sorted order from the smallest to largest score. This structure supports not just membership testing, but efficient retrieval of ranges of elements based on their scores.

Example operations on a Redis Sorted Set:

ZADD myzset 1 value1 2 value2 3 value3 ZRANGE myzset 0 -1 WITHSCORES ZREM myzset value1 ZRANK myzset value2
  • ZADD adds elements to the sorted set with their scores.
  • ZRANGE retrieves a range of elements (optionally with scores).
  • ZREM removes an element from the sorted set.
  • ZRANK gets the rank (index) of an element by its score.

Key Differences

  1. Ordering: Sets are unordered; Sorted Sets maintain an ordering of elements.
  2. Use Case: Use Sets when you need uniqueness without concern for the order. Sorted Sets are useful when you need to maintain an order of elements, often used for leaderboards, priority queues, etc.
  3. Performance: While both offer O(1) complexity for basic operations like add, remove, and check, Sorted Sets also allow log-time complexity operations due to the underlying data structures that support sorting.

Choosing between a Set and a Sorted Set depends on whether the application requires maintaining an order among the elements and how critical performance considerations are concerning these operations.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book
Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.