Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres hash index with unique constraint

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?

like image 901
Green Avatar asked May 31 '17 01:05

Green


People also ask

Does unique constraint CREATE INDEX in Postgres?

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.

Does a unique constraint create an index?

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.

What is the advantage of a hash index over a B-tree index in PostgreSQL?

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.

What is hash index in PostgreSQL?

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.


2 Answers

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.

like image 134
klin Avatar answered Sep 21 '22 10:09

klin


You can achieve this using an exclusion constraint:

create table t (id int);
alter table t add constraint c exclude using hash (id with =);
like image 29
jbg Avatar answered Sep 22 '22 10:09

jbg