## Redis ZRANGEBYLEX – How to get elements of sorted set by asc value range

###### 1 week ago Lalit Bhagtani 0

In this tutorial, we will learn about how to get all the elements of the sorted set value having values between a specific range and in ascending lexicographical order. For this, we will use Redis ZRANGEBYLEX command.

## ZRANGEBYLEX Command

This command returns all the elements of the sorted set value stored at a specified key, with values (string representation of element) between min and max arguments. Here all the elements in a sorted set value are inserted with the same score, in order to force lexicographical ordering. Returned elements are in ascending lexicographical order.

The min and max arguments must start with ( or [, where [ specifies closed interval (inclusive) and ( specifies open interval (exclusive). For example :-

ZRANGEBYLEX set [a [f

Will return all elements with a <= element <= f while:

ZRANGEBYLEX set [a (f

Will return all the elements with a <= element < f

The min and max arguments can have special values of + or , where + specifies positive infinite strings and specifies negative infinite strings, so for example the command ZRANGEBYLEX set – + will return all the elements of the sorted set value.

The LIMIT ( optional ) argument can be passed in the command, to get the count matching elements starting from the offset. If count value is negative then all elements are returned from the offset. For example:-

ZRANGEBYLEX set [a [f LIMIT 1 3
Where set = [a, b, c, d, e, f, g, h]

Will return three matching elements, starting from second matching element. i.e [b, c, d]

An empty set is returned, if a key does not exist and an error is returned, if a key exists but value stored at the key is not of sorted set datatype. The syntax of Redis ZRANGEBYLEX command is as follows:-

## Syntax :-

redis host:post> ZRANGEBYLEX <keyname> <min> <max> [LIMIT offset count]

## Output :-

- (array) reply, representing elements of the sorted set in the specified range.
- Empty Set, if key does not exists.
- Error, if key exist and value stored at the key is not a sorted set.

## References :-

That’s all for how to get all the elements of the sorted set value having values between specific range and in ascending lexicographical order. If you liked it, please share your thoughts in comments section and share it with others too.