user
In REDIS, what is the difference between LIST, SET and SORTED SET?
alphonsio

In Redis, LIST, SET, and SORTED SET (ZSET) are different data structures, each with specific characteristics and use cases:


🔹 LIST

Description:
A Redis LIST is an ordered collection of string elements, like a linked list.

Characteristics:

  • Maintains insertion order.
  • Allows duplicate elements.
  • Supports push/pop operations from both ends (LPUSH, RPUSH, LPOP, RPOP).
  • Indexable via LINDEX, LRANGE.

Use cases:

  • Message queues
  • Logs
  • Stacks or queues (FIFO/LIFO)

Example:

RPUSH mylist "a" "b" "c"
LRANGE mylist 0 -1   # ["a", "b", "c"]

🔹 SET

Description:
A Redis SET is an unordered collection of unique string elements.

Characteristics:

  • No order is guaranteed.
  • No duplicates allowed.
  • Fast operations for adding, removing, and checking membership.
  • Supports set operations: SUNION, SINTER, SDIFF.

Use cases:

  • Membership checks
  • Tags or categories
  • Unique collections

Example:

SADD myset "a" "b" "c" "a"
SMEMBERS myset   # {"a", "b", "c"}

🔹 SORTED SET (ZSET)

Description:
A Sorted Set is like a SET but with a score associated with each element, and elements are sorted by score.

Characteristics:

  • Elements are unique.
  • Sorted by a floating-point score (can be negative).
  • Allows range queries by score or rank.
  • Supports operations like ZRANGE, ZREVRANGE, ZADD, ZSCORE.

Use cases:

  • Leaderboards (e.g., top scores)
  • Priority queues
  • Timestamped events

Example:

ZADD myzset 100 "Alice" 200 "Bob" 150 "Charlie"
ZRANGE myzset 0 -1 WITHSCORES  
# [("Alice", 100), ("Charlie", 150), ("Bob", 200)]

Summary Comparison

FeatureLISTSETSORTED SET (ZSET)
OrderYes (insertion)NoYes (by score)
DuplicatesAllowedNot allowedNot allowed
IndexingYes (by position)NoYes (by rank/score)
Main useQueues/logsMembership/tagsRankings/leaderboards