0
0
Redisquery~5 mins

List vs sorted set for sequences in Redis

Choose your learning style9 modes available
Introduction

Lists and sorted sets are two ways to store sequences in Redis. They help keep items in order but work differently.

When you want to keep items in the order they were added and access them by position.
When you need to store items with a score to sort them automatically.
When you want to add or remove items quickly from the start or end of a sequence.
When you want to get items sorted by a custom score, like timestamps or priorities.
When you want to avoid duplicates and keep items unique with a score.
Syntax
Redis
List commands:
LPUSH key value1 [value2 ...]  # Add items to the start
RPUSH key value1 [value2 ...]  # Add items to the end
LRANGE key start stop          # Get items by index range

Sorted Set commands:
ZADD key score1 member1 [score2 member2 ...]  # Add items with scores
ZRANGE key start stop [WITHSCORES]            # Get items by rank range
ZRANGEBYSCORE key min max [WITHSCORES]         # Get items by score range

Lists keep order by insertion and allow duplicates.

Sorted sets keep items unique and order by score.

Examples
Adds "banana" and "apple" to the start of the list, then gets all items.
Redis
LPUSH mylist "apple" "banana"
LRANGE mylist 0 -1
Adds "apple" and "banana" to the end of the list, then gets all items.
Redis
RPUSH mylist "apple" "banana"
LRANGE mylist 0 -1
Adds "apple" with score 10 and "banana" with score 20, then gets all items with scores sorted by score.
Redis
ZADD myset 10 "apple" 20 "banana"
ZRANGE myset 0 -1 WITHSCORES
Adds "apple" and "banana" with scores, then gets items with scores between 0 and 10.
Redis
ZADD myset 10 "apple"
ZADD myset 5 "banana"
ZRANGEBYSCORE myset 0 10 WITHSCORES
Sample Program

This example shows how to add items to a list and a sorted set, then retrieve them. The list keeps insertion order. The sorted set orders by score.

Redis
# Using Redis CLI commands

# Create a list and add items
RPUSH fruits "apple"
RPUSH fruits "banana"
RPUSH fruits "cherry"

# Show list items
LRANGE fruits 0 -1

# Create a sorted set and add items with scores
ZADD fruit_scores 3 "apple"
ZADD fruit_scores 1 "banana"
ZADD fruit_scores 2 "cherry"

# Show sorted set items with scores
ZRANGE fruit_scores 0 -1 WITHSCORES
OutputSuccess
Important Notes

Lists are simple and fast for adding/removing items at ends (O(1) time).

Sorted sets keep items unique and sorted by score, but adding is O(log n) time.

Use lists when order of insertion matters and duplicates are allowed.

Use sorted sets when you need automatic sorting by score and uniqueness.

Summary

Lists store ordered sequences with duplicates allowed.

Sorted sets store unique items sorted by a numeric score.

Choose lists for simple order, sorted sets for scored sorting.