✏️ Explanatory Question

What is a composite index and why does column order matter?

👁 8 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

54

What is a composite index and why does column order matter?

Level: Advanced — Understanding the "leftmost prefix" rule is a strong signal of query-tuning skill.

A composite index (also called a multi-column or concatenated index) is a single index built on two or more columns. It is sorted first by the leftmost column, then by the next, and so on — like sorting a list by last name, then first name.

The Leftmost Prefix Rule: MySQL can use a composite index only if the query filters on a left-to-right prefix of the indexed columns. It can use column 1, or columns 1+2, or 1+2+3 — but not column 2 alone or column 3 alone.

Which Queries Use Index (a, b, c)?

WHERE Condition Uses Index? Reason
a = ? Yes Leftmost column
a = ? AND b = ? Yes Prefix a, b
a = ? AND b = ? AND c = ? Yes (fully) Full index
b = ? No Skips leftmost column a
a = ? AND c = ? Partial (only a) Gap at b breaks the prefix

How to Order Columns

  • Put the most frequently filtered column first.
  • Put equality (=) columns before range (>, <, BETWEEN) columns.
  • Put high-selectivity (many distinct values) columns earlier for better filtering.
Range column caveat: Once a range condition is used on a column, the index cannot be used for equality on columns after it. So place range columns last.

Quick Example

-- Composite index: order is (dept_id, salary)
CREATE INDEX idx_dept_sal ON employees(dept_id, salary);

-- USES index (leftmost prefix)
SELECT * FROM employees WHERE dept_id = 10;
SELECT * FROM employees WHERE dept_id = 10 AND salary > 50000;

-- Does NOT use the index efficiently (skips leftmost dept_id)
SELECT * FROM employees WHERE salary > 50000;

-- Verify with EXPLAIN
EXPLAIN SELECT * FROM employees WHERE dept_id = 10 AND salary > 50000;
Interviewer tip: The one-liner they want — "A composite index spans multiple columns and follows the leftmost prefix rule — MySQL can only use it when the query filters on a left-to-right prefix. Place equality columns before range columns."