Re: Multi-column index: Which column order - Mailing list pgsql-general

From Laurenz Albe
Subject Re: Multi-column index: Which column order
Date
Msg-id 8780fa45a4041e4229f4a3fa88a61778d8534ab2.camel@cybertec.at
Whole thread Raw
In response to Multi-column index: Which column order  (Sebastien Flaesch <sebastien.flaesch@4js.com>)
Responses Re: Multi-column index: Which column order  (Ron <ronljohnsonjr@gmail.com>)
List pgsql-general
On Tue, 2023-02-14 at 17:53 +0000, Sebastien Flaesch wrote:
> When creating an index on multiple columns, does the order of the columns matter?
> (I guess so)

It does, but not in your case.

> It's mostly for SELECT statements using a condition that include ALL columns of the index (pkey):
>
>      SELECT * FROM art WHERE etb='L1' and code='ART345'
>
> I would naturally put the columns with the most various values first, and
>
> For example, if the "code" column contains thousands of various item ids like 'SXZ874',
> 'ERF345', ... while the "etb" column contains a dozen of values like "L1", "LT" and "BX".
>
> Which one is best?
>
> CREATE UNIQUE INDEX ix1 ON art (code, etb)
> or
> CREATE UNIQUE INDEX ix1 ON art (etb, code)
>
> (or its PRIMARY KEY equivalent)

Both are the same.

There is an old myth that says that you should use the moew selective column first
(which would be "code"), but that is just a myth.

Order makes a difference for queries like "WHERE etb = 'L1' and code LIKE 'ART345'"
or "WHERE code = 'ART345' ORDER BY etb", but not for two equality comparisons.

> Does it depend on the type of index (Btree, GiST, etc) ?

Yes, it does.  For B-tree and GiST indexes order matters, for hash, GIN and BRIN
indexes it doesn't (for various reasons).

Yours,
Laurenz Albe
--
Cybertec | https://www.cybertec-postgresql.com



pgsql-general by date:

Previous
From: Bryn Llewellyn
Date:
Subject: Re: Order of rows in simple "select r from table_fn()"
Next
From: King of Hearts
Date:
Subject: unresolved external symbol when building on Windows