使用索引
索引是一种数据结构,它让数据库无需扫描整张表就能定位到行。没有索引时,查询必须检查每一行来寻找匹配项。有了索引,数据库可以直接跳到相关的行——大幅减少被检查的行数。
索引能加速读操作,但会给写操作(插入、更新、删除)带来额外开销,因为索引必须保持同步,所以应当谨慎创建、仅在需要时创建。
适合建索引的候选列,是那些经常出现在 WHERE 子句、连接和排序中的列。当有多个列被用作过滤条件时,创建复合索引可能有意义,不过请记住列的顺序很重要——把选择性最高(唯一值最多)的列放在最前面。
分析查询性能
大多数数据库都允许你查看一条查询是如何被执行的,这被称为执行计划。理解这样的计划有助于你找出缺失的索引,并通过比较获取同一数据的各种方式来优化查询的构造方式。
CockroachDB
使用 EXPLAIN ANALYZE(语法与 PostgreSQL 相同):
EXPLAIN ANALYZE SELECT * FROM "user" WHERE "firstName" = 'Timber';留意 full scan(无索引)与带具体索引名的 scan 之间的区别。
进一步了解
Google Spanner
在 Google Cloud Console 中使用 Query Plan visualizer,或者通过 gcloud CLI 以 PLAN/PROFILE 模式运行查询:
gcloud spanner databases execute-sql DATABASE_ID \
--instance=INSTANCE_ID \
--query-mode=PROFILE \
--sql="SELECT * FROM user WHERE firstName = 'Timber'"在返回的计划中留意 Table Scan(无索引)与 Index Scan 的区别。
进一步了解
MariaDB
使用 EXPLAIN 或 ANALYZE 查看查询执行计划:
ANALYZE SELECT * FROM user WHERE firstName = 'Timber';检查 type 列——ALL 表示全表扫描,而 ref、range 或 index 表示用到了索引。key 列显示选择了哪个索引。
进一步了解
MongoDB
在查询上使用 explain() 方法查看执行计划:
db.user.find({ firstName: "Timber" }).explain("executionStats")留意 COLLSCAN(集合扫描——无索引)与 IXSCAN(索引扫描)的区别。
进一步了解
MS SQL Server
使用执行计划分析查询。在 SQL Server Management Studio 中,按 Ctrl+M 包含实际执行计划,然后运行你的查询。以编程方式:
SET STATISTICS IO ON;
SELECT * FROM [user] WHERE firstName = 'Timber';
SET STATISTICS IO OFF;在执行计划中留意 Table Scan(无索引)与 Index Seek 或 Index Scan 的区别。
进一步了解
MySQL
使用 EXPLAIN 查看查询执行计划:
EXPLAIN SELECT * FROM user WHERE firstName = 'Timber';检查 type 列——ALL 表示全表扫描,而 ref、range 或 index 表示用到了索引。key 列显示选择了哪个索引。
Aurora MySQL
这同样适用于 Amazon Aurora MySQL,它使用相同的查询引擎和 EXPLAIN 语法。Aurora 专属的指导请参阅 Aurora MySQL 调优。
进一步了解
Oracle
使用 EXPLAIN PLAN 查看执行计划:
EXPLAIN PLAN FOR SELECT * FROM "user" WHERE "firstName" = 'Timber';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);留意 TABLE ACCESS FULL(无索引)与 INDEX RANGE SCAN 或 INDEX UNIQUE SCAN 的区别。
进一步了解
PostgreSQL
使用 EXPLAIN ANALYZE 查看 PostgreSQL 如何执行查询以及是否使用了索引:
EXPLAIN ANALYZE SELECT * FROM "user" WHERE "firstName" = 'Timber';留意 Seq Scan(全表扫描——未使用索引)与 Index Scan 或 Index Only Scan(使用了索引)的区别。
Aurora PostgreSQL
这同样适用于 Amazon Aurora PostgreSQL,它使用相同的查询引擎和 EXPLAIN 语法。Aurora 还提供查询计划管理,用于捕获和控制执行计划。
进一步了解
SAP HANA
使用 EXPLAIN PLAN FOR 查看执行计划:
EXPLAIN PLAN FOR SELECT * FROM "user" WHERE "firstName" = 'Timber';
SELECT * FROM EXPLAIN_PLAN_TABLE;在 operator 列中留意 TABLE SCAN(无索引)与 INDEX SCAN 或 INDEX SEEK 的区别。
进一步了解
SQLite
使用 EXPLAIN QUERY PLAN 查看 SQLite 如何解析查询:
EXPLAIN QUERY PLAN SELECT * FROM user WHERE firstName = 'Timber';在输出中留意 SCAN(无索引)与 SEARCH(使用了索引)的区别。
进一步了解
在 TypeORM 中定义索引
TypeORM 支持用 @Index 装饰器在表列上创建索引。
- 基础索引
- 复合索引
- 连接列
import { Entity, PrimaryGeneratedColumn, Column, Index } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
@Index()
email: string
@Column()
firstName: string
}import { Entity, PrimaryGeneratedColumn, Column, Index } from "typeorm"
@Entity()
@Index(["lastName", "firstName"]) // 选择性最高的列放最前
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
}import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
Index,
} from "typeorm"
import { User } from "./User"
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@ManyToOne(() => User)
@Index() // 给外键列建索引以加速连接
author: User
}要全面了解各种索引类型(唯一、空间、全文、并发等),请阅读索引指南。
合理的索引往往是你能做出的最大单项性能改进——先用上面的执行计划工具分析最慢的查询,然后在最关键的地方加上索引。
Indexes are data structures that allow the database to locate rows without scanning the entire table. Without an index, a query must examine every row to find matches. With an index, the database can jump directly to the relevant rows — dramatically reducing the number of rows examined.
Indexes accelerate read operations but add overhead to writes (inserts, updates, deletes) since the index must be kept in sync, so they should be created carefully and only when needed.
Good candidates for indexes are columns frequently used in WHERE clauses, joins, and sorting. When more than one column is used as a filter, it might make sense to create a composite index, however bear in mind that column order matters — place the most selective (most unique values) columns first.
Analyzing query performance
Most databases let you inspect how a query is being executed, which is called an execution plan. Understanding such a plan helps you identify missing indexes and optimize how a query is constructed by comparing various ways of fetching the same data.
CockroachDB
Use EXPLAIN ANALYZE (same syntax as PostgreSQL):
EXPLAIN ANALYZE SELECT * FROM "user" WHERE "firstName" = 'Timber';Look for full scan (no index) vs scan with a specific index name.
Learn more
Google Spanner
Use the Query Plan visualizer in the Google Cloud Console, or run a query in PLAN/PROFILE mode via the gcloud CLI:
gcloud spanner databases execute-sql DATABASE_ID \
--instance=INSTANCE_ID \
--query-mode=PROFILE \
--sql="SELECT * FROM user WHERE firstName = 'Timber'"Look for Table Scan (no index) vs Index Scan in the returned plan.
Learn more
MariaDB
Use EXPLAIN or ANALYZE to inspect the query execution plan:
ANALYZE SELECT * FROM user WHERE firstName = 'Timber';Check the type column — ALL means a full table scan, while ref, range, or index indicate index usage. The key column shows which index was chosen.
Learn more
MongoDB
Use the explain() method on a query to see the execution plan:
db.user.find({ firstName: "Timber" }).explain("executionStats")Look for COLLSCAN (collection scan — no index) vs IXSCAN (index scan).
Learn more
MS SQL Server
Use the execution plan to analyze queries. In SQL Server Management Studio, press Ctrl+M to include the actual execution plan, then run your query. Programmatically:
SET STATISTICS IO ON;
SELECT * FROM [user] WHERE firstName = 'Timber';
SET STATISTICS IO OFF;Look for Table Scan (no index) vs Index Seek or Index Scan in the execution plan.
Learn more
MySQL
Use EXPLAIN to inspect the query execution plan:
EXPLAIN SELECT * FROM user WHERE firstName = 'Timber';Check the type column — ALL means a full table scan, while ref, range, or index indicate index usage. The key column shows which index was chosen.
Aurora MySQL
This also applies to Amazon Aurora MySQL, which uses the same query engine and EXPLAIN syntax. See Aurora MySQL tuning for Aurora-specific guidance.
Learn more
Oracle
Use EXPLAIN PLAN to inspect the execution plan:
EXPLAIN PLAN FOR SELECT * FROM "user" WHERE "firstName" = 'Timber';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);Look for TABLE ACCESS FULL (no index) vs INDEX RANGE SCAN or INDEX UNIQUE SCAN.
Learn more
PostgreSQL
Use EXPLAIN ANALYZE to see how PostgreSQL executes a query and whether it uses indexes:
EXPLAIN ANALYZE SELECT * FROM "user" WHERE "firstName" = 'Timber';Look for Seq Scan (full table scan — no index used) vs Index Scan or Index Only Scan (index used).
Aurora PostgreSQL
This also applies to Amazon Aurora PostgreSQL, which uses the same query engine and EXPLAIN syntax. Aurora also offers query plan management for capturing and controlling execution plans.
Learn more
SAP HANA
Use EXPLAIN PLAN FOR to inspect the execution plan:
EXPLAIN PLAN FOR SELECT * FROM "user" WHERE "firstName" = 'Timber';
SELECT * FROM EXPLAIN_PLAN_TABLE;Look for TABLE SCAN (no index) vs INDEX SCAN or INDEX SEEK in the operator column.
Learn more
SQLite
Use EXPLAIN QUERY PLAN to see how SQLite resolves a query:
EXPLAIN QUERY PLAN SELECT * FROM user WHERE firstName = 'Timber';Look for SCAN (no index) vs SEARCH (index used) in the output.
Learn more
Defining indexes in TypeORM
TypeORM supports creating indexes on table columns using the @Index decorator.
- Basic index
- Composite index
- Join column
import { Entity, PrimaryGeneratedColumn, Column, Index } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
@Index()
email: string
@Column()
firstName: string
}import { Entity, PrimaryGeneratedColumn, Column, Index } from "typeorm"
@Entity()
@Index(["lastName", "firstName"]) // most selective column first
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
}import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
Index,
} from "typeorm"
import { User } from "./User"
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@ManyToOne(() => User)
@Index() // index foreign key columns to speed up joins
author: User
}For a comprehensive overview of different index types (unique, spatial, fulltext, concurrent, and more), read the Indexes guide.
Proper indexing is often the single biggest performance improvement you can make — start by analyzing your slowest queries with the execution plan tools above, then add indexes where they matter most.