Creación y eliminación de índices
Aprenda los comandos SQL para crear, verificar y eliminar índices, junto con las prácticas recomendadas para administrarlos.
Creación y eliminación de índices es una lección gratuita de Advanced PostgreSQL: Indexing, Partitioning, Replication en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Advanced PostgreSQL: Indexing, Partitioning, Replication, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Advanced PostgreSQL: Indexing, Partitioning, Replication incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Index Management: The Basics
Time to get hands-on. This lesson covers the practical SQL to create, verify, and drop indexes — the everyday tools of index management.
Setting Up Our Table
First, let's build a small users table with a few rows to experiment on. Run the code to create and populate it.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100) UNIQUE,
city VARCHAR(100)
);
INSERT INTO users (name, email, city) VALUES
('Alice Smith', 'alice@example.com', 'New York'),
('Bob Johnson', 'bob@example.com', 'Los Angeles'),
('Charlie Brown', 'charlie@example.com', 'New York'),
('Diana Prince', 'diana@example.com', 'London');The CREATE INDEX Command
CREATE INDEX name ON table (column) builds an index to speed up queries. PostgreSQL makes it a B-tree by default — no USING BTREE needed.
Creating Your First Index
Let's index the city column so filtering by city gets much faster as the table grows. Run the command below.
CREATE INDEX idx_users_city ON users (city);Verifying Existing Indexes
Did it work? PostgreSQL's pg_indexes system view lists every index in your database — query it to inspect what you just built.
Example: Listing Indexes
Query pg_indexes filtered to the users table to confirm your new index exists. Run it and check the output.
SELECT indexname, tablename, indexdef
FROM pg_indexes
WHERE tablename = 'users';
Composite Indexes
When queries filter on several columns, use a composite index spanning them. Column order matters — match your typical WHERE clause order.
Creating a Composite Index
Here we build a composite index on city and name — handy when you often search by both at once. Then re-run the pg_indexes query.
CREATE INDEX idx_users_city_name ON users (city, name);The DROP INDEX Command
Drop an index when it's unused, slowing writes, or being replaced. The syntax is simple: DROP INDEX index_name.
Example: Dropping an Index
Let's remove the idx_users_city index by name with DROP INDEX, then verify it's gone with the pg_indexes query.
DROP INDEX idx_users_city;Quick Check: Index Commands
Consider a table named products with columns product_id, category, and price.
Recap: Index Management
That's index management: CREATE INDEX to add, pg_indexes to verify, DROP INDEX to remove. Next up: more advanced index types.
Preguntas frecuentes
¿La lección «Creación y eliminación de índices» es gratis?
Sí — el texto completo de «Creación y eliminación de índices» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Advanced PostgreSQL: Indexing, Partitioning, Replication, actualiza a CoddyKit PRO. El curso de Advanced PostgreSQL: Indexing, Partitioning, Replication incluye 4 lecciones en total.
¿Qué aprenderé en «Creación y eliminación de índices»?
Aprenda los comandos SQL para crear, verificar y eliminar índices, junto con las prácticas recomendadas para administrarlos. Practicas Advanced PostgreSQL: Indexing, Partitioning, Replication con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Advanced PostgreSQL: Indexing, Partitioning, Replication?
No se requiere experiencia previa. Advanced PostgreSQL: Indexing, Partitioning, Replication en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Creación y eliminación de índices»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Advanced PostgreSQL: Indexing, Partitioning, Replication?
Sí. Cada lección de Advanced PostgreSQL: Indexing, Partitioning, Replication incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Por qué son importantes los índices
- Conceptos básicos de los índices B-tree
- Creación y eliminación de índices
- Índices de claves únicas y primarias