Junior — Middle
What is the difference between two independent indexes, each on one field, and a single combined index containing these two fields?
sobes.tech AI
Answer from AI
The difference between two independent indexes on one field and a combined index on two fields lies in how they are used for searching and query optimization.
-
Two independent indexes (on separate fields):
- Each index speeds up searches on its respective field.
- If a query filters on one of these fields, the index is used efficiently.
- When filtering on both fields simultaneously, the database can use one of the indexes or perform a union of results, which may be less efficient.
-
Combined index (composite index) on two fields:
- The index stores pairs of values (field1, field2) in a specific order.
- Very effective for queries filtering on the first field, as well as on both fields together.
- Less effective for queries filtering only on the second field (without the first), since the index is ordered first by the first field.
Example:
If there is a table with fields first_name and last_name:
- Indexes:
INDEX(first_name),INDEX(last_name)— speed up searches on each field separately. - Combined index:
INDEX(first_name, last_name)— speeds up searches onfirst_nameand on the combination offirst_name+last_name, but not onlast_namealone.
The choice depends on the types of queries that are performed most frequently.