Skip to content

Redis - Sorted Sets

Sorted sets in Redis are sets but with one exception; each element also contains a score value. That score value is used to sort the set in order by the value (smallest to greatest score). Learn more

Adding Elements to a Sorted Set (ZADD)

The ZADD command can be used to add values to a sorted set. For the arguments you will first need to set the score value and the element after that. Learn more

Time Complexity: O( log(N) ) for each item added, where N is the number of elements in the sorted set.

Example usage:

Text Only
ZADD game.tetris.scoreboard 2045 anne 15 mark 17 diane 9024 john
Example Output
(integer) 4

Viewing Elements in a Sorted Set (ZRANGE)

The ZRANGE command can be used to view the elements of a sorted set. For the command you need to pass the starting and ending element number. Note that the ending number can also be -1 to view all the records. Learn more

Time Complexity: O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements returned.

Example usage:

Text Only
ZRANGE game.tetris.scoreboard 0 -1
Example Output
1) "mark"
2) "diane"
3) "anne"
4) "john"
Text Only
ZRANGE game.tetris.scoreboard 0 1
Example Output
1) "mark"
2) "diane"

Viewing Amount of Records in a Sorted Set (ZCARD)

The ZCARD command can be used to view the number of records in a sorted set. Learn more

Time Complexity: O(1)

Example usage:

Text Only
ZCARD game.tetris.scoreboard
Example Output
(integer) 4

Removing Element from a Sorted Set (ZREM)

The ZREM command can be used to remove a element from a sorted set. Learn more

Time Complexity: O(M*log(N)) with N being the number of elements in the sorted set and M the number of elements to be removed.

Example usage:

Text Only
ZREM game.tetris.scoreboard mark
Example Output
(integer) 1

Incrementing the score of an Element

The ZINCRBY command can be used to increment the score of an element. Learn more

Time Complexity: O(log(N)) where N is the number of elements in the sorted set.

Example usage:

Text Only
ZINCRBY game.tetris.scoreboard 206 diane
Example Output
(integer) 223

Getting the Score of an Element

The ZSCORE command can be used to get the score of an element. Learn more

Time Complexity: O(1)

Example usage:

Text Only
ZSCORE game.tetris.scoreboard diane
Example Output
(integer) 223