Question

In my application, I'd like the user to select his working days. then store them in the database. Of course my application will process the users' data like: Is today a working day for a specific user, who are the users that should work today , ... etc.

My question is, what is the best practice for doing this? should I use:

  1. Bitmasking field in the users table
  2. Many to many relationships tables by creating table for days, users and days_users. Thank you in advance.
Was it helpful?

Solution

I would say that bit mask fields are a relational anti-pattern.

A field should have a single meaningful value, otherwise you end up with querying issues - parsing the field every time you need to query using it.

Such a field also requires extra documentation, as the values it stores are not self describing.

OTHER TIPS

Bitmasking field is a bit more cryptic in nature and you need to create something else to interpret what you store in the bitmask.

The second approach is a lot more transparent and easily understandable and it's a bit more flexible if you need to add more values. With the bitmask, you again need to redo your bitmap decoder each time you add a value which can be a maintainance nightmare compared to the relational approach.

I have made the mistake of going with option 1, and given the opportunity to go back in time I would absolutely do it the other way.

Your database almost certainly will not use an index to make bitwise queries on your bitmask. So if you want to find, say, everyone working Tuesdays, you're going to do an index scan every time. As your tables get large, this can destroy your performance. You can try to optimize around this by caching a SELECT DISTINCT(bitmaskfield) ahead of time, doing the bitmask logic in your own application, and turing it into an appropriate WHERE bitmaskfield IN (...) clause, but that quickly becomes unmaintainable as you then have to update your distinct-bitmask cache in every place that you change values in the database.

The extra tables and joins may seem like a pain, but the bitmask will turn out worse. Trust me on this. Use your database as a database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top