SlideShare uma empresa Scribd logo
1 de 60
Are You Getting the Best Out of Your
MySQL Indexes?

http://bit.ly/mysqlindex

Sheeri Cabral

Senior DB Admin/Architect, Mozilla
@sheeri www.sheeri.com
Northeast PHP 2012
What is an index?
KEY vs. INDEX
KEY = KEY CONSTRAINT
PRIMARY, UNIQUE, FOREIGN
Everything else is an “implementation detail”
The plural of INDEX is....?
http://www.sheldoncomics.com/strips/sd120626.png
More Lingo
Simple
(last_name)
Composite
(last_name,first_name)
Data Structures
B-TREE for InnoDB, MyISAM

Can be HASH for MEMORY
B-tree

(Image from Wikipedia)
B-trees Are Excellent For...
A range search - foo BETWEEN 5 AND 10
One equality match - foo=11
A few equality matches - foo IN (5,10,11)
- How is it done?

(Image from Wikipedia)
Composite Indexes
Index on (last_name,first_name)
Used find words beginning with “g” (last_name)
Not used to find words ending with “g” (first_name)
OK to have (last_name,first_name) and (first_name)
Like a dictionary index

(Image from Wikipedia)
MySQL Uses Indexes For...
Matching a WHERE clause
Eliminating rows
Resolving MIN() or MAX() values
Eliminating sorting
Helping with grouping
Everything – Covering index

(Image from Wikipedia)
MySQL Ignores Indexes For...
Functions
DATE(ts_col)='2012_08_11'
JOINs if the fields are not similar
date_col='2012_08_11 00:00:00'

(Image from Wikipedia)
MySQL Ignores Indexes For...
Queries with multiple WHERE clauses not all
using the same index joined by AND

For example, imagine a test table, with an index
on (last_name,first_name)
test,(last_name,first_name)
Queries that use the index:
SELECT * FROM test WHERE last_name='Cabral';
SELECT * FROM test
WHERE last_name='Cabral' AND first_name='Sheeri';
SELECT * FROM test
WHERE last_name='Cabral'
AND (first_name='Tony' OR first_name='Antonio');
test,(last_name,first_name)
Queries that DO NOT use the index:
SELECT * FROM test WHERE first_name='Sheeri';
SELECT * FROM test
WHERE last_name='Cabral' OR first_name='Sheeri';
MySQL Ignores Indexes For...
“Too much” data, just do a full table scan
6 lookups vs. walking the 10-node tree

(Image from Wikipedia)

(Image from Wikipedia)
“Too Much” Data
“Too much” is about 15-25%
How is that calculated?
Metadata!
Exact in MyISAM (writes are table-locking)
Approximate in InnoDB
“value group”
Average value group size
Used for approx rows for rows read, joins
Average Value Group Size
Body parts: 2 eyes, 10 fingers
Average value group size = 6
Not perfect optimization for either eyes or fingers
Estimate is longer than reality for eyes
Estimate is shorter than reality for fingers
Remember the “too much data” feature/problem
Composite Index
Like a sorted array
Can be ASC or DESC
But not ASC,DESC or DESC, ASC

(Image from Wikipedia)
NULL and Equality
NULL = x is not true for ANY value of x
NULL = NULL is not true
If a referenced value in an equality is NULL
MySQL immediately returns false
NULL-safe operator is <=>
Remember the “too much data” feature/problem
NULL and Value Groups
innodb_stats_method, myisam_stats_method
nulls_equal (default)
nulls_unequal
nulls_ignored
PRIMARY Keys
Row identifiers
Cannot be NULL
InnoDB orders on disk in PRIMARY KEY order
UNIQUE Keys
Row identifiers
Can be NULL
Both PRIMARY/UNIQUE can be composite index
FOREIGN Keys
Parent/child relationship
customer->id vs. payment->customer_id
Cascading update/deletes
Numeric vs. Human-readable
customer_id

status_id

status_id

status

121

1

1

free

122

2

2

paid

125

1

3

disabled

customer_id

status

status

121

free

free

122

paid

paid

125

free

disabled
Prefix Indexing
For strings
Up to 767 bytes on InnoDB, 1000 on MyISAM
Beware of charset!
Composite Indexes
Index on (last_name,first_name,middle_name)
Functions as:
(last_name,first_name,middle_name)
(last_name,first_name)
(last_name)
FULLTEXT Indexing
No prefix indexing
Only for CHAR, VARCHAR, TEXT
No prefix indexing
MyISAM only
Knowing All This...
Use EXPLAIN
If you are not getting the index you expect
Check your expectations
Or file a bug: http://bugs.mysql.com
Questions? Comments?
OurSQL Podcast
www.oursql.com
MySQL Administrator's Bible
- tinyurl.com/mysqlbible
kimtag.com/mysql
planet.mysql.com
Are You Getting the Best Out of Your
MySQL Indexes?

http://bit.ly/mysqlindex

Sheeri Cabral

Senior DB Admin/Architect, Mozilla
@sheeri www.sheeri.com
Northeast PHP 2012
What is an index?
KEY vs. INDEX
KEY = KEY CONSTRAINT
PRIMARY, UNIQUE, FOREIGN
Everything else is an “implementation detail”
The plural of INDEX is....?
http://www.sheldoncomics.com/strips/sd120626.png
More Lingo
Simple
(last_name)
Composite
(last_name,first_name)
Data Structures
B-TREE for InnoDB, MyISAM

Can be HASH for MEMORY
B-tree

(Image from Wikipedia)
B-trees Are Excellent For...
A range search - foo BETWEEN 5 AND 10
One equality match - foo=11
A few equality matches - foo IN (5,10,11)
- How is it done?

(Image from Wikipedia)
Composite Indexes
Index on (last_name,first_name)
Used find words beginning with “g” (last_name)
Not used to find words ending with “g” (first_name)
OK to have (last_name,first_name) and (first_name)
Like a dictionary index

(Image from Wikipedia)
MySQL Uses Indexes For...
Matching a WHERE clause
Eliminating rows
Resolving MIN() or MAX() values
Eliminating sorting
Helping with grouping
Everything – Covering index

(Image from Wikipedia)
MySQL Ignores Indexes For...
Functions
DATE(ts_col)='2012_08_11'
JOINs if the fields are not similar
date_col='2012_08_11 00:00:00'

(Image from Wikipedia)
MySQL Ignores Indexes For...
Queries with multiple WHERE clauses not all
using the same index joined by AND

For example, imagine a test table, with an index
on (last_name,first_name)
test,(last_name,first_name)
Queries that use the index:
SELECT * FROM test WHERE last_name='Cabral';
SELECT * FROM test
WHERE last_name='Cabral' AND first_name='Sheeri';
SELECT * FROM test
WHERE last_name='Cabral'
AND (first_name='Tony' OR first_name='Antonio');
test,(last_name,first_name)
Queries that DO NOT use the index:
SELECT * FROM test WHERE first_name='Sheeri';
SELECT * FROM test
WHERE last_name='Cabral' OR first_name='Sheeri';
MySQL Ignores Indexes For...
“Too much” data, just do a full table scan
6 lookups vs. walking the 10-node tree

(Image from Wikipedia)

(Image from Wikipedia)
“Too Much” Data
“Too much” is about 15-25%
How is that calculated?
Metadata!
Exact in MyISAM (writes are table-locking)
Approximate in InnoDB
“value group”
Average value group size
Used for approx rows for rows read, joins
Average Value Group Size
Body parts: 2 eyes, 10 fingers
Average value group size = 6
Not perfect optimization for either eyes or fingers
Estimate is longer than reality for eyes
Estimate is shorter than reality for fingers
Remember the “too much data” feature/problem
Composite Index
Like a sorted array
Can be ASC or DESC
But not ASC,DESC or DESC, ASC

(Image from Wikipedia)
NULL and Equality
NULL = x is not true for ANY value of x
NULL = NULL is not true
If a referenced value in an equality is NULL
MySQL immediately returns false
NULL-safe operator is <=>
Remember the “too much data” feature/problem
NULL and Value Groups
innodb_stats_method, myisam_stats_method
nulls_equal (default)
nulls_unequal
nulls_ignored
PRIMARY Keys
Row identifiers
Cannot be NULL
InnoDB orders on disk in PRIMARY KEY order
UNIQUE Keys
Row identifiers
Can be NULL
Both PRIMARY/UNIQUE can be composite index
FOREIGN Keys
Parent/child relationship
customer->id vs. payment->customer_id
Cascading update/deletes
Numeric vs. Human-readable
customer_id

status_id

status_id

status

121

1

1

122

2

2

paid

125

1

3

disabled

customer_id

status

free

status

121

free

free

122

paid

paid

125

free

disabled
Prefix Indexing
For strings
Up to 767 bytes on InnoDB, 1000 on MyISAM
Beware of charset!
Composite Indexes
Index on (last_name,first_name,middle_name)
Functions as:
(last_name,first_name,middle_name)
(last_name,first_name)
(last_name)
FULLTEXT Indexing
No prefix indexing
Only for CHAR, VARCHAR, TEXT
No prefix indexing
MyISAM only
Knowing All This...
Use EXPLAIN
If you are not getting the index you expect
Check your expectations
Or file a bug: http://bugs.mysql.com
Questions? Comments?
OurSQL Podcast
www.oursql.com
MySQL Administrator's Bible
- tinyurl.com/mysqlbible
kimtag.com/mysql
planet.mysql.com

Mais conteúdo relacionado

Destaque (13)

Eesws
EeswsEesws
Eesws
 
Presentacion
PresentacionPresentacion
Presentacion
 
Entrepreneurs and their firms
Entrepreneurs and their firmsEntrepreneurs and their firms
Entrepreneurs and their firms
 
ATS Overview
ATS OverviewATS Overview
ATS Overview
 
Mensaje del cielo
Mensaje del cieloMensaje del cielo
Mensaje del cielo
 
Neve na finlandia
Neve na finlandiaNeve na finlandia
Neve na finlandia
 
Números *** http://andreaebert.tumblr.com/ ***
Números  ***   http://andreaebert.tumblr.com/    ***Números  ***   http://andreaebert.tumblr.com/    ***
Números *** http://andreaebert.tumblr.com/ ***
 
اذاعة القدرات
اذاعة القدراتاذاعة القدرات
اذاعة القدرات
 
tutorial mengambar doraemon dengan mudah
 tutorial mengambar doraemon dengan mudah tutorial mengambar doraemon dengan mudah
tutorial mengambar doraemon dengan mudah
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
 
Need for Speed: MySQL Indexing
Need for Speed: MySQL IndexingNeed for Speed: MySQL Indexing
Need for Speed: MySQL Indexing
 
Advanced Query Optimizer Tuning and Analysis
Advanced Query Optimizer Tuning and AnalysisAdvanced Query Optimizer Tuning and Analysis
Advanced Query Optimizer Tuning and Analysis
 
Query Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New TricksQuery Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New Tricks
 

Semelhante a Are You Getting the Best of your MySQL Indexes

Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and Answers
Vineet Kumar Saini
 
SQA server performance tuning
SQA server performance tuningSQA server performance tuning
SQA server performance tuning
Duy Tan Geek
 
Web app development_php_04
Web app development_php_04Web app development_php_04
Web app development_php_04
Hassen Poreya
 

Semelhante a Are You Getting the Best of your MySQL Indexes (20)

Automating With Excel An Object Oriented Approach
Automating  With  Excel    An  Object  Oriented  ApproachAutomating  With  Excel    An  Object  Oriented  Approach
Automating With Excel An Object Oriented Approach
 
Pig - Analyzing data sets
Pig - Analyzing data setsPig - Analyzing data sets
Pig - Analyzing data sets
 
Access
AccessAccess
Access
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
MySQL Document Store for Modern Applications
MySQL Document Store for Modern ApplicationsMySQL Document Store for Modern Applications
MySQL Document Store for Modern Applications
 
Making Django and NoSQL Play Nice
Making Django and NoSQL Play NiceMaking Django and NoSQL Play Nice
Making Django and NoSQL Play Nice
 
The Challenges of SQL on Hadoop
The Challenges of SQL on HadoopThe Challenges of SQL on Hadoop
The Challenges of SQL on Hadoop
 
A "M"ind Bending Experience. Power Query for Excel and Beyond.
A "M"ind Bending Experience. Power Query for Excel and Beyond.A "M"ind Bending Experience. Power Query for Excel and Beyond.
A "M"ind Bending Experience. Power Query for Excel and Beyond.
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and Answers
 
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
Fnt Software Solutions Pvt Ltd Placement Papers - PHP TechnologyFnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
 
Performance By Design
Performance By DesignPerformance By Design
Performance By Design
 
Sql
SqlSql
Sql
 
SQA server performance tuning
SQA server performance tuningSQA server performance tuning
SQA server performance tuning
 
MongoDB performance
MongoDB performanceMongoDB performance
MongoDB performance
 
Raven db byexample
Raven db byexampleRaven db byexample
Raven db byexample
 
AnzoGraph DB - SPARQL 101
AnzoGraph DB - SPARQL 101AnzoGraph DB - SPARQL 101
AnzoGraph DB - SPARQL 101
 
Automating SolidWorks with Excel
Automating SolidWorks with ExcelAutomating SolidWorks with Excel
Automating SolidWorks with Excel
 
20180420 hk-the powerofmysql8
20180420 hk-the powerofmysql820180420 hk-the powerofmysql8
20180420 hk-the powerofmysql8
 
Web app development_php_04
Web app development_php_04Web app development_php_04
Web app development_php_04
 
Some NoSQL
Some NoSQLSome NoSQL
Some NoSQL
 

Mais de MYXPLAIN

MySQL 5.6 Performance
MySQL 5.6 PerformanceMySQL 5.6 Performance
MySQL 5.6 Performance
MYXPLAIN
 
MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6
MYXPLAIN
 
56 Query Optimization
56 Query Optimization56 Query Optimization
56 Query Optimization
MYXPLAIN
 
Tools and Techniques for Index Design
Tools and Techniques for Index DesignTools and Techniques for Index Design
Tools and Techniques for Index Design
MYXPLAIN
 
Powerful Explain in MySQL 5.6
Powerful Explain in MySQL 5.6Powerful Explain in MySQL 5.6
Powerful Explain in MySQL 5.6
MYXPLAIN
 
Optimizing Queries with Explain
Optimizing Queries with ExplainOptimizing Queries with Explain
Optimizing Queries with Explain
MYXPLAIN
 
The Power of MySQL Explain
The Power of MySQL ExplainThe Power of MySQL Explain
The Power of MySQL Explain
MYXPLAIN
 
Improving Performance with Better Indexes
Improving Performance with Better IndexesImproving Performance with Better Indexes
Improving Performance with Better Indexes
MYXPLAIN
 
Explaining the MySQL Explain
Explaining the MySQL ExplainExplaining the MySQL Explain
Explaining the MySQL Explain
MYXPLAIN
 
Covering indexes
Covering indexesCovering indexes
Covering indexes
MYXPLAIN
 
MySQL Optimizer Overview
MySQL Optimizer OverviewMySQL Optimizer Overview
MySQL Optimizer Overview
MYXPLAIN
 
Advanced query optimization
Advanced query optimizationAdvanced query optimization
Advanced query optimization
MYXPLAIN
 

Mais de MYXPLAIN (12)

MySQL 5.6 Performance
MySQL 5.6 PerformanceMySQL 5.6 Performance
MySQL 5.6 Performance
 
MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6
 
56 Query Optimization
56 Query Optimization56 Query Optimization
56 Query Optimization
 
Tools and Techniques for Index Design
Tools and Techniques for Index DesignTools and Techniques for Index Design
Tools and Techniques for Index Design
 
Powerful Explain in MySQL 5.6
Powerful Explain in MySQL 5.6Powerful Explain in MySQL 5.6
Powerful Explain in MySQL 5.6
 
Optimizing Queries with Explain
Optimizing Queries with ExplainOptimizing Queries with Explain
Optimizing Queries with Explain
 
The Power of MySQL Explain
The Power of MySQL ExplainThe Power of MySQL Explain
The Power of MySQL Explain
 
Improving Performance with Better Indexes
Improving Performance with Better IndexesImproving Performance with Better Indexes
Improving Performance with Better Indexes
 
Explaining the MySQL Explain
Explaining the MySQL ExplainExplaining the MySQL Explain
Explaining the MySQL Explain
 
Covering indexes
Covering indexesCovering indexes
Covering indexes
 
MySQL Optimizer Overview
MySQL Optimizer OverviewMySQL Optimizer Overview
MySQL Optimizer Overview
 
Advanced query optimization
Advanced query optimizationAdvanced query optimization
Advanced query optimization
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

Are You Getting the Best of your MySQL Indexes