---
title: "Redis Sorted Sets Made Easy: A Step-by-Step Management Guide"
description: "Need precise control over sorted data? Master Redis sorted sets and achieve effortless data organization with this comprehensive step-by-step guide."
canonical: "https://adamtheautomator.com/redis-sorted-set/"
---

# Redis Sorted Sets Made Easy: A Step-by-Step Management Guide

> Need precise control over sorted data? Master Redis sorted sets and achieve effortless data organization with this comprehensive step-by-step guide.

Source: https://adamtheautomator.com/redis-sorted-set/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![How To Manage Redis Sorted Set](https://adamtheautomator.com/wp-content/uploads/2022/04/How-To-Manage-Redis-Sorted-Set.jpg)

# How To Manage Redis Sorted Set

[![](https://secure.gravatar.com/avatar/2788bb1a3f735603f81eca51d68daec56a9d97e805a10268fb2c20afcc76b81b?s=192&d=mm&r=g)Nicholas Xuan Nguyen](https://adamtheautomator.com/author/nicholas-xuan-nguyen/)23 February 202410 min. read

Categories: [DevOps](/category/devops/)

Tags:[Redis](/tag/redis/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Configuring Redis](#configuring-redis)
*   [Creating a Redis Sorted Set](#creating-a-redis-sorted-set)
*   [Adding Multiple Members to a Sorted Set](#adding-multiple-members-to-a-sorted-set)
*   [Modifying ZADD Command’s Behavior with Options](#modifying-zadd-commands-behavior-with-options)
*   [Fetching Members by Range of Scores from a Sorted Set](#fetching-members-by-range-of-scores-from-a-sorted-set)
*   [Fetching Members and their Corresponding Scores](#fetching-members-and-their-corresponding-scores)
*   [Fetching Members with the Same Scores Alphabetically](#fetching-members-with-the-same-scores-alphabetically)
*   [Fetching Members Rank and Score](#fetching-members-rank-and-score)
*   [Fetching Information About a Sorted Set](#fetching-information-about-a-sorted-set)
*   [Removing Members from a Sorted Set](#removing-members-from-a-sorted-set)
*   [Conclusion](#conclusion)

Managing data can be a pain if they end up getting cluttered, leaving you confused, thinking which is which. The good news is that Redis takes care of sorting your data automatically, resulting in not requiring additional processes to sort data manually. This behavior makes a Redis sorted set an ideal choice for real-time applications that require sorted data.

In this tutorial, you’ll learn how to effectively manage Redis sorted sets via the command-line interface (CLI).

Read on to never again worry about manually sorting your data sets!

## Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following.

*   An Ubuntu server. This tutorial uses Ubuntu 20.04.

Related:[How to Install Ubuntu 20.04 \[Step-by-Step\]](https://adamtheautomator.com/install-ubuntu/)

*   [Redis installed](https://linuxize.com/post/how-to-install-and-configure-redis-on-ubuntu-20-04/) on your server.

Related:[How to Perform a Secure Redis Install on Linux](https://adamtheautomator.com/redis-install/)

*   A user account with [root/sudo privileges](https://www.wikihow.com/Become-Root-in-Ubuntu).

## **Configuring Redis**

A few configuration directives are important for your Redis server, `supervised`, and `dbfilename` directives. By default, Redis stores its configuration parameters in the _/etc/redis/redis.conf_ file.

The supervised directive tells Redis what kind of init system to use, and the available options are systemd, upstart, and none. But in this tutorial, you’ll use systemd to manage Redis.

1\. SSH into your server and open the _/etc/redis/redis.conf_ file with your favorite text editor.

```bash
sudo nano /etc/redis/redis.conf
```

Related: [How to Edit Files with a Real PowerShell Text Editor](https://adamtheautomator.com/powershell-text-editor/)

2\. Find the **supervised** directive and uncomment it by removing the leading pound sign (**#**), then set the value to **systemd**, as shown below. Once you’ve made the changes, save and exit the _redis.conf_ file.

By default, this directive is commented out and set to 0 (none), which indicates you can not use systemd to manage your Redis server.

![Setting the supervised Directive Value to systemd](https://adamtheautomator.com/wp-content/uploads/2022/04/image-54.png)

Setting the supervised Directive Value to systemd

3\. Open your terminal and run each of the following `systemctl` commands to restart the Redis server to apply the changes.

> _The first two commands don’t have an output, but you’ll see the Redis server’s status after running the last one._

```bash
# Restart Redis Server
sudo systemctl restart redis
# Start Redis Server
sudo systemctl start redis
# Check Redis Server Status
sudo systemctl status redis
```

If all goes well, you’ll see an output similar to the following, showing the Redis server is active (running).

![Checking the Status of the Redis Server](https://adamtheautomator.com/wp-content/uploads/2022/04/image-55.png)

Checking the Status of the Redis Server

Related:[Controlling Systemd services with Ubuntu systemctl](https://adamtheautomator.com/ubuntu-systemctl/)

4\. Finally, run the below commands to log in to your Redis server and ensure Redis is functioning correctly.

```bash
# Login to Redis Server
redis-cli
# Ping Redis Server to ensure Redis is working correctly.
ping
```

If you receive a PONG response, your Redis server is running, and you can continue to the next section.

![](https://adamtheautomator.com/wp-content/uploads/2022/04/image-56.png)

Pinging your Redis Server

## Creating a Redis Sorted Set

Now that your Redis server is running, you can create a sorted set to store your data. Suppose you have a leaderboard of the users with the most active sessions on your server. You can create a sorted set to store the leaderboard data with a score representing the number of active sessions.

In the syntax below, the `score` arguments are scores of the members in your sorted set, while the `member` arguments are the IDs of the members in your sorted set as strings (`""`).

```bash
ZADD key score1 "member1" score2 "member2" ... scoreN "memberN"
```

Now, run the `ZADD` command below to create a sorted set called `leaderboard` with one (`1`) score for the user `ata1` (member ID), indicating the user has one active session.

```bash
ZADD leaderboard 1 "ata1"
```

> _Since the member IDs are strings, Redis can adequately parse the arguments’ returned values and store them as a sorted set._

Like all Redis commands, the `ZADD` command returns an integer response indicating the number of members added to the sorted set. In this case, you added one member to the leaderboard sorted set, as shown below.

![Adding One Member on the leaderboard Sorted Set](https://adamtheautomator.com/wp-content/uploads/2022/04/image-57.png)

Adding One Member on the leaderboard Sorted Set

## Adding Multiple Members to a Sorted Set

You’ve just added one member, but can you add multiple members to the sorted set in one go? Yes! This behavior can be useful if you don’t want to issue the same command multiple times to add more members in a sorted set.

Run the below command to add members to the `leaderboard` sorted set with different scores and IDs.

Note that in the command below:

*   The scores are not required to be sequential or in order (`2 "ata2"` `3 "ata3"` `3 "ata4"` `6 "ata5"`).
*   You can have gaps between the scores (`3 "ata4"` `6 "ata5"`)
*   You can also have identical scores (`3 "ata3"` `3 "ata4"`).

This behavior makes sorted sets unique from other data structures in Redis. You can take advantage of this property to store data in a way that is convenient for you.

```bash
ZADD leaderboard 2 "ata2" 3 "ata3" 3 "ata4" 6 "ata5" 2 "ata6" 7 "ata7" 10 "ata8" 11 "ata9"
```

![Adding Multiple Members to a Sorted Set](https://adamtheautomator.com/wp-content/uploads/2022/04/image-58.png)

Adding Multiple Members to a Sorted Set

## Modifying `ZADD` Command’s Behavior with Options

The `ZADD` command supports the following options. Put these options after the key name and before the first score to modify the command’s behavior.

For example, you’ve found out that the ata1 user has increased activity and now has two active sessions. You can update ata1’s score by appending the `XX` options in the `ZADD` command. The `XX` option only updates the existing elements in the sorted set with the new scores.

1\. Run the following command to update `ata1`‘s score to `2` without changing any of the other members’ in the `leaderboard` sorted set.

```bash
ZADD leaderboard XX 2 "ata1"
```

The output below confirms Redis updated the ata1 member with a new score of 2. And the integer value is 0 since there are no new members added.

![Updating User’s (ata1) Score](https://adamtheautomator.com/wp-content/uploads/2022/04/image-59.png)

Updating User’s (ata1) Score

2\. Next, run the below command to add `ata10` to the `leaderboard` sorted set. With the `NX` option appended, the `ZADD` command adds `ata10` without affecting the scores of other members.

This command only adds ata10 if it does not exist in the leaderboard sorted set.

```bash
ZADD leaderboard NX 2 "ata1" 12 "ata10”
```

As you can see below, (integer) 1 indicates the ata10 user was added to the leaderboard sorted set with a score of 12.

![Adding a New Member (leaving other members’ scores unaffected)](https://adamtheautomator.com/wp-content/uploads/2022/04/image-60.png)

Adding a New Member (leaving other members’ scores unaffected)

> _You can’t use NX with the XX option. You must choose one or the other; otherwise, you’ll get the error below._

![Getting Error using XX and NX Options Together](https://adamtheautomator.com/wp-content/uploads/2022/04/image-61.png)

Getting Error using XX and NX Options Together

3\. Lastly, run the `ZADD` command below appending the `CH` option.

The CH option returns the number of members whose scores changed or the number of new members added to the sorted set. This option can be useful for debugging your code or monitoring your sorted set’s health.

```bash
ZADD leaderboard CH 2 "ata2" 3 "ata3" 3 "ata4" 6 "ata5" 2 "ata6" 7 "ata7" 10 "ata8" 11 "ata9”
```

You’ll see that the CH option returns (integer) 0 because no members were added or had their scores changed, as shown below.

![Verifying Recent Changes in the Sorted Set](https://adamtheautomator.com/wp-content/uploads/2022/04/image-62.png)

Verifying Recent Changes in the Sorted Set

## Fetching Members by Range of Scores from a Sorted Set

You’ve successfully created a sorted set with a few members, but is that all? Perhaps you have applications dependent on the members in your sorted set. If so, you’ll have to run a handful of commands to fetch members from a sorted set.

Run the [`zrange`](https://redis.io/commands/zrange) command below to fetch the first six members (`0` to `5`) from the `leaderboard` sorted set. Zero (`0`) is the first index, and five (`5`) is the last index to return.

```bash
zrange leaderboard 0 5
```

As shown below, the command returns all the members in the sorted set with scores in the range of 0-5. Those members have a low score, so they may be less likely to be active users.

> _If your members have the same score, the `zrange` command returns them alphabetically._

![Fetching a Range Members ](https://adamtheautomator.com/wp-content/uploads/2022/04/image-63.png)

Fetching a Range Members

Now, run the below `zrange` command to fetch the last four members (`-4 -1`) from the `leaderboard` sorted set.

The `zrange` command supports negative indexes to fetch members starting from the end of the sorted set. In the following command, `-1` is the last index in the sorted set, while `-4` is the fourth to the last index.

```bash
zrange leaderboard -4 -1
```

![fetching the last five members](https://adamtheautomator.com/wp-content/uploads/2022/04/image-64.png)

fetching the last five members

> _Negative indexes can be useful for pagination. For example, if you have a sorted set with 1,000 members and your application can only display the first 20 members at a time. In that case, negative indexes can fetch the last 20, 40, 60, and so on., members from the sorted set for pagination._

## Fetching Members and their Corresponding Scores

You’ve seen how to fetch a range of members from a sorted set. But the `zrange` command, without options, only returns the members ID. What about the scores? You’ll run the same `zrange` command but appended by the `WITHSCORES` option this time.

Run the below command to fetch the first six members (`0` `5`) from the `leaderboard` sorted set with their corresponding scores (`WITHSCORES`).

```bash
zrange leaderboard 0 5 WITHSCORES
```

![Fetching the First Six Members with their Corresponding Scores](https://adamtheautomator.com/wp-content/uploads/2022/04/image-65.png)

Fetching the First Six Members with their Corresponding Scores

By default, Redis returns the members in ascending order. But perhaps you prefer to fetch the members from a sorted set in reverse order. If so, replace `zrange` with the [`zrevrange`](https://redis.io/commands/zrevrange) command instead.

Run the below `zrevrange` command to fetch members with the highest scores on the top.

```bash
zrevrange leaderboard 0 11 WITHSCORES
```

![Fetching Members with the Highest Scores on the Top](https://adamtheautomator.com/wp-content/uploads/2022/04/image-66.png)

Fetching Members with the Highest Scores on the Top

## Fetching Members with the Same Scores Alphabetically

You’ll meet situations where you have to deal with many members (even thousands) with the same score. In these cases, the [`zrangebylex`](http://%3Chttps://redis.io/commands/zrangebylex) command will come in handy.

The `zrangebylex` command lets you force Redis to return the members in alphabetical order. Redis will use the alphabetical order of the string instead of the score to return the members.

The `zrangebylex` command has the following syntax.

```bash
zrangebylex key [start interval [stop interval.
```

Run the following commands to create a new sorted set (`zadd`) called `leaderboard2`, and fetch all the members (`zrangebylex`) from leaderboard2 in alphabetical order (`[a [z`).

```bash
# Creates leaderboard2 sorted set with multiple members
zadd leaderboard2 0 ata 0 bta 0 cta 0 dta 0 eta
# Fetches all the members in the leaderboard2 sorted set in alphabetical order (a-z).
zrangebylex leaderboard2 [a [z
```

You can see below that the members are listed in alphabetical order (a-z).

![Fetching all the Members in the leaderboard2 Sorted Set in Alphabetical Order](https://adamtheautomator.com/wp-content/uploads/2022/04/image-67.png)

Fetching all the Members in the leaderboard2 Sorted Set in Alphabetical Order

> _Note that the `zrangebylex` command is case-sensitive. So, if you have members with names such as Mary, mary, and MARY, they are all considered different members._

Now, run the commands below to add new members (`zadd`) to the `leaderboard2` sorted set and fetch the members (`zrangebylex`) that start with capital letters alphabetically (`[A [Z`).

```bash
# Adds new members with capital letters
zadd leaderboard2 0 Ata 0 Bta 0 Cta 0 Dta 0 Eta
# Fetches all the members with IDs starting with capital letters in alphabetical order 
zrangebylex leaderboard2 [A [Z
```

Below, all members start with a capital letter and are listed in alphabetical order.

![Fetching all Members in Capital Alphabetical Order](https://adamtheautomator.com/wp-content/uploads/2022/04/image-68.png)

Fetching all Members in Capital Alphabetical Order

## Fetching Members Rank and Score

Apart from fetching members alphabetically, you can also fetch members’ rank and score by running the [`zrevrank`](https://redis.io/commands/zrevrank) command.

The member’s rank is just an integer number but can be useful for determining the importance of a member in a set. For example, if you aim to know which member has the most section points, the members’ rank can help.

Run the following commands to fetch the rank of members `ata1` and `ata9` in the `leaderboard` sorted set.

```bash
zrevrank leaderboard ata1
zrevrank leaderboard ata9
```

As shown below, the **ata1** member has a score of **2** and is ranked **9** (almost at the bottom). In contrast, the **ata9** member has a score of 11 and is ranked **1** (at the top).

![Fetching Members Ranks](https://adamtheautomator.com/wp-content/uploads/2022/04/image-69.png)

Fetching Members Ranks

## Fetching Information About a Sorted Set

You already know how to add and fetch members from a sorted set. But your app might need to fetch further information, like the following:

*   The total number of members in a sorted set. If a sorted set contains no members, your app might choose to add some.
*   Members that fall within a specific range of scores.
*   If a member exists in a sorted set, your app might choose to update its score. But if not, your app might choose to add it.

Redis offers some commands you can use to get more information about a sorted set. One of those commands is the [`zcard`](https://redis.io/commands/zcard/) command. The `zcard` command lets you get the total number of members ([cardinality](https://en.wikipedia.org/wiki/Cardinality)) in a sorted set.

1\. Run the below `zcard` command to fetch the total number of members in the `leaderboard` sorted set.

```bash
zcard leaderboard
```

Below, the zcard command returns ten members in the leaderboard sorted set below.

![Fetching the Total Number of Members in a Sorted Set](https://adamtheautomator.com/wp-content/uploads/2022/04/image-70.png)

Fetching the Total Number of Members in a Sorted Set

2\. Next, run the following command to fetch the number of members in the `leaderboard` sorted set with scores between `8` and `10`. For example, these scores may indicate who is highly engaged in your website.

```bash
zcount leaderboard 8 10
```

![](https://adamtheautomator.com/wp-content/uploads/2022/04/image-71.png)

Fetching Top Ten Members By Score

3\. Lastly, run the `zrank` command below to find the rank of the member `ata20` in the `leaderboard` sorted set. This command lets you find out if a member exists in a sorted set and, if it does, fetch what its rank is.

```bash
zrank leaderboard ata20
```

When a member does not exist in a sorted set, the zrank command returns nil, as shown below.

![Finding the Rank of a Specific Member](https://adamtheautomator.com/wp-content/uploads/2022/04/image-72.png)

Finding the Rank of a Specific Member

## Removing Members from a Sorted Set

A sorted set is a great way to store data, but your data can only be as good as when it’s up-to-date. Perhaps you have one too many members in your sorted set. If so, how do you remove some of them?

Suppose you have a sorted set called “players” that contains the players currently playing in your game. And as players leave the game, you need to remove them from the “players” sorted set.

Redis offers a few different commands for removing members from a sorted set, and one of them is the [`zrem`](https://redis.io/commands/ZREM) command. The `zrem` command removes one or more members from a sorted set, following the syntax below.

```bash
zrem key member1 member2 ... memberN
```

To remove members from your sorted set:

1\. Run the below `zrem` command to remove the member `ata1` from the `leaderboard` sorted set.

```bash
zrem leaderboard ata1
```

![Removing a Member from a Sorted Set](https://adamtheautomator.com/wp-content/uploads/2022/04/image-73.png)

Removing a Member from a Sorted Set

2\. Next, run the below command to remove all members containing A and Z in their name from the `leaderboard2` sorted set. The command removes all members with the same score in alphabetical order (`[A [Z`).

```bash
zremrangebylex leaderboard2 [A [Z
```

![](https://adamtheautomator.com/wp-content/uploads/2022/04/image-74-1024x85.png)

Removing All Members That Have AZ in Their Name

3\. Run the below [`zremrangebyrank`](https://redis.io/commands/zremrangebyrank) command to remove members in the **1** – **4** score range from the `leaderboard` sorted set. The `zremrangebyrank` command lets you remove members based on their rank.

```bash
zremrangebyrank leaderboard 1 4
```

![Removing Members in the 1-4 Score Range](https://adamtheautomator.com/wp-content/uploads/2022/04/image-75.png)

Removing Members in the 1-4 Score Range

4\. Finally, run the `zrange` command below to verify that you’ve successfully removed the specified members (steps one to three) from the `leaderboard` sorted set.

```bash
zrange leaderboard 0 10 WITHSCORES
zrange leaderboard2 0 10 WITHSCORES
```

![Verifying Removed Members from the leaderboard Sorted Set](https://adamtheautomator.com/wp-content/uploads/2022/04/image-76.png)

Verifying Removed Members from the leaderboard Sorted Set

![Verifying Removed Members from the leaderboard2 Sorted Set](https://adamtheautomator.com/wp-content/uploads/2022/04/image-77.png)

Verifying Removed Members from the leaderboard2 Sorted Set

## Conclusion

Throughout this tutorial, you’ve learned about managing sorted sets in Redis. From creating sorted sets to adding and removing members and fetching data from sorted sets.

Redis sorted sets are a great way to store sorted data. By using the various Redis commands, you can keep your data up-to-date.

At this point, you should know the basics of sorted sets. So why not start [using sorted sets in your own applications](https://daily.dev/blog/creating-a-capped-leaderboard-with-redis-sorted-set-secondary-index-and-lua).

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fredis-sorted-set%2F&text=How%20To%20Manage%20Redis%20Sorted%20Set)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fredis-sorted-set%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fredis-sorted-set%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2026/08/featured_image-6.webp)

### [Automate Terraform with Azure DevOps](/automate-terraform-azure-devops/)

Automate Terraform with Azure DevOps Pipelines: structure a multi-environment repo, store remote state in Azure Storage with locking, and deploy through

![](https://adamtheautomator.com/wp-content/uploads/2026/08/featured_image-5.webp)

### [Azure DevOps Boards: Trace Every Commit to Deployment](/azure-devops-boards-traceability/)

Configure Azure DevOps Boards process templates, backlogs, and Kanban WIP limits, then trace every work item from commit to deployment.

![](https://adamtheautomator.com/wp-content/uploads/2026/07/featured_image-3.png)

### [Build Your First Internal Developer Platform](/build-first-internal-developer-platform/)

Build your first Internal Developer Platform with Backstage, a software catalog, software templates, CI/CD handoffs, and Kubernetes deployment manifests.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
