SlideShare uma empresa Scribd logo
1 de 42
MENTOR
Your Indexes
Bill Karwin
Independent Oracle Users Group • 2010-9-21
Me

• Software developer
• C, Java, Perl, PHP, Ruby
• SQL maven
• Author of new book
  SQL Antipatterns
“Whenever any result is sought, the
question will then arise—by what
course of calculation can these results
be arrived at by the machine in the
shortest time?”
           — Charles Babbage, Passages from the
                     Life of a Philosopher (1864)
Indexes
Common blunders:

• Creating indexes naively
• Executing non-indexable queries
• Rejecting indexes because of overhead
CREATE TABLE Posts (

 PostId
 
 
 
 SERIAL PRIMARY KEY,

 CreationDate
 DATE NOT NULL,

 Title

 
 
 
 VARCHAR(80) NOT NULL,

 Body

 
 
 
 TEXT NOT NULL,

 Score
 
 
 
 INT
);
CREATE TABLE Posts (

 PostId
 
 
 
 SERIAL PRIMARY KEY,

 CreationDate
 DATE NOT NULL,

 Title

 
 
 
 VARCHAR(80) NOT NULL,

 Body

 
 
 
 TEXT NOT NULL,

 Score
 
 
 
 INT,

 INDEX (PostId)
);
                   redundant index,
                     already in PK
CREATE TABLE Posts (

 PostId
 
 
 
 SERIAL PRIMARY KEY,

 CreationDate
 DATE NOT NULL,

 Title

 
 
 
 VARCHAR(80) NOT NULL,

 Body

 
 
 
 TEXT NOT NULL,

 Score
 
 
 
 INT,

 INDEX (Title)
);
  bulky index
CREATE TABLE Posts (

 PostId
 
 
 
 SERIAL PRIMARY KEY,

 CreationDate
 DATE NOT NULL,

 Title

 
 
 
 VARCHAR(80) NOT NULL,

 Body

 
 
 
 TEXT NOT NULL,

 Score
 
 
 
 INT,

 INDEX (Score)
);                  unnecessary index,
                we may never query on score
CREATE TABLE Posts (

 PostId
 
 
 
 SERIAL PRIMARY KEY,

 CreationDate
 DATE NOT NULL,

 Title

 
 
 
 VARCHAR(80) NOT NULL,

 Body

 
 
 
 TEXT NOT NULL,

 Score
 
 
 
 INT,

 INDEX (Score, CreationDate, Title)
);
         unnecessary
       composite index
SELECT * FROM Posts
WHERE Title LIKE ‘%crash%’

                    non-leftmost
                    string match
Telephone book analogy:

• Easy to search for Dean Thomas:
                                      uses index
                                       to match
  SELECT * FROM TelephoneBook
  WHERE full_name LIKE ‘Thomas, %’

• Hard to search for Thomas Riddle:   requires full
                                       table scan
  SELECT * FROM TelephoneBook
  WHERE full_name LIKE ‘%, Thomas’
SELECT * FROM Posts
WHERE MONTH(CreationDate) = 4
              function applied
                 to column
SELECT * FROM Users
WHERE LastName = ‘Thomas’
 OR FirstName = ‘Thomas’
          just like searching
            for first_name
SELECT * FROM Users
ORDER BY FirstName, LastName
                    non-leftmost
                 composite key match
the benefit quickly
                      justifies the overhead




O(n) table scan
O(log n) index scan
Relational         Index
data modeling   optimization
  is derived      is derived
  from data     from queries
MENTOR Your
  Indexes
Measure
 Explain
Nominate
  Test
Optimize
 Repair
Measure
 Explain
Nominate
  Test
Optimize
 Repair
• Profile your code to identify your biggest
  performance costs.
  • MySQL: PROFILER
  • Oracle: TKPROF or Trace Analyzer
  • Application-level profiling
Measure
 Explain
Nominate
  Test
Optimize
 Repair
• Analyze the database’s optimization plan
    for costly queries.
•   Identify queries that don’t use indexes.
• MySQL: EXPLAIN Query
  • “Explain Output Format”
    http://dev.mysql.com/doc/refman/5.5/en/
    explain-output.html
• Oracle: EXPLAIN PLAN Query
  • “Understanding Explain Plan”
    http://www.orafaq.com/node/1420
Measure
 Explain
Nominate
  Test
Optimize
 Repair
• Which queries need optimization?
  • Frequently used queries
  • Very slow queries
  • Reports
• Which column(s) need indexes?
  • WHERE conditions
  • JOIN conditions
  • ORDER BY criteria
  • MIN() / MAX()
• Automatic tools for nominating indexes:
 • MySQL Enterprise Query Analyzer
 • Oracle Automatic SQL Tuning Advisor
Measure
 Explain
Nominate
  Test
Optimize
 Repair
• After creating index, measure your high-
    priority queries again.
•   Confirm that the new index made a
    difference to these queries.
•   Impress your boss/client!
      “The new index gave us a 127%
      performance improvement!”
Measure
 Explain
Nominate
  Test
Optimize
 Repair
• Indexes are compact, frequently-used data
    structures.
•   Try to cache indexes in memory.
• Cache indexes in MySQL/InnoDB:
 • Increase innodb_buffer_pool_size
 • Used for both data and indexes
• Cache indexes in MySQL/MyISAM:
  • Increase key_buffer_size
  • LOAD INDEX INTO CACHE TableName
    [INDEX IndexName];
• Cache indexes in Oracle:
  ALTER SYSTEM SET DB_32K_CACHE_SIZE = 100m;
  CREATE TABLESPACE INDEX_TS_32K
  BLOCKSIZE 32K;
  ALTER INDEX IndexName REBUILD ONLINE
  TABLESPACE INDEX_TS_32K;

  http://www.dba-oracle.com/art_so_optimizer_index_caching.htm
Measure
 Explain
Nominate
  Test
Optimize
 Repair
• Indexes require periodic maintenance.
• Like a filesystem requires periodic
  defragmentation.
• Analyze / rebuild indexes in MySQL:
  • ANALYZE TABLE TableName
  • OPTIMIZE TABLE TableName
• Analyze / rebuild indexes in Oracle:
  • ANALYZE INDEX IndexName
  • ALTER INDEX IndexName REBUILD ...
1. Know Your Data.
2. Know Your Queries.
3. MENTOR Your Indexes.
SQL Antipatterns:
Avoiding the Pitfalls of
Database Programming




http://www.pragprog.com/titles/bksqla/
Copyright 2010 Bill Karwin
        www.slideshare.net/billkarwin
              Released under a Creative Commons 3.0 License:
              http://creativecommons.org/licenses/by-nc-nd/3.0/

                You are free to share - to copy, distribute and
             transmit this work, under the following conditions:

   Attribution.                Noncommercial.          No Derivative Works.
You must attribute this    You may not use this work       You may not alter,
 work to Bill Karwin.       for commercial purposes.      transform, or build
                                                            upon this work.

Mais conteúdo relacionado

Mais procurados

How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
MYXPLAIN
 

Mais procurados (20)

MySQL Atchitecture and Concepts
MySQL Atchitecture and ConceptsMySQL Atchitecture and Concepts
MySQL Atchitecture and Concepts
 
How to Use JSON in MySQL Wrong
How to Use JSON in MySQL WrongHow to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
 
How to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better PerformanceHow to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better Performance
 
Modern query optimisation features in MySQL 8.
Modern query optimisation features in MySQL 8.Modern query optimisation features in MySQL 8.
Modern query optimisation features in MySQL 8.
 
How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
 
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
 
MySQL Advanced Administrator 2021 - 네오클로바
MySQL Advanced Administrator 2021 - 네오클로바MySQL Advanced Administrator 2021 - 네오클로바
MySQL Advanced Administrator 2021 - 네오클로바
 
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLTop 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
 
How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
 
Oracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptOracle Database Performance Tuning Concept
Oracle Database Performance Tuning Concept
 
Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
 
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data TablesPostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
 
Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0
 
MariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsMariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAs
 
Indexes in postgres
Indexes in postgresIndexes in postgres
Indexes in postgres
 
Sql Server Performance Tuning
Sql Server Performance TuningSql Server Performance Tuning
Sql Server Performance Tuning
 
More mastering the art of indexing
More mastering the art of indexingMore mastering the art of indexing
More mastering the art of indexing
 
Oracle Database Advanced Querying
Oracle Database Advanced QueryingOracle Database Advanced Querying
Oracle Database Advanced Querying
 
SQL Plan Directives explained
SQL Plan Directives explainedSQL Plan Directives explained
SQL Plan Directives explained
 

Destaque

Hierarchical data models in Relational Databases
Hierarchical data models in Relational DatabasesHierarchical data models in Relational Databases
Hierarchical data models in Relational Databases
navicorevn
 

Destaque (15)

InnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick FiguresInnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick Figures
 
MySQL 5.5 Guide to InnoDB Status
MySQL 5.5 Guide to InnoDB StatusMySQL 5.5 Guide to InnoDB Status
MySQL 5.5 Guide to InnoDB Status
 
Survey of Percona Toolkit
Survey of Percona ToolkitSurvey of Percona Toolkit
Survey of Percona Toolkit
 
Schemadoc
SchemadocSchemadoc
Schemadoc
 
Requirements the Last Bottleneck
Requirements the Last BottleneckRequirements the Last Bottleneck
Requirements the Last Bottleneck
 
Percona toolkit
Percona toolkitPercona toolkit
Percona toolkit
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
 
SQL Outer Joins for Fun and Profit
SQL Outer Joins for Fun and ProfitSQL Outer Joins for Fun and Profit
SQL Outer Joins for Fun and Profit
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
 
Practical Object Oriented Models In Sql
Practical Object Oriented Models In SqlPractical Object Oriented Models In Sql
Practical Object Oriented Models In Sql
 
Full Text Search In PostgreSQL
Full Text Search In PostgreSQLFull Text Search In PostgreSQL
Full Text Search In PostgreSQL
 
Hierarchical data models in Relational Databases
Hierarchical data models in Relational DatabasesHierarchical data models in Relational Databases
Hierarchical data models in Relational Databases
 
Trees and Hierarchies in SQL
Trees and Hierarchies in SQLTrees and Hierarchies in SQL
Trees and Hierarchies in SQL
 
Trees In The Database - Advanced data structures
Trees In The Database - Advanced data structuresTrees In The Database - Advanced data structures
Trees In The Database - Advanced data structures
 

Semelhante a Mentor Your Indexes

Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimization
Baohua Cai
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
086ChintanPatel1
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
jyothimuppasani1
 

Semelhante a Mentor Your Indexes (20)

Dive Into Azure Data Lake - PASS 2017
Dive Into Azure Data Lake - PASS 2017Dive Into Azure Data Lake - PASS 2017
Dive Into Azure Data Lake - PASS 2017
 
SQL
SQLSQL
SQL
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowTen query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should know
 
The perfect index
The perfect indexThe perfect index
The perfect index
 
Dan Hotka's Top 10 Oracle 12c New Features
Dan Hotka's Top 10 Oracle 12c New FeaturesDan Hotka's Top 10 Oracle 12c New Features
Dan Hotka's Top 10 Oracle 12c New Features
 
PostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty databasePostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty database
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimization
 
Les09
Les09Les09
Les09
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
 
Tech Gupshup Meetup On MongoDB - 24/06/2016
Tech Gupshup Meetup On MongoDB - 24/06/2016Tech Gupshup Meetup On MongoDB - 24/06/2016
Tech Gupshup Meetup On MongoDB - 24/06/2016
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for Developers
 
Access 04
Access 04Access 04
Access 04
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
 
High Performance Rails with MySQL
High Performance Rails with MySQLHigh Performance Rails with MySQL
High Performance Rails with MySQL
 
Taming the Data Science Monster with A New ‘Sword’ – U-SQL
Taming the Data Science Monster with A New ‘Sword’ – U-SQLTaming the Data Science Monster with A New ‘Sword’ – U-SQL
Taming the Data Science Monster with A New ‘Sword’ – U-SQL
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

Mentor Your Indexes

  • 1. MENTOR Your Indexes Bill Karwin Independent Oracle Users Group • 2010-9-21
  • 2. Me • Software developer • C, Java, Perl, PHP, Ruby • SQL maven • Author of new book SQL Antipatterns
  • 3. “Whenever any result is sought, the question will then arise—by what course of calculation can these results be arrived at by the machine in the shortest time?” — Charles Babbage, Passages from the Life of a Philosopher (1864)
  • 5. Common blunders: • Creating indexes naively • Executing non-indexable queries • Rejecting indexes because of overhead
  • 6. CREATE TABLE Posts ( PostId SERIAL PRIMARY KEY, CreationDate DATE NOT NULL, Title VARCHAR(80) NOT NULL, Body TEXT NOT NULL, Score INT );
  • 7. CREATE TABLE Posts ( PostId SERIAL PRIMARY KEY, CreationDate DATE NOT NULL, Title VARCHAR(80) NOT NULL, Body TEXT NOT NULL, Score INT, INDEX (PostId) ); redundant index, already in PK
  • 8. CREATE TABLE Posts ( PostId SERIAL PRIMARY KEY, CreationDate DATE NOT NULL, Title VARCHAR(80) NOT NULL, Body TEXT NOT NULL, Score INT, INDEX (Title) ); bulky index
  • 9. CREATE TABLE Posts ( PostId SERIAL PRIMARY KEY, CreationDate DATE NOT NULL, Title VARCHAR(80) NOT NULL, Body TEXT NOT NULL, Score INT, INDEX (Score) ); unnecessary index, we may never query on score
  • 10. CREATE TABLE Posts ( PostId SERIAL PRIMARY KEY, CreationDate DATE NOT NULL, Title VARCHAR(80) NOT NULL, Body TEXT NOT NULL, Score INT, INDEX (Score, CreationDate, Title) ); unnecessary composite index
  • 11. SELECT * FROM Posts WHERE Title LIKE ‘%crash%’ non-leftmost string match
  • 12. Telephone book analogy: • Easy to search for Dean Thomas: uses index to match SELECT * FROM TelephoneBook WHERE full_name LIKE ‘Thomas, %’ • Hard to search for Thomas Riddle: requires full table scan SELECT * FROM TelephoneBook WHERE full_name LIKE ‘%, Thomas’
  • 13. SELECT * FROM Posts WHERE MONTH(CreationDate) = 4 function applied to column
  • 14. SELECT * FROM Users WHERE LastName = ‘Thomas’ OR FirstName = ‘Thomas’ just like searching for first_name
  • 15. SELECT * FROM Users ORDER BY FirstName, LastName non-leftmost composite key match
  • 16. the benefit quickly justifies the overhead O(n) table scan O(log n) index scan
  • 17. Relational Index data modeling optimization is derived is derived from data from queries
  • 18. MENTOR Your Indexes
  • 19. Measure Explain Nominate Test Optimize Repair
  • 20. Measure Explain Nominate Test Optimize Repair
  • 21. • Profile your code to identify your biggest performance costs. • MySQL: PROFILER • Oracle: TKPROF or Trace Analyzer • Application-level profiling
  • 22. Measure Explain Nominate Test Optimize Repair
  • 23. • Analyze the database’s optimization plan for costly queries. • Identify queries that don’t use indexes.
  • 24. • MySQL: EXPLAIN Query • “Explain Output Format” http://dev.mysql.com/doc/refman/5.5/en/ explain-output.html
  • 25. • Oracle: EXPLAIN PLAN Query • “Understanding Explain Plan” http://www.orafaq.com/node/1420
  • 26. Measure Explain Nominate Test Optimize Repair
  • 27. • Which queries need optimization? • Frequently used queries • Very slow queries • Reports
  • 28. • Which column(s) need indexes? • WHERE conditions • JOIN conditions • ORDER BY criteria • MIN() / MAX()
  • 29. • Automatic tools for nominating indexes: • MySQL Enterprise Query Analyzer • Oracle Automatic SQL Tuning Advisor
  • 30. Measure Explain Nominate Test Optimize Repair
  • 31. • After creating index, measure your high- priority queries again. • Confirm that the new index made a difference to these queries. • Impress your boss/client! “The new index gave us a 127% performance improvement!”
  • 32. Measure Explain Nominate Test Optimize Repair
  • 33. • Indexes are compact, frequently-used data structures. • Try to cache indexes in memory.
  • 34. • Cache indexes in MySQL/InnoDB: • Increase innodb_buffer_pool_size • Used for both data and indexes • Cache indexes in MySQL/MyISAM: • Increase key_buffer_size • LOAD INDEX INTO CACHE TableName [INDEX IndexName];
  • 35. • Cache indexes in Oracle: ALTER SYSTEM SET DB_32K_CACHE_SIZE = 100m; CREATE TABLESPACE INDEX_TS_32K BLOCKSIZE 32K; ALTER INDEX IndexName REBUILD ONLINE TABLESPACE INDEX_TS_32K; http://www.dba-oracle.com/art_so_optimizer_index_caching.htm
  • 36. Measure Explain Nominate Test Optimize Repair
  • 37. • Indexes require periodic maintenance. • Like a filesystem requires periodic defragmentation.
  • 38. • Analyze / rebuild indexes in MySQL: • ANALYZE TABLE TableName • OPTIMIZE TABLE TableName
  • 39. • Analyze / rebuild indexes in Oracle: • ANALYZE INDEX IndexName • ALTER INDEX IndexName REBUILD ...
  • 40. 1. Know Your Data. 2. Know Your Queries. 3. MENTOR Your Indexes.
  • 41. SQL Antipatterns: Avoiding the Pitfalls of Database Programming http://www.pragprog.com/titles/bksqla/
  • 42. Copyright 2010 Bill Karwin www.slideshare.net/billkarwin Released under a Creative Commons 3.0 License: http://creativecommons.org/licenses/by-nc-nd/3.0/ You are free to share - to copy, distribute and transmit this work, under the following conditions: Attribution. Noncommercial. No Derivative Works. You must attribute this You may not use this work You may not alter, work to Bill Karwin. for commercial purposes. transform, or build upon this work.