# How to use Redis Sorted Lists

> Learn how to use Redis sorted sets, which attach a score to each item, with ZADD, ZRANK, ZRANGE and ZINCRBY, perfect for building a leaderboard.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-07-29 | Topics: [Redis](https://flaviocopes.com/tags/redis/) | Canonical: https://flaviocopes.com/redis-sorted-lists/

A sorted set associates a rank to each item in a set.

Sorted sets work in a similar way to sets, and they use similar commands, except `S` is now `Z`, for example:

- `SADD` -> `ZADD`
- `SPOP` -> `ZPOP`

But they are slightly different.

`ZADD` accepts a **score**:

```
ZADD names 1 "Flavio"
ZADD names 2 "Syd"
ZADD names 2 "Roger"
```

As you can see, values must still be unique, but now they are associated to a score. 

The score does not have to be unique.

Items in a set are always sorted by the score.

This is very useful to implement some kind of data storage tool like (usual example) a leaderboard. Or to indicate the time some item was added, with a timestamp.

You can get the score of an item using `ZRANK`:

```
ZRANK names "Flavio"
```

List all items in a sorted set using `ZRANGE`, which works similarly to `LRANGE` in lists:

```
ZRANGE names 0 -1
```

![Redis CLI showing ZRANGE names 0 -1 command output with three names: Flavio, Roger, and Syd](https://flaviocopes.com/images/redis-sorted-lists/Screenshot_2020-03-30_at_17.17.43.png)

Add `WITHSCORES` to also return the scores information:

![Redis CLI showing ZRANGE names 0 -1 WITHSCORES command output displaying names with their associated scores](https://flaviocopes.com/images/redis-sorted-lists/Screenshot_2020-03-30_at_17.22.32.png)

You can increment the score of an item in the set using `ZINCRBY`.

See all the sorted sets commands [here](https://redis.io/commands#sorted_set).
