Sobes.tech
Senior

WHERE A=a AND B=b vs WHERE B=b AND A=a Which composite index would you create?

sobes.tech AI

Answer from AI

When creating a composite index for conditions WHERE A=a AND B=b and WHERE B=b AND A=a, it is important to consider the order of columns in the index and the filtering selectivity.

If queries always use both conditions together, then an index on (A, B) or (B, A) will work, but the efficiency depends on which column is more selective (i.e., filters more data).

  • If A is more selective, an index on (A, B) is better.
  • If B is more selective, an index on (B, A) is better.

Also, note that an index on (A, B) is effectively used for queries filtering by A or by both A and B, but not for filtering only by B.

If queries vary in the order of conditions and sometimes filter by only one field, consider creating two separate indexes or using a covering index with included columns.

Example of creating an index in SQL:

CREATE INDEX idx_a_b ON table_name (A, B);
WHERE A=a AND B=b vs WHERE B=b AND A=a Which… - sobes.tech