From: Erik Wienhold <ewie@ewie.name>
To: Sebastien Flaesch <sebastien.flaesch@4js.com>
To: pgsql-general@postgresql.org <pgsql-general@postgresql.org>
Subject: Re: Multi-column index: Which column order
Date: Tue, 14 Feb 2023 19:47:02 +0100 (CET)
Message-ID: <824167798.67572.1676400422583@office.mailbox.org> (raw)
In-Reply-To: <DBAP191MB12893BBE46573CA38E0FE921B0A29@DBAP191MB1289.EURP191.PROD.OUTLOOK.COM>
References: <DBAP191MB12893BBE46573CA38E0FE921B0A29@DBAP191MB1289.EURP191.PROD.OUTLOOK.COM>
> On 14/02/2023 18:53 CET Sebastien Flaesch <sebastien.flaesch@4js.com> wrote:
>
> Hello!
>
> When creating an index on multiple columns, does the order of the columns
> matter? (I guess so)
Maybe, depending on the queries.
> 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)
It should not make any difference for the query above. It can make a
difference for queries that only filter by the second index column or use
inequality constraints on those columns.
> Does it depend on the type of index (Btree, GiST, etc) ?
>
> I could not find that information in the doc.
Yes, see the documentation on multicolumn indexes with details on how they
are used: https://www.postgresql.org/docs/current/indexes-multicolumn.html
But you're limited to btree anyway if you're only interested in unique
indexes.
--
Erik
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: ewie@ewie.name, sebastien.flaesch@4js.com
Subject: Re: Multi-column index: Which column order
In-Reply-To: <824167798.67572.1676400422583@office.mailbox.org>
References: <DBAP191MB12893BBE46573CA38E0FE921B0A29@DBAP191MB1289.EURP191.PROD.OUTLOOK.COM> <824167798.67572.1676400422583@office.mailbox.org>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox