1. Background
I was working on an online account adjustment system this week, and one requirement was tricky: after submitting an adjustment request, the system records the corresponding adjustment types in a database table. On the review page, the filter for adjustment types needed to support multi-select. Here’s the enum:
1 | public enum AdjustTypeEnum { |
If request A involves both “Expected Penalty Interest” and “Expected Total Repayment,” the stored value would be 0,1. On the review page, if the filter includes either of those two types, the query should return this request. The problem is that MySQL’s FIND_IN_SET only supports single-value matching — it can’t flexibly decompose the stored comma-separated values against a multi-select filter. This meant rethinking both the storage format and the query logic.
2. The Power of Bitwise AND
The abstraction we needed had to do two things at once: store multiple values in a single column (saving space, keeping the schema clean), while still letting the database engine query individual items within that combined value. The data should look combined on the surface, but each piece remains individually addressable underneath.
The comma-separated approach couldn’t satisfy this. Binary representation works better. A few bitwise AND examples show why:
1 | // Stored value: 3; Filter condition: 1 |
1 | // Stored value: 7; Filter condition: 1 |
1 | // Stored value: 7; Filter condition: 3 |
1 | // Stored value: 7; Filter condition: 15 |
The pattern is clear: if each enum value is a power of 2, summing the selected values maps each one to a distinct bit position.
For any filter condition, a single bitwise AND against the stored sum tells you whether there’s a match — the result equals the filter value if matched, or differs if not.
With this approach, the enum becomes:
1 | public enum AdjustTypeEnum { |
And the query becomes:
1 | SELECT |