LTRIM
LTRIM key start stop
- Group
- List
- Complexity
- O(N) where N is the number of elements removed
- Arity
- 4 (exactly, counting the command name)
- Flags
- write
- Keys
- first 1, last 1, step 1
- HotKV Cloud
- All plans
- On-Premise
- no license needed
LTRIM keeps only the elements of the list at key from index start to
index stop, both included, and removes the rest. Indexes follow the same
rules as LRANGE: they start at 0, negative values count
from the end, and out-of-range values are clamped. If the range is empty, the
whole list is removed and the key is deleted.
A common pattern is to push and then trim, to keep a capped list of the most recent items:
LPUSH recent:events <event>LTRIM recent:events 0 99Return value
Section titled “Return value”| Case | RESP2 | RESP3 |
|---|---|---|
| Success (including a missing key) | Simple string OK |
Same |
Errors:
ERR value is not an integer or out of rangeifstartorstopis not an integer. This is checked before the key is looked up.WRONGTYPEifkeyholds a value that is not a list.
Examples
Section titled “Examples”127.0.0.1:6379> RPUSH letters a b c d e(integer) 5127.0.0.1:6379> LTRIM letters 1 -2OK127.0.0.1:6379> LRANGE letters 0 -11) "b"2) "c"3) "d"127.0.0.1:6379> LTRIM letters 5 10OK127.0.0.1:6379> EXISTS letters(integer) 0Compatibility
Section titled “Compatibility”Same as Redis 7.4 and Valkey 8.
See also
Section titled “See also”Was this page helpful?
Thanks for the feedback.