LTRIM(3valkey)

πŸ“¦
version 9.0.6 Β· 2 versions
, in fedora 44

✨ LTRIM (3valkey) β€” the valkey command manual, but make it cute ✨

okay bestie, pull up a chair, we're learning LTRIM πŸ’… it lives in the valkey command manual and it is genuinely one of the most useful lil guys in the whole list family.


🌸 NAME 🌸

ltrim β€” Removes elements from both ends a list. Deletes the list if all elements were trimmed.

yes, BOTH ends. it's giving scissors. it's giving "we're cutting the crusts off this sandwich" βœ‚οΈπŸ“

πŸŽ€ SYNOPSIS πŸŽ€

LTRIM key start stop

πŸ’– DESCRIPTION πŸ’–

So the vibe is: you have an existing list, and you wanna trim it down so it only contains the specified range of elements. Both start and stop are zero-based indexes β€” meaning 0 is the first element of the list (the head, the main character πŸ‘‘), 1 is the next element, and so on down the line.

For example: LTRIM foobar 0 2 will modify the list stored at foobar so that only the first three elements of the list will remain.

start and end can also be negative numbers, which means they're counting offsets from the end of the list instead πŸ¦‹ β€” where -1 is the last element of the list, -2 is the penultimate element, and so on.

Now here's the part where nobody yells at you for going out of range, because out of range indexes will not produce an error 😌:

  • if start is larger than the end of the list, or start > end, the result will be an empty list β€” which causes key to be removed πŸ’€
  • if end is larger than the end of the list, Valkey will treat it like the last element of the list

A common use of LTRIM is together with valkey-lpush(7) LPUSH / valkey-rpush(7) RPUSH. For example:

LPUSH mylist someelement
LTRIM mylist 0 99

This pair of commands will push a new element on the list, while making sure that the list will not grow larger than 100 elements πŸ”₯ This is very useful when using Valkey to store logs for example. It is important to note that when used in this way LTRIM is an O(1) operation because in the average case just one element is removed from the tail of the list.

ngl this is the log-keeping hack and it absolutely ate 🫢

🌈 REPLY 🌈

valkey-protocol(7) Simple string reply: OK.


⭐ COMPLEXITY ⭐

O(N) where N is the number of elements to be removed by the operation.


πŸ‘‘ ACL CATEGORIES πŸ‘‘

@list @slow @write


πŸ¦‹ HISTORY πŸ¦‹

  • Available since: 1.0.0

like... an icon from the very beginning, periodt πŸ’œ


✨ EXAMPLES ✨

127.0.0.1:6379> RPUSH mylist "one"
(integer) 1
127.0.0.1:6379> RPUSH mylist "two"
(integer) 2
127.0.0.1:6379> RPUSH mylist "three"
(integer) 3
127.0.0.1:6379> LTRIM mylist 1 -1
OK
127.0.0.1:6379> LRANGE mylist 0 -1
1) "two"
2) "three"

see how "one" just... left the chat 😭 iconic behavior fr fr


πŸŽ€ SEE ALSO πŸŽ€


and that's the whole page, bestie πŸ’– this was version 9.0.0, dated 2025-10-21, and honestly? she slayed. mwah 🫢✨

πŸ“¦ where this page comes from