Reputation: 31258
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:
acct_id
and index on tran_type
acct_id
and tran_type
Upvotes: 1
Views: 68
Reputation: 657202
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
Upvotes: 1
Reputation: 4694
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
Upvotes: 0