Redis SCARD Command Explained

In Redis, the SCARD command returns the number of members in the specified set. This is referred to as the cardinality of the set.

Syntax

The syntax goes like this:

SCARD key

Where key is the key in question.

Example

Here’s an example of using SCARD against a set called animals:

SCARD animals

Result:

(integer) 4

The result is an integer reply of 4, which means the set contains four members.

We can verify this by looking at all the members in the set:

SMEMBERS animals

Result:

1) "Horse"
2) "Ant"
3) "Dog"
4) "Cat"

If we add more members to the set, SCARD returns a different number:

SADD animals "Cow" "Mouse" "Chicken"

Result:

(integer) 3

Now let’s run SCARD again to check the set’s cardinality:

SCARD animals

Result:

(integer) 7

When the Key Doesn’t Exist

If the key doesn’t exist, SCARD returns 0:

SCARD oops

Result:

(integer) 0

In this case, the key oops doesn’t exist, and we get an integer reply of zero.