Delete all entries in a Redis list

Paul A Jungwirth picture Paul A Jungwirth · Mar 22, 2012 · Viewed 60.4k times · Source

Suppose you have a LIST datatype in Redis. How do you delete all its entries? I've tried this already:

LTRIM key 0 0
LTRIM key -1 0

Both of those leave the first element. This will leave all the elements:

LTRIM key 0 -1

I don't see a separate command to completely empty a list.

Answer

Anurag picture Anurag · Mar 22, 2012

Delete the key, and that will clear all items. Not having the list at all is similar to not having any items in it. Redis will not throw any exceptions when you try to access a non-existent key.

DEL key

Here's some console logs.

redis> KEYS *
(empty list or set)
redis> LPUSH names John
(integer) 1
redis> LPUSH names Mary
(integer) 2
redis> LPUSH names Alice
(integer) 3
redis> LLEN names
(integer) 3
redis> LRANGE names 0 2
1) "Alice"
2) "Mary"
3) "John"
redis> DEL names
(integer) 1
redis> LLEN names
(integer) 0
redis> LRANGE names 0 2
(empty list or set)