Domanda

My Postgres table looks something like this:

tran_id SERIAL PRIMARY KEY,
acct_id int NOT NULL,
tran_type char(2) NOT NULL,
/* some performance irrelevant fields */

The only multi-row query the application will run is as follows:

SELECT acct_id, COUNT(tran_id) FROM table WHERE tran_type = 'X' GROUP BY acct_id;

So I always just want to pull a list of accounts that have a particular transaction type and get the number of transactions of that type. With that in mind, what are my best choices for indexing:

  1. index on acct_id and index on tran_type
  2. composite index on acct_id and tran_type
    1. and 2. combined (3 indexes total)
  3. something else?
È stato utile?

Soluzione

Number 2. But the sequence of columns is essential. Make it:

CREATE INDEX tbl_mult_idx ON tbl (tran_type, acct_id)

Also, it would be more effective to have an integer column (or an enum) instead of char(2) for the type.

And use count(*) instead of count(tran_id) if tran_id is defined NOT NULL. It's a bit faster.

More details in this related answer on dba.SE

Altri suggerimenti

build your number 2 :). It is just one index - will be easier to maintain, it will serve your query perfectly, and even more - it will not use table at all, just index!

under number 4 could be materialized view

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top