sqlpostgresqlindexingpartial-index

Does an index on columns not used in a SELECT query make a difference?


I have a table:

T(A, B, C, D)

With this query:

SELECT A
FROM T 
WHERE B = C

Does having an index on D make a difference in the performance of the given query?

Does having an index on columns that are not used in a select query make a difference?


Solution

  • Does having an index on D make a difference in the performance of the given query? Does having an index on columns that are not used in a select query make a difference?

    No to both questions.

    An index on D is dead freight and not involved in the given query. It neither helps nor hinders it. There are hypothetical side effects of maintaining another index, by way of wasting resources. But, basically, it's a clear "No".

    Actually useful index

    In fact, the only (potentially) useful index for this query is a partial index of the form:

    CREATE INDEX useful_idx ON t (a) WHERE b = c;
    

    Proof:

    fiddle

    Creating such a tailored index only makes sense, if ...

    1. ... WHERE b = c is selective (only a small part of the table qualifies)
    2. ... that exact condition is used often enough to warrant the cost for maintaining another index.

    The condition WHERE b = c cannot make use of a plain index on the involved columns. That's not how indexes work. You need a constant input value to look something up in the index. B = C has no such constant, both values change from row to row.