Redis Commands Cheat Sheet Part 3 - Sets and Sorted Sets
Tags: redis, cheatsheet, rediscommand, database
Published: 2023-01-28 21:20:39

![Redis Icon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ch1nj3g33iea3w75ol8.png)

---
Following are some of the commonly used Redis commands and data structures, use this list as a quick cheat sheet or a ready reference for your day-to-day Redis usage as needed 😄

This is Part 3 of this series, containing commands pertaining to **Sets** and **Sorted Sets** in Redis.

---
### Sets

```bash
# add one/more elements (members) to a set
# ignores duplicates - returns 0 for duplicates since they will not be added
> SADD key member [member ...]

# get number of members, or cardinality, in a set
> SCARD key

# get all members of a set
# inefficient
> SMEMBERS key

# iterate over members of a set
# more efficient than SMEMBERS
> SSCAN key cursor [MATCH pattern] [COUNT count]

# determine if a given value is a member of a set
# returns:
#   - 1 if the element is a member of the set.
#   - 0 if the element is not a member of the set, or if key does not exist
> SISMEMBER key member

# remove one/more members by value
# specified members that are not a member of this set are ignored
# if 'key' does not exist, it is treated as an empty set and this command returns 0
# error is returned when the value stored at 'key' is not a set
# the return value indicates how many elements were removed
> SREM key member [member ...]

# remove and return one/multiple random member from the set
# default value of 'count' is 1
> SPOP key [count]

# union, intersection, difference of multiple sets stored at a specific key
> SUNION key [key ...]
> SINTER key [key ...]
> SDIFF key [key ...]

# union, intersection, difference of multiple sets stored at a specific key - and store the resulting set in a new set at a 'destination' key
> SUNIONSTORE destination key [key ...]
> SINTERSTORE destination key [key ...]
> SDIFFSTORE destination key [key ...]
``` 

---
### Sorted Sets

```bash
# add one/more members to sorted set, or update its score if member already exists
# for oprions, see: https://redis.io/commands/zadd/
> ZADD key score member [score member ...] [NX | XX] [GT | LT] [CH] [INCR]

# increment score of a member
# decremebt score by using negative value for 'ncrement'
> ZINCRBY key increment member

# iterate over sorted set, from lowest score to highest score
> ZRANGE key start-index stop-index [WITHSCORES]
> ZRANGE "subway:red-line" 0 -1 WITHSCORES

# iterate over sorted set, from highest score to lowest score
> ZREVRANGE key start-index stop-index [WITHSCORES]

# WITHSCORES includes the score of the members in the output

# return all the elements in the sorted set at key with a score between min and max, from lowest score to highest score
> ZRANGEBYSCORE key min max [WITHSCORES]

# return all the elements in the sorted set at key with a score between min and max, from highest score to lowest score
> ZREVRANGEBYSCORE key min max [WITHSCORES]

# 'min' and 'max' can be -inf and +inf
# by default, the interval specified by 'min' and 'max' is inclusive
# it is possible to specify an exclusive interval by prefixing the score with the character '('
# example:
> ZRANGEBYSCORE zset (1 5 # return all elements with 1 < score <= 5
> ZRANGEBYSCORE zset (5 (10 # return all the elements with 5 < score < 10 (5 and 10 excluded)

# when all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering
> ZRANGEBYLEX key min max

# 'min' and 'max' can be - and +
# '(' is exclusive
# '[' is inclusive
# example:
> ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g
> ZRANGEBYLEX myzset - [c # returns a, b and c
> ZRANGEBYLEX myzset - (c # returns a and b

# find index (rank) of a member in a sorted set, from lowest score to highest score
# scores ordered from low to high, i.e. member with the lowest score has rank 0
> ZRANK key member

# find index (rank) of a member in a sorted set, from highest score to lowest score
# scores ordered from high to low, i.e. member with the highest score has rank 0
> ZREVRANK key member

# get score of a given member
> ZSCORE key member

# count the members with scores within the given values
# includes members with scores equl to 'min' and 'max'
> ZCOUNT key min max 

# remove one/more members from a sorted set
> ZREM key member [member ...]

# get number of elements (cardinality) in a sorted set
> ZCARD key

# set operations - union, intersection, difference on sorted sets
> ZUNION numkeys key [key ...]
> ZINTER numkeys key [key ...]
> ZDIFF numkeys key [key ...]

> ZUNIONSTORE destination numkeys key [key ...] [AGGREGATE <SUM | MIN | MAX>]
> ZINTERSTORE destination numkeys key [key ...] [AGGREGATE <SUM | MIN | MAX>]
> ZDIFFSTORE destination numkeys key [key ...]

# for the above commands, it is mandatory to provide the number of input keys (numkeys) before passing the input keys and the other (optional) arguments
# when AGGREGATE is SUM: the resulting set will contain the sum of the score of an element across the inputs where it exists (default)
# when AGGREGATE is MIN or MAX: the resulting set will contain the minimum or maximum score of an element across the inputs where it exists

# commands for set operations on sorted sets, can work between sets as well as sorted sets

# remove all members in a sorted set within the given scores
# min and max are inclusive by default, exclusive if appended with a '('
# min and max can be -inf and +inf
> ZREMRANGEBYSCORE key min max 

# remove all members in a sorted set within the given indexes
# start and stop are inclusive
> ZREMRANGEBYRANK key start stop

# remove all members in a sorted set within the given lexicographical range
# min and max are inclusive if appended with a '[', exclusive if appended with a '('
# min and max can be - and +
> ZREMRANGEBYLEX key min max
```

---
Hope you found this useful! Save the post for reference, here's [Part 1](https://dev.to/espelar-dev/redis-commands-cheat-sheet-part-1-keys-strings-278j) and [Part 2](...) of the series.

Do follow [espelar.dev](https://dev.to/espelar-dev) we're working on some pretty cool stuff and have exciting content for you in the works.😊
Cheers!