Redis SINTERCARD Command Explained

In Redis, the SINTERCARD command returns the cardinality of the set which would result from the intersection of all the given sets. It’s similar to SINTER, but instead of returning the result set, it returns just the cardinality of the result.

The SINTERCARD command was introduced in Redis 7.0.0.

Syntax

The syntax goes like this:

SINTERCARD numkeys key [key ...] [LIMIT limit]

Example

Suppose we create the following sets:

SADD set1 0 1 2 3 4 5 6
SADD set2 3 4 5 6 7 8

We can use the SINTERCARD command to return the cardinality of the set which would result from the intersection of both sets:

SINTERCARD 2 set1 set2

Result:

(integer) 4

We can use the SINTER command to see the actual members:

SINTER set1 set2

Result:

1) "3"
2) "4"
3) "5"
4) "6"

We get 3, 4, 5 and 6, because those two members are in both sets.

Now let’s create another set:

SADD set3 1 4 5

Now let’s include that as a set when calling the SINTERCARD command:

SINTERCARD 3 set1 set2 set3

Result:

(integer) 2

This time only 2 is returned, because only two members are common to all sets.

About the First Argument

The first argument specifies the number of keys to compare. It can’t be greater than the actual number of keys.

Here’s what happens if the first argument is greater than the number of specified keys:

SINTERCARD 4 set1 set2 set3

Result:

(error) ERR Number of keys can't be greater than number of args

And here’s what happens when the first argument is less than the number of specified keys:

SINTERCARD 2 set1 set2 set3

Result:

(error) ERR syntax error

Limiting the Results

We can provide another argument that limits the intersection cardinality. Basically, if the intersection cardinality reaches the LIMIT value partway through the computation, the algorithm will exit and yield limit as the cardinality.

Here’s an example:

SINTERCARD 2 set1 set2 LIMIT 3

Result:

(integer) 3

This allows for a performance increase for queries where the limit is lower than the actual intersection cardinality. The default value is 0, which means that there’s no limit.

Non-Existent Keys

Keys that don’t exist are treated as empty sets. If we pass an empty set to the SINTERCARD command, the result will be zero. That is because any intersection with an empty set will always result in an empty set.

Example:

SINTERCARD 2 set1 nonexistentkey

Result:

(integer) 0

If we use the SINTER command against the same sets, we’d get an empty array.