HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

PostgreSQL indexing on bit string

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlindexingbitstring

Problem

What is the best way to create an index on a bit string column? Let's say I had the column of type bit(4) and I wanted to search for all entries that had had a specific bit set. So if I had the entries:

bitfield | ...
--------------
1001
1010
0110
0010
0000


If I was trying to search for all entries that 0010 set, I can easily do that. But can I use indexes to optimize the searching?

Solution

First of all: it would be more efficient to store 4 bits of information as separate boolean columns - in every respect: easier to handle, easier to understand and change, easier to index, even smaller storage size! Closely related answer:

  • Does it make sense to store a couple of Boolean values as array?



To answer your question asked: you can use a partial index like:

CREATE INDEX foo ON tbl (tbl_id)
WHERE bitfield & '0010' = '0010';


& being the bitwise AND operator.

tbl_id being the PK column. (The actual index column hardly matters here.)

In combination with a matching query:

SELECT *
FROM   tbl
WHERE  bitfield & '0010' = '0010';


But your question probably does not reflect your complete situation. There may be better options.

Code Snippets

CREATE INDEX foo ON tbl (tbl_id)
WHERE bitfield & '0010' = '0010';
SELECT *
FROM   tbl
WHERE  bitfield & '0010' = '0010';

Context

StackExchange Database Administrators Q#144463, answer score: 8

Revisions (0)

No revisions yet.