Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL unique index using gist

I have a table "locations" with "from" and "to" columns with "point" type. I'm only able to use "gist" indexes on those columns as the b-tree is not available for "point" type.

I would like to have a unique index on both of the columns (to ensure there is no same location stored).

This is not possible due to error "access method "gist" does not support unique indexes".

Is it somehow possible to achieve this? I could workaround it by creating regular text column storing "from_lat,from_lng:to_lat,to_lng" and add unique index on it, but is there a better way?

like image 798
morgoth Avatar asked Nov 30 '25 18:11

morgoth


1 Answers

You can use an exclusion constraint. A unique constraint (or index) is essentially just a special case of an exclusion constraint.

An exclusion constraints an be defined using GIST:

alter table locations
  add constraint unique_points
  exclude using gist ("from" with ~=, "to" with ~=);

The operator ~= checks for the equality of two points


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!