Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Uso de índices
Los índices son estructuras de datos que permiten a la base de datos localizar filas sin escanear toda la tabla. Sin un índice, una consulta debe examinar cada fila para encontrar coincidencias. Con un índice, la base de datos puede saltar directamente a las filas relevantes, reduciendo drásticamente el número de filas examinadas.
Los índices aceleran las operaciones de lectura pero añaden sobrecarga a las escrituras (inserciones, actualizaciones, eliminaciones) porque el índice debe mantenerse sincronizado, por lo que deben crearse con cuidado y solo cuando sean necesarios.
Buenos candidatos para índices son las columnas usadas frecuentemente en cláusulas WHERE, uniones (joins) y ordenamientos. Cuando se usan varias columnas como filtro, puede ser útil crear un índice compuesto, pero recuerda que el orden de las columnas importa: coloca primero las más selectivas (con valores más únicos).
Análisis del rendimiento de consultas
La mayoría de bases de datos permiten inspeccionar cómo se ejecuta una consulta, lo que se llama plan de ejecución. Entender este plan te ayuda a identificar índices faltantes y optimizar la construcción de consultas comparando distintas formas de obtener los mismos datos.
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.
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.
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.
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).
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.
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.
This also applies to Amazon Aurora MySQL, which uses the same query engine and EXPLAIN syntax. See Aurora MySQL tuning for Aurora-specific guidance.
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.
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).
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.
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.
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.
Definición de índices en TypeORM
TypeORM permite crear índices en columnas de tablas usando el decorador @Index.
- 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
}
Para una visión completa de los tipos de índices (únicos, espaciales, fulltext, concurrentes, etc.), consulta la guía de Índices.
Una indexación adecuada suele ser la mejora de rendimiento más significativa: comienza analizando tus consultas más lentas con las herramientas de plan de ejecución mencionadas, luego añade índices donde más impacto tengan.