Efficient Way to save Multi-Select value in database

Freddy Flint
1 min readApr 20, 2021

Have you ever struggled to save a multi-select field in a database? One of your obvious solutions would be using an array of values or multiple columns. But there is an easier way to do the same.
Let just say, you need to save the day field in the database. The options would be MON, TUE … SUN.
Assign each option increment power of 2
So MON-1 TUE-2 WED-4 and so on
When you are saving the value using bitwise or operator ( |). So when MON and WED are selected 1 | 4= 5, store the result in the database. When reading the value from the database you can use bitwise and operator (&) to check whether the option is selected.
For result 5, you can check MON by 1 & 5 != 0 , it would return true. It would return false for option TUE, it would return false.

--

--