SlideShare a Scribd company logo
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.

More Related Content

What's hot

MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
MYXPLAIN
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index TuningManikanda kumar
 
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015PostgreSQL-Consulting
 
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
Jaime Crespo
 
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
Hemant Kumar Singh
 
How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, ReallyMYXPLAIN
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain Explained
Jeremy Coates
 
MySQL_SQL_Tunning_v0.1.3.docx
MySQL_SQL_Tunning_v0.1.3.docxMySQL_SQL_Tunning_v0.1.3.docx
MySQL_SQL_Tunning_v0.1.3.docx
NeoClova
 
PostgreSQL Extensions: A deeper look
PostgreSQL Extensions:  A deeper lookPostgreSQL Extensions:  A deeper look
PostgreSQL Extensions: A deeper look
Jignesh Shah
 
PyCon DE 2013 - Table Partitioning with Django
PyCon DE 2013 - Table Partitioning with DjangoPyCon DE 2013 - Table Partitioning with Django
PyCon DE 2013 - Table Partitioning with Django
Max Tepkeev
 
Indexing the MySQL Index: Key to performance tuning
Indexing the MySQL Index: Key to performance tuningIndexing the MySQL Index: Key to performance tuning
Indexing the MySQL Index: Key to performance tuningOSSCube
 
InnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick FiguresInnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick Figures
Karwin Software Solutions LLC
 
Recursive Query Throwdown
Recursive Query ThrowdownRecursive Query Throwdown
Recursive Query Throwdown
Karwin Software Solutions LLC
 
Advanced Postgres Monitoring
Advanced Postgres MonitoringAdvanced Postgres Monitoring
Advanced Postgres MonitoringDenish Patel
 
Introduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineIntroduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the Engine
Brent Ozar
 
Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
oracle content
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
Karwin Software Solutions LLC
 
More mastering the art of indexing
More mastering the art of indexingMore mastering the art of indexing
More mastering the art of indexing
Yoshinori Matsunobu
 
The MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer TraceThe MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer Trace
oysteing
 

What's hot (20)

MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
 
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 Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
 
How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain Explained
 
MySQL_SQL_Tunning_v0.1.3.docx
MySQL_SQL_Tunning_v0.1.3.docxMySQL_SQL_Tunning_v0.1.3.docx
MySQL_SQL_Tunning_v0.1.3.docx
 
PostgreSQL Extensions: A deeper look
PostgreSQL Extensions:  A deeper lookPostgreSQL Extensions:  A deeper look
PostgreSQL Extensions: A deeper look
 
PyCon DE 2013 - Table Partitioning with Django
PyCon DE 2013 - Table Partitioning with DjangoPyCon DE 2013 - Table Partitioning with Django
PyCon DE 2013 - Table Partitioning with Django
 
Indexing the MySQL Index: Key to performance tuning
Indexing the MySQL Index: Key to performance tuningIndexing the MySQL Index: Key to performance tuning
Indexing the MySQL Index: Key to performance tuning
 
InnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick FiguresInnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick Figures
 
Recursive Query Throwdown
Recursive Query ThrowdownRecursive Query Throwdown
Recursive Query Throwdown
 
Advanced Postgres Monitoring
Advanced Postgres MonitoringAdvanced Postgres Monitoring
Advanced Postgres Monitoring
 
Survey of Percona Toolkit
Survey of Percona ToolkitSurvey of Percona Toolkit
Survey of Percona Toolkit
 
Introduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineIntroduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the Engine
 
Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
 
More mastering the art of indexing
More mastering the art of indexingMore mastering the art of indexing
More mastering the art of indexing
 
The MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer TraceThe MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer Trace
 

Viewers also liked

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
Karwin Software Solutions LLC
 
Schemadoc
SchemadocSchemadoc
Requirements the Last Bottleneck
Requirements the Last BottleneckRequirements the Last Bottleneck
Requirements the Last Bottleneck
Karwin Software Solutions LLC
 
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
Karwin Software Solutions LLC
 
Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
Karwin Software Solutions LLC
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
Karwin Software Solutions LLC
 
Practical Object Oriented Models In Sql
Practical Object Oriented Models In SqlPractical Object Oriented Models In Sql
Practical Object Oriented Models In Sql
Karwin Software Solutions LLC
 
Hierarchical data models in Relational Databases
Hierarchical data models in Relational DatabasesHierarchical data models in Relational Databases
Hierarchical data models in Relational Databasesnavicorevn
 
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
Lorenzo Alberton
 

Viewers also liked (11)

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
 
Schemadoc
SchemadocSchemadoc
Schemadoc
 
Requirements the Last Bottleneck
Requirements the Last BottleneckRequirements the Last Bottleneck
Requirements the Last Bottleneck
 
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 Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
 
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
 
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
 

Similar to Mentor Your Indexes

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
Ike Ellis
 
SQL
SQLSQL
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
Carsten Czarski
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
ColdFusionConference
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
Joel Brewer
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
MengChun Lam
 
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
Kevin Kline
 
The perfect index
The perfect indexThe perfect index
The perfect index
ArthurDaniels4
 
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
Embarcadero Technologies
 
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
Barry Jones
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
Reuven Lerner
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimizationBaohua Cai
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
086ChintanPatel1
 
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
Mukesh Tilokani
 
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
Michael Rys
 
Access 04
Access 04Access 04
Access 04
Alexander Babich
 
•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
 
High Performance Rails with MySQL
High Performance Rails with MySQLHigh Performance Rails with MySQL
High Performance Rails with MySQL
Jervin Real
 
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
Michael Rys
 

Similar to 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
 

Recently uploaded

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 

Recently uploaded (20)

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 

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.