0
0
Redisquery~5 mins

SCARD for set size in Redis

Choose your learning style9 modes available
Introduction

SCARD helps you find out how many unique items are in a set. It tells you the size of the set quickly.

You want to count how many friends are in your friend list stored as a set.
You need to know how many unique visitors came to your website today.
You want to check how many different tags are assigned to a blog post.
You want to find out how many unique products a customer has bought.
Syntax
Redis
SCARD key

key is the name of the set you want to check.

The command returns the number of elements in the set.

Examples
Returns the number of elements in the set named 'myset'.
Redis
SCARD myset
Returns how many users are currently online if stored in the 'users_online' set.
Redis
SCARD users_online
Sample Program

First, we add some fruits to the set named 'fruits'. Notice 'banana' is added twice but counted once because sets store unique items. Then we use SCARD to get the total number of unique fruits.

Redis
SADD fruits apple banana orange
SADD fruits banana grape
SCARD fruits
OutputSuccess
Important Notes

If the set does not exist, SCARD returns 0.

Sets only store unique values, so duplicates do not increase the count.

Summary

SCARD returns the number of unique elements in a set.

It is useful to quickly check the size of a set without retrieving all elements.