# LINSERT

> Insert an element before or after another element in a list.

URL: https://docs.hotkv.com/commands/linsert/

```
LINSERT key BEFORE | AFTER pivot element
```

- Group: List
- Complexity: O(N) where N is the number of elements before the pivot
- HotKV Cloud: all plans
- On-Premise: no license needed

`LINSERT` finds the first occurrence of `pivot` in the list stored at `key`,
scanning from the head, and inserts `element` just before or just after it.
If `pivot` is not in the list, nothing changes. A missing key is treated as an
empty list and is not created.

## Options

| Option | Effect |
| --- | --- |
| `BEFORE` | Insert `element` immediately before `pivot`. |
| `AFTER` | Insert `element` immediately after `pivot`. |

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| Inserted | Integer: the length of the list after the insert | Same |
| `pivot` not found | Integer `-1` | Same |
| Key does not exist | Integer `0` | Same |

Errors:

- `ERR syntax error` if the second argument is not `BEFORE` or `AFTER`.
- `WRONGTYPE` if `key` holds a value that is not a list.

## Examples

```
127.0.0.1:6379> RPUSH steps "one" "three"
(integer) 2
127.0.0.1:6379> LINSERT steps BEFORE "three" "two"
(integer) 3
127.0.0.1:6379> LINSERT steps AFTER "nine" "ten"
(integer) -1
127.0.0.1:6379> LRANGE steps 0 -1
1) "one"
2) "two"
3) "three"
```

## Compatibility

Same as Redis 7.4 and Valkey 8.

## See also

[LSET](https://docs.hotkv.com/commands/lset/index.md), [LPOS](https://docs.hotkv.com/commands/lpos/index.md), [LREM](https://docs.hotkv.com/commands/lrem/index.md),
[LPUSH](https://docs.hotkv.com/commands/lpush/index.md)