Set data type
The Set data type is a collection of unordered, unique members. A Set is similar to a mathematical set, which means that it supports common set operations such as the union, intersection and difference of two or more sets.
The SADD
command allows you to add members to a set, while SREM
removes a member and SPOP
gets and removes a member.
SISMEMBER
is useful for checking whether or not a set contains a specific member. The ability to test for membership can be used to ensure that an onboarding flow is only shown to first time users of your application. Membership can also be used to check if a contact is a customer in a CRM application.
You can count the number of members in a set with SCARD
, which stands for set cardinality. In an accounting application, you could use SCARD
to count how many invoices are unpaid after 30 days.
Sets also support set operations, such as union, intersection and difference which can be used to express relationships. For example, if you’re building an HR application you can use SINTER
to show a project manager all employees who know both Java and HTML. But what if there are not enough employees who have both skills? You could then use SDIFF
to display a list of employees who know Java or HTML, but not both.
Taking this example a step further, you could use SUNION
to show all employees who know Java and/or HTML, and then use a second query for SINTER
to display a special icon next to employees who have both skills.