With Postgres 10 properly supporting hash index, I would like to use hash index for id lookup (hash index is smaller in size compared to btree and theoretically faster).
I have a table
create table t (id int);
create unique index on t using hash (id);
But I got the following:
ERROR: access method "hash" does not support unique indexes
Why does hash index not allow unique constraint? Are there ways to circumvent this?
PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.
PRIMARY KEY or UNIQUE constraint When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is automatically created if a clustered index on the table does not already exist and you do not specify a unique nonclustered index. The primary key column cannot allow NULL values.
Hash Index Advantages Over B-Tree Indexes The first advantage is the hash index can locate the key values being searched for without the need to traverse any type of tree data structure. This can be advantageous for large tables because of lowered I/O to find the necessary records.
Hash Index. Just like the name suggests, Hash indexes in PostgreSQL use a form of the hash table data structure. Hash table is a common data structure in many programming languages. For example, a Dict in Python, a HashMap in Java or the new Map type in JavaScript.
The documentation leaves no room for doubt:
Currently, only B-tree indexes can be declared unique.
There was a discussion on the hackers list about this recently, and it was concluded that it wouldn't be simple to add the capability to allow UNIQUE
hash indexes.
You can achieve this using an exclusion constraint:
create table t (id int);
alter table t add constraint c exclude using hash (id with =);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With