Owens

Owens

Ecto Postgres Index vs Unique Index

Hello all,

Does anyone know if you create a unique_index in postgres for two fields on a table, does that mean you DON’T need to create an additional index on those two tables?

e.g.

  1. create unique_index(:projects, [:organization_id, :name])

means you DON’T need to do create index(:projects, [:organization_id])

  1. create unique_index(:team_users, [:team_id, :user_id])

means you DON’T need to do

create index(:teams_users, [:team_id])
create index(:teams_users, [:user_id])

AND if you already setup those indexes before the unique_indexes, should you drop/delete those indexes before migrating the unique_indexes?

Marked As Solved

amnu3387

amnu3387

From what I understood from this (Multicolumn indexes pg 9.6 (but same up to 12) the indexes can be used when the query involves columns from the index, going from the left to right.

In this case the second index on organization_id doesn’t give you anything extra since the leftmost column of the unique index you created before, is that same column.

Here you wouldn’t need a team_id index, but you would need a user_id if you are planning on querying the teams_users table solely by user_id (without team_id that is).
The team_id being the leftmost column declared on the unique_index would be used when a query containing a team_id column is made.

Theoretically this applies to indexes with more than 2 columns too.
E.g.

unique index on a, b, c
Means that pg can use the index on a query containing:
a
a,b
and a,b,c

(though it still goes through the planner ofc, so it might not use it, but that wouldn’t be because it can’t, at least this is my reading from the docs, it also means that the order in which you declare the columns for the index plays a role too)

Also Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Unique constraints will create a unique index in the background anyway, it’s the only way to enforce the constraint in a performant manner.

Basically, create unique indices to enforce uniqueness rules. Also, create indices to reflect query patterns. If those two reasons to create indices happen to overlap, great! But it isn’t a big deal if they don’t, and they’re both perfectly valid reasons to create an index.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

It does not mean that. The index will only be used if you query both of those fields. If you query only one of them, it cannot use that index. If you plan to query the table by those fields individually then you also want indices on those fields.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

As far as I can tell there isn’t any practical difference, however I think from a clarity perspective it is better to use constraints to enforce uniqueness. Just know that you don’t need to make an index for it, one will be created already.

kip

kip

ex_cldr Core Team

With some material limitations, Postgres can use a leading subset of multi-column indexes. From the documentation:

A multicolumn B-tree index can be used with query conditions that involve any subset of the index’s columns, but the index is most efficient when there are constraints on the leading (leftmost) columns. The exact rule is that equality constraints on leading columns, plus any inequality constraints on the first column that does not have an equality constraint, will be used to limit the portion of the index that is scanned. Constraints on columns to the right of these columns are checked in the index, so they save visits to the table proper, but they do not reduce the portion of the index that has to be scanned. For example, given an index on (a, b, c) and a query condition WHERE a = 5 AND b >= 42 AND c < 77 , the index would have to be scanned from the first entry with a = 5 and b = 42 up through the last entry with a = 5. Index entries with c >= 77 would be skipped, but they’d still have to be scanned through. This index could in principle be used for queries that have constraints on b and/or c with no constraint on a — but the entire index would have to be scanned, so in most cases the planner would prefer a sequential table scan over using the index.

But as Ben says, not appropriate to apply unique constraints.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Yup so was I, in fact ecto unique constraints rely on postgres constraints, they don’t replace them.

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New

Other popular topics Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement