Blogs · SQL · Database

SQL: Index and Optimization

A concise guide to SQL indexes, query plans, filtering, joins, aggregation, and practical optimization habits.

2020.08.31 · 1 min read · by Zhenlin Wang

Introduction

SQL optimization is about helping the database do less work. Indexes, query structure, and data layout all affect performance.

The first rule: measure before optimizing.

Indexes

An index is a data structure that helps the database find rows faster.

Index columns used in:

Example:

CREATE INDEX idx_orders_user_id ON orders(user_id);

Indexes are not free. They take storage and slow writes because the index must be updated when data changes.

Composite Indexes

A composite index covers multiple columns:

CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);

Column order matters. This index helps queries filtering by user_id, and it may help queries filtering by user_id plus created_at.

Query Plans

Use EXPLAIN to inspect how the database plans to run a query:

EXPLAIN
SELECT *
FROM orders
WHERE user_id = 42;

Look for:

Optimization Habits

Useful habits:

Common Mistakes

Optimization is a feedback loop: inspect the query, read the plan, change one thing, measure again.