Índices compostos e de cobertura
Acelere consultas com várias colunas usando índices compostos e elimine completamente as buscas na tabela com índices de cobertura que usam INCLUDE.
Índices compostos e de cobertura é uma aula grátis de PostgreSQL Performance & Query Optimization no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de PostgreSQL Performance & Query Optimization, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de PostgreSQL Performance & Query Optimization inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Beyond Single-Column Indexes
Many queries filter on more than one column. A composite index spans multiple columns and can serve such queries far better than separate single-column indexes.
Creating a Composite Index
List columns in the order you want them indexed.
CREATE INDEX idx_orders_cust_date
ON orders (customer_id, order_date);Column Order Matters
A composite index on (a, b) helps queries filtering on a alone or a AND b, but generally NOT queries filtering only on b.
The Leftmost Prefix Rule
PostgreSQL can use any leftmost prefix of the index. So (a, b, c) serves filters on a, on a+b, and on a+b+c.
Ordering by Selectivity
Put the most selective or most frequently filtered column first, often an equality column before a range column, to maximize how many rows the index eliminates early.
CREATE INDEX idx_orders_status_date
ON orders (status, order_date);The Heap Lookup Cost
A normal index scan finds matching rows then visits the table (the heap) to read the other columns. Those extra fetches cost I/O.
Covering Indexes
A covering index contains every column the query needs, so PostgreSQL answers from the index alone, an Index Only Scan, with no heap visit.
Using INCLUDE
The INCLUDE clause adds non-key columns to the index leaf pages so they are available without being part of the searchable key.
CREATE INDEX idx_orders_cust_incl
ON orders (customer_id)
INCLUDE (order_date, total);Confirming Index Only Scan
Check the plan; you want to see Index Only Scan rather than Index Scan plus heap fetches.
EXPLAIN ANALYZE
SELECT order_date, total
FROM orders WHERE customer_id = 42;The Visibility Map Caveat
Index Only Scans still need the heap when pages are not marked all-visible. Keeping tables well-vacuumed maintains the visibility map so scans stay index-only.
VACUUM ANALYZE orders;Costs of Wide Indexes
More columns mean larger indexes and slower writes. Add covering columns only for hot queries, not everywhere.
Quick Check
Test what you have learned.
Recap
You learned how composite indexes serve multi-column filters under the leftmost prefix rule, how column order and selectivity matter, and how covering indexes with INCLUDE enable Index Only Scans, balanced against larger size and write cost.
Perguntas Frequentes
A aula “Índices compostos e de cobertura” é grátis?
Sim — o texto completo de “Índices compostos e de cobertura” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de PostgreSQL Performance & Query Optimization, atualize para CoddyKit PRO. O curso de PostgreSQL Performance & Query Optimization inclui 4 aulas no total.
O que vou aprender em “Índices compostos e de cobertura”?
Acelere consultas com várias colunas usando índices compostos e elimine completamente as buscas na tabela com índices de cobertura que usam INCLUDE. Você pratica PostgreSQL Performance & Query Optimization com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar PostgreSQL Performance & Query Optimization?
Nenhuma experiência prévia é necessária. PostgreSQL Performance & Query Optimization no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Índices compostos e de cobertura”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de PostgreSQL Performance & Query Optimization?
Sim. Cada aula de PostgreSQL Performance & Query Optimization inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Fundamentos dos índices B-Tree
- Criando e usando índices
- Quando e como criar índices
- Índices compostos e de cobertura