# ZUNION

> Return the union of sorted sets, combining the scores of shared members.

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

```
ZUNION numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM | MIN | MAX] [WITHSCORES]
```

- Group: Sorted set
- Complexity: O(N)+O(M*log(M)) where N is the total size of the input sets and M is the size of the result
- HotKV Cloud: all plans
- On-Premise: no license needed

`ZUNION` returns every member that appears in at least one of the given sorted
sets, ordered by its combined score. A member's combined score is built from
its score in each input that contains it, by default by adding them up.

Inputs can also be plain sets; their members count as having score `1`.
Missing keys count as empty. To store the result instead, use
[ZUNIONSTORE](https://docs.hotkv.com/commands/zunionstore/index.md).

## Options

| Option | Effect |
| --- | --- |
| `numkeys` | How many keys follow. Must be at least 1. |
| `WEIGHTS weight ...` | One multiplier per input key, applied to that input's scores before they are combined. Default `1` each. |
| `AGGREGATE SUM` | Add up the (weighted) scores. The default. |
| `AGGREGATE MIN` | Keep the lowest (weighted) score. |
| `AGGREGATE MAX` | Keep the highest (weighted) score. |
| `WITHSCORES` | Return each member with its combined score. Must be the last argument. |

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| Success | Array of members | Same |
| With `WITHSCORES` | Flat array: member, score, ... (scores as bulk strings) | Array of `[member, score]` pairs, the score a double |

Errors:

- `ERR value is not an integer or out of range` if `numkeys` is not an
  integer, and ``ERR at least 1 input key is needed for 'zunion' command`` if
  it is below 1.
- `ERR syntax error` if fewer keys follow than `numkeys` says, `WEIGHTS` has
  too few values, the `AGGREGATE` value is unknown, or anything else follows.
- `ERR weight value is not a float` for a weight that is not a number.
- `WRONGTYPE` if a key holds something other than a sorted set or a set. Key
  types are checked before the options.

## Examples

```
127.0.0.1:6379> ZADD q1 10 "alice" 5 "bob"
(integer) 2
127.0.0.1:6379> ZADD q2 3 "bob" 7 "carol"
(integer) 2
127.0.0.1:6379> ZUNION 2 q1 q2 WITHSCORES
1) "carol"
2) "7"
3) "bob"
4) "8"
5) "alice"
6) "10"
127.0.0.1:6379> ZUNION 2 q1 q2 WEIGHTS 1 2 AGGREGATE MAX
1) "bob"
2) "alice"
3) "carol"
```

## Compatibility

Same replies as Redis 7.4 and Valkey 8. HotKV requires `WITHSCORES` to be the
last argument; Redis and Valkey also accept it before `WEIGHTS` or
`AGGREGATE`.

## See also

[ZUNIONSTORE](https://docs.hotkv.com/commands/zunionstore/index.md), [ZINTER](https://docs.hotkv.com/commands/zinter/index.md), [ZDIFF](https://docs.hotkv.com/commands/zdiff/index.md),
[SUNION](https://docs.hotkv.com/commands/sunion/index.md)