How to Use LRANGE Command in Redis: Syntax and Examples
Use the
LRANGE command in Redis to get a range of elements from a list by specifying the start and stop indexes. The command returns the list elements between these indexes, including both ends, with 0 as the first element index.Syntax
The LRANGE command syntax is:
LRANGE key start stop
Where:
- key: the name of the list.
- start: the starting index (0-based).
- stop: the ending index (inclusive).
Indexes can be negative to count from the end (-1 is the last element).
redis
LRANGE mylist 0 2
Example
This example shows how to add elements to a list and then retrieve a range of elements using LRANGE.
redis
127.0.0.1:6379> RPUSH mylist "apple" "banana" "cherry" "date" "fig" (integer) 5 127.0.0.1:6379> LRANGE mylist 1 3 1) "banana" 2) "cherry" 3) "date"
Output
1) "banana"
2) "cherry"
3) "date"
Common Pitfalls
Common mistakes when using LRANGE include:
- Using indexes that are out of range returns fewer elements without error (not an empty list unless start is beyond the end).
- Confusing inclusive
stopindex with exclusive (it includes the stop element). - Negative indexes count from the end, which can be confusing if not expected.
Example of a wrong and right usage:
redis
127.0.0.1:6379> LRANGE mylist 0 10 1) "apple" 2) "banana" 3) "cherry" 4) "date" 5) "fig" 127.0.0.1:6379> LRANGE mylist 0 -1 1) "apple" 2) "banana" 3) "cherry" 4) "date" 5) "fig"
Output
1) "apple"
2) "banana"
3) "cherry"
4) "date"
5) "fig"
1) "apple"
2) "banana"
3) "cherry"
4) "date"
5) "fig"
Quick Reference
| Parameter | Description |
|---|---|
| key | Name of the list to query |
| start | Start index (0-based, can be negative) |
| stop | Stop index (inclusive, can be negative) |
| Return | List of elements in the specified range |
Key Takeaways
LRANGE returns elements from a Redis list between start and stop indexes inclusive.
Indexes start at 0 and can be negative to count from the end of the list.
If indexes are out of range, LRANGE returns available elements without error.
Use LRANGE with RPUSH or LPUSH to manage and retrieve list data efficiently.