SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
By: Jehad Keriaki
DBA
MySQL: Indexing for Better Performance1
MySQL: Indexing for Better Performance
Jehad Keriaki 2014
What is an Index
 Data structure to improve the speed of data
retrieval from DBs.
MySQL: Indexing for Better Performance2
Jehad Keriaki 2014
Why Would We Use Indexes
 Speed, Speed, and Speed
 Constraints (Uniqueness)
 IO Optimization
 MAX, MIN
 Sorting, Grouping
MySQL: Indexing for Better Performance3
Jehad Keriaki 2014
Index Types
 Primary Key (PK), Unique, Key
 Primary Key vs Unique
 Unique can be NULL
 InnoDB is clustered based on PK
MySQL: Indexing for Better Performance4
Jehad Keriaki 2014
Types (Algorithm)
 B-Tree, R-Tree, Hash, Full text
 R-Tree: Geo-spatial
 Hash: Memory only, fast for equality, whole key is used,
no range
 Full-text:
 For MyISAM, and as of 5.6 for InnoDB too.
 SELECT * WHERE MATCH(description) AGAINST ('toshiba')
 boolean , with query expansion, stop words, short words,
50% rule
 A better choice would be to use a search server like Sphinx
MySQL: Indexing for Better Performance5
Jehad Keriaki 2014
Types (Algorithm) [cont'd]
 B-Tree:
 For comparison operations (<>=..etc)
 Range (Between)
 Like, which is a special case of range when used with %
 It is the DEFAULT in MySQL
 In B-Tree, data are stored in the leaf nodes
MySQL: Indexing for Better Performance6
Jehad Keriaki 2014
Types (Structure)
 One column
 Multi-Column [composite]
 Partial [prefix]
 Any one of them can be "Covering Index", except
'partial'
MySQL: Indexing for Better Performance7
Jehad Keriaki 2014
What Indexes to Create?
 PK is a must
 Best to be unsigned [smallest int] auto increment
 PK and InnoDB (Clustered)
 InnoDB tables are clustered based on PKs
 Each secondary index has the PK in it. example:
INDEX(name) is in fact (name, id)
 AVOID long PKs. Why?
 AVOID md5(), uuid(), etc.
MySQL: Indexing for Better Performance8
Jehad Keriaki 2014
MyISAM and InnoDB
 In MyISAM:
 Index entry tells the physical offset of the row in the
data file
 In InnoDB:
 PK index has the data. Secondary indexes store PK as
a pointer. Key on field F is (F, PK) - good for sorting
and covering index
MySQL: Indexing for Better Performance9
Jehad Keriaki 2014
Cardinality and Selectivity
 Cardinality: Number of distinct values
 Selectivity: Cardinality / total number of rows
 What values are better
 Optimize  Stats Update
MySQL: Indexing for Better Performance10
Jehad Keriaki 2014
One Column Index
 This index is on one column only
 Query example:
 SELECT * FROM employee WHERE first_name LIKE 'stephane';
 Index solution:
 ALTER TABLE employee ADD INDEX (first_name);
 Notes:
 Index the first n char of the char/varchar/text fields
 Do not use a function. i.e.
 WHERE md5(field)='1bc29b36f623ba82aaf6724fd3b16718'
MySQL: Indexing for Better Performance11
Jehad Keriaki 2014
Multi Column Index
 What is it:
 Index that involves more than one column.
 Higher cardinality field goes first, with exceptions.
 What 'left most' term is. [INDEX (A, B, C)]
 Query example:
 SELECT * FROM employee
WHERE department = 5 AND last_name LIKE 'tran';
 Index solution:
 ALTER TABLE employee ADD INDEX (last_name, department);
{WHY NOT (department, last_name)??}
MySQL: Indexing for Better Performance12
Jehad Keriaki 2014
Multi Column Index [Cont’d]
 Query example:
 SELECT * FROM employee WHERE department = 5 and
hiring_date>='2014-01-01';
 Index solution:
 ALTER TABLE employee ADD INDEX (department, hiring_date);
 Notes
 Should it be (hiring_date, department)? Is this an
exception?
 Order of columns IS important
 WILL NOT USE THE INDEX:
 SELECT * FROM employee WHERE hiring_date>='2014-01-01';
MySQL: Indexing for Better Performance13
Jehad Keriaki 2014
Partial Index
 What is it: Index on the first n char of a field.
 Query example:
 email: varchar(255);
 SELECT * FROM users WHERE email like 'richardmelo@yahoo.com';
 Index solution
 ALTER TABLE users ADD INDEX (email(12));
vs
 ALTER TABLE users ADD INDEX (email);
 Notes:
 Save space, efficient writing, same performance
 SELECT COUNT(DISTINCT(LEFT(field, 20))) FROM table
 85% threshold? 90% maybe?
MySQL: Indexing for Better Performance14
Jehad Keriaki 2014
Joins and Indexes
 Linking two or more tables to get related rows
 Query example:
 SELECT employee.first_name, employee.last_name,
FROM department
INNER JOIN employee ON departmant.id = employee.department
WHERE department.location='MTL';
 Index solution:
 ALTER TABLE department ADD INDEX (location);
 ALTER TABLE employee ADD INDEX (department);
 Notes: The join could be on a non-indexed field on
department, but an index has to exist on "employee's field"
MySQL: Indexing for Better Performance15
Jehad Keriaki 2014
Multiple Indexes OR Multi-Col Index
 What is it:
 ALTER TABLE ADD INDEX(field1), ADD INDEX(field2)
 ALTER TABLE ADD INDEX(field1, field2)
 Query example:
 WHERE field1=1 OR field2=2 [multiple indexes]
 WHERE field1=1 AND field2=2 [multi-col index]
MySQL: Indexing for Better Performance16
Jehad Keriaki 2014
Covering Index
 When the index has the required data, no need to
read data from table’s data!
 Example:
 employee(id, first_name, last_name, email, phone, hiring_date)
 SELECT email FROM employee WHERE phone='123456789';
 ALTER TABLE employee ADD INDEX(phone, email);
 min(), max() functions use the index only.
MySQL: Indexing for Better Performance17
Jehad Keriaki 2014
Covering Index - Note
 only in InnoDB:
 myindex(col1,col2)
 SELECT col1 FROM table1 WHERE col2 = 200 <<-- will use index
 SELECT * FROM table1 where col2 = 200 <<-- will NOT use index.
MySQL: Indexing for Better Performance18
Jehad Keriaki 2014
ICP (Index Condition Pushdown) [5.6]
 Lets the optimizer check in the index instead of checking in the
table's data.
 employee(id, first_name, last_name, department, phone, email, address)
 INDEX(department, email)
 SELECT * FROM employee
WHERE department=5
AND email LIKE '%@beta.example%'
[and address LIKE '%montreal%'];
 Instead of stopping at department and then use where to check for
email in the table's data, it will actually check in the index to see if
the 2nd condition is satisfied, and then if yes, it will fetch the data
from the table
MySQL: Indexing for Better Performance19
Jehad Keriaki 2014
Using Index for Sorting
 ORDER BY x  (index on x)
 WHERE x ORDER BY y  (index on x, y)
 WHERE x ORDER BY x DESC, y DESC (index on x, y)
 WHERE x ORDER BY x ASC, y DESC  (Can't use index)
MySQL: Indexing for Better Performance20
Jehad Keriaki 2014
Exceptions
 E.g. Date index with other less cardinal field.
 Status or Gender special cases
MySQL: Indexing for Better Performance21
Jehad Keriaki 2014
Overhead of indexing
 IO: Each DML operation will modify the indexes
 Disk space
 More indexes => Higher possibility of deadlock
MySQL: Indexing for Better Performance22
Jehad Keriaki 2014
ABOUT EXPLAIN
 It lets us know the plan of query execution
 What index would be used, if any
 Rows to be scanned
MySQL: Indexing for Better Performance23
MySQL: Indexing for Better Performance24
QUESTIONS & EXAMPLES
MySQL: Indexing for Better Performance25
mysql> explain select * from md_table where id=50000G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: md_table
type: const
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: const
rows: 1
Extra:
1 row in set (0.00 sec)
mysql> explain select id from md_table where id=50000G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: md_table
type: const
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: const
rows: 1
Extra: Using index
1 row in set (0.00 sec)
MySQL: Indexing for Better Performance26
mysql> explain select id from md_table where hashed_id='1017bfd4673955ffee4641ad3d481b1c'G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: md_table
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 100000
Extra: Using where
1 row in set (0.00 sec)
mysql> alter table md_table add index (hashed_id(15));
Query OK, 100000 rows affected (0.77 sec)
Records: 100000 Duplicates: 0 Warnings: 0
mysql> explain select id from md_table where hashed_id='1017bfd4673955ffee4641ad3d481b1c'G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: md_table
type: ref
possible_keys: hashed_id
key: hashed_id
key_len: 46
ref: const
rows: 1
Extra: Using where
1 row in set (0.01 sec)

Weitere ähnliche Inhalte

Was ist angesagt?

MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index TuningManikanda kumar
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexingMahabubur Rahaman
 
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.6MYXPLAIN
 
MySQL Optimizer Overview
MySQL Optimizer OverviewMySQL Optimizer Overview
MySQL Optimizer OverviewOlav Sandstå
 
Database index by Reema Gajjar
Database index by Reema GajjarDatabase index by Reema Gajjar
Database index by Reema GajjarReema Gajjar
 
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 Performanceoysteing
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query OptimizationBrian Gallagher
 
Why Use EXPLAIN FORMAT=JSON?
 Why Use EXPLAIN FORMAT=JSON?  Why Use EXPLAIN FORMAT=JSON?
Why Use EXPLAIN FORMAT=JSON? Sveta Smirnova
 
More mastering the art of indexing
More mastering the art of indexingMore mastering the art of indexing
More mastering the art of indexingYoshinori Matsunobu
 
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 Performanceoysteing
 
MySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZEMySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZENorvald Ryeng
 
MySQL_MariaDB-성능개선-202201.pptx
MySQL_MariaDB-성능개선-202201.pptxMySQL_MariaDB-성능개선-202201.pptx
MySQL_MariaDB-성능개선-202201.pptxNeoClova
 
Postgresql stored procedure
Postgresql stored procedurePostgresql stored procedure
Postgresql stored procedureJong Woo Rhee
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimizationBaohua Cai
 

Was ist angesagt? (20)

Index in sql server
Index in sql serverIndex in sql server
Index in sql server
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 
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
 
MySQL Optimizer Overview
MySQL Optimizer OverviewMySQL Optimizer Overview
MySQL Optimizer Overview
 
How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
 
Indexing
IndexingIndexing
Indexing
 
MySQL JOIN & UNION
MySQL JOIN & UNIONMySQL JOIN & UNION
MySQL JOIN & UNION
 
Database index by Reema Gajjar
Database index by Reema GajjarDatabase index by Reema Gajjar
Database index by Reema Gajjar
 
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
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query Optimization
 
Why Use EXPLAIN FORMAT=JSON?
 Why Use EXPLAIN FORMAT=JSON?  Why Use EXPLAIN FORMAT=JSON?
Why Use EXPLAIN FORMAT=JSON?
 
More mastering the art of indexing
More mastering the art of indexingMore mastering the art of indexing
More mastering the art of indexing
 
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
 
MySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZEMySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZE
 
MySQL_MariaDB-성능개선-202201.pptx
MySQL_MariaDB-성능개선-202201.pptxMySQL_MariaDB-성능개선-202201.pptx
MySQL_MariaDB-성능개선-202201.pptx
 
Indexes in postgres
Indexes in postgresIndexes in postgres
Indexes in postgres
 
Postgresql stored procedure
Postgresql stored procedurePostgresql stored procedure
Postgresql stored procedure
 
Subqueries
SubqueriesSubqueries
Subqueries
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimization
 

Andere mochten auch

1 data types
1 data types1 data types
1 data typesRam Kedem
 
Database indexing framework
Database indexing frameworkDatabase indexing framework
Database indexing frameworkNitin Pande
 
Database indexing techniques
Database indexing techniquesDatabase indexing techniques
Database indexing techniquesahmadmughal0312
 
MySQL Scalability Mistakes - OTN
MySQL Scalability Mistakes - OTNMySQL Scalability Mistakes - OTN
MySQL Scalability Mistakes - OTNRonald Bradford
 
The History and Future of the MySQL ecosystem
The History and Future of the MySQL ecosystemThe History and Future of the MySQL ecosystem
The History and Future of the MySQL ecosystemRonald Bradford
 
10x Performance Improvements - A Case Study
10x Performance Improvements - A Case Study10x Performance Improvements - A Case Study
10x Performance Improvements - A Case StudyRonald Bradford
 
Lessons Learned Managing Large AWS Environments
Lessons Learned Managing Large AWS EnvironmentsLessons Learned Managing Large AWS Environments
Lessons Learned Managing Large AWS EnvironmentsRonald Bradford
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptFramgia Vietnam
 
The MySQL Performance Schema & New SYS Schema
The MySQL Performance Schema & New SYS SchemaThe MySQL Performance Schema & New SYS Schema
The MySQL Performance Schema & New SYS SchemaTed Wennmark
 
MySQL Performance - SydPHP October 2011
MySQL Performance - SydPHP October 2011MySQL Performance - SydPHP October 2011
MySQL Performance - SydPHP October 2011Graham Weldon
 
MySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance SchemaMySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance SchemaSveta Smirnova
 
Performance Schema in MySQL (Danil Zburivsky)
Performance Schema in MySQL (Danil Zburivsky)Performance Schema in MySQL (Danil Zburivsky)
Performance Schema in MySQL (Danil Zburivsky)Ontico
 

Andere mochten auch (20)

My MySQL SQL Presentation
My MySQL SQL PresentationMy MySQL SQL Presentation
My MySQL SQL Presentation
 
MySQL Views
MySQL ViewsMySQL Views
MySQL Views
 
Mysql Indexing
Mysql IndexingMysql Indexing
Mysql Indexing
 
1 data types
1 data types1 data types
1 data types
 
3 indexes
3 indexes3 indexes
3 indexes
 
Database indexing framework
Database indexing frameworkDatabase indexing framework
Database indexing framework
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Explain that explain
Explain that explainExplain that explain
Explain that explain
 
Database indexing techniques
Database indexing techniquesDatabase indexing techniques
Database indexing techniques
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Introduction to TFS 2013
Introduction to TFS 2013Introduction to TFS 2013
Introduction to TFS 2013
 
MySQL Scalability Mistakes - OTN
MySQL Scalability Mistakes - OTNMySQL Scalability Mistakes - OTN
MySQL Scalability Mistakes - OTN
 
The History and Future of the MySQL ecosystem
The History and Future of the MySQL ecosystemThe History and Future of the MySQL ecosystem
The History and Future of the MySQL ecosystem
 
10x Performance Improvements - A Case Study
10x Performance Improvements - A Case Study10x Performance Improvements - A Case Study
10x Performance Improvements - A Case Study
 
Lessons Learned Managing Large AWS Environments
Lessons Learned Managing Large AWS EnvironmentsLessons Learned Managing Large AWS Environments
Lessons Learned Managing Large AWS Environments
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - Thaipt
 
The MySQL Performance Schema & New SYS Schema
The MySQL Performance Schema & New SYS SchemaThe MySQL Performance Schema & New SYS Schema
The MySQL Performance Schema & New SYS Schema
 
MySQL Performance - SydPHP October 2011
MySQL Performance - SydPHP October 2011MySQL Performance - SydPHP October 2011
MySQL Performance - SydPHP October 2011
 
MySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance SchemaMySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance Schema
 
Performance Schema in MySQL (Danil Zburivsky)
Performance Schema in MySQL (Danil Zburivsky)Performance Schema in MySQL (Danil Zburivsky)
Performance Schema in MySQL (Danil Zburivsky)
 

Ähnlich wie MySQL: Indexing for Better Performance

How mysql choose the execution plan
How mysql choose the execution planHow mysql choose the execution plan
How mysql choose the execution plan辛鹤 李
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLMárton Kodok
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance OptimizationMindfire Solutions
 
SQL Server 2000 Research Series - Performance Tuning
SQL Server 2000 Research Series - Performance TuningSQL Server 2000 Research Series - Performance Tuning
SQL Server 2000 Research Series - Performance TuningJerry Yang
 
Query parameterization
Query parameterizationQuery parameterization
Query parameterizationRiteshkiit
 
MongoDB Tips and Tricks
MongoDB Tips and TricksMongoDB Tips and Tricks
MongoDB Tips and TricksM Malai
 
MySQL Indexing
MySQL IndexingMySQL Indexing
MySQL IndexingBADR
 
Optimizer overviewoow2014
Optimizer overviewoow2014Optimizer overviewoow2014
Optimizer overviewoow2014Mysql User Camp
 
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...Mydbops
 
MongoDB performance
MongoDB performanceMongoDB performance
MongoDB performanceMydbops
 
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdfRivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdfFrederic Descamps
 
15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performanceguest9912e5
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxBhupendraShahi6
 
Migration from mysql to elasticsearch
Migration from mysql to elasticsearchMigration from mysql to elasticsearch
Migration from mysql to elasticsearchRyosuke Nakamura
 
MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresSteven Johnson
 
My sql查询优化实践
My sql查询优化实践My sql查询优化实践
My sql查询优化实践ghostsun
 
Developers' New features of Sql server express 2012
Developers' New features of Sql server express 2012Developers' New features of Sql server express 2012
Developers' New features of Sql server express 2012Ziaur Rahman
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsDave Stokes
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSabrinaShanta2
 

Ähnlich wie MySQL: Indexing for Better Performance (20)

How mysql choose the execution plan
How mysql choose the execution planHow mysql choose the execution plan
How mysql choose the execution plan
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance Optimization
 
SQL Server 2000 Research Series - Performance Tuning
SQL Server 2000 Research Series - Performance TuningSQL Server 2000 Research Series - Performance Tuning
SQL Server 2000 Research Series - Performance Tuning
 
Query parameterization
Query parameterizationQuery parameterization
Query parameterization
 
MongoDB Tips and Tricks
MongoDB Tips and TricksMongoDB Tips and Tricks
MongoDB Tips and Tricks
 
MySQL Indexing
MySQL IndexingMySQL Indexing
MySQL Indexing
 
Optimizer overviewoow2014
Optimizer overviewoow2014Optimizer overviewoow2014
Optimizer overviewoow2014
 
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
 
MongoDB performance
MongoDB performanceMongoDB performance
MongoDB performance
 
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdfRivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
 
15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance
 
MySQL performance tuning
MySQL performance tuningMySQL performance tuning
MySQL performance tuning
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
Migration from mysql to elasticsearch
Migration from mysql to elasticsearchMigration from mysql to elasticsearch
Migration from mysql to elasticsearch
 
MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome Measures
 
My sql查询优化实践
My sql查询优化实践My sql查询优化实践
My sql查询优化实践
 
Developers' New features of Sql server express 2012
Developers' New features of Sql server express 2012Developers' New features of Sql server express 2012
Developers' New features of Sql server express 2012
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 

Kürzlich hochgeladen

Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 

Kürzlich hochgeladen (20)

Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 

MySQL: Indexing for Better Performance

  • 1. By: Jehad Keriaki DBA MySQL: Indexing for Better Performance1 MySQL: Indexing for Better Performance
  • 2. Jehad Keriaki 2014 What is an Index  Data structure to improve the speed of data retrieval from DBs. MySQL: Indexing for Better Performance2
  • 3. Jehad Keriaki 2014 Why Would We Use Indexes  Speed, Speed, and Speed  Constraints (Uniqueness)  IO Optimization  MAX, MIN  Sorting, Grouping MySQL: Indexing for Better Performance3
  • 4. Jehad Keriaki 2014 Index Types  Primary Key (PK), Unique, Key  Primary Key vs Unique  Unique can be NULL  InnoDB is clustered based on PK MySQL: Indexing for Better Performance4
  • 5. Jehad Keriaki 2014 Types (Algorithm)  B-Tree, R-Tree, Hash, Full text  R-Tree: Geo-spatial  Hash: Memory only, fast for equality, whole key is used, no range  Full-text:  For MyISAM, and as of 5.6 for InnoDB too.  SELECT * WHERE MATCH(description) AGAINST ('toshiba')  boolean , with query expansion, stop words, short words, 50% rule  A better choice would be to use a search server like Sphinx MySQL: Indexing for Better Performance5
  • 6. Jehad Keriaki 2014 Types (Algorithm) [cont'd]  B-Tree:  For comparison operations (<>=..etc)  Range (Between)  Like, which is a special case of range when used with %  It is the DEFAULT in MySQL  In B-Tree, data are stored in the leaf nodes MySQL: Indexing for Better Performance6
  • 7. Jehad Keriaki 2014 Types (Structure)  One column  Multi-Column [composite]  Partial [prefix]  Any one of them can be "Covering Index", except 'partial' MySQL: Indexing for Better Performance7
  • 8. Jehad Keriaki 2014 What Indexes to Create?  PK is a must  Best to be unsigned [smallest int] auto increment  PK and InnoDB (Clustered)  InnoDB tables are clustered based on PKs  Each secondary index has the PK in it. example: INDEX(name) is in fact (name, id)  AVOID long PKs. Why?  AVOID md5(), uuid(), etc. MySQL: Indexing for Better Performance8
  • 9. Jehad Keriaki 2014 MyISAM and InnoDB  In MyISAM:  Index entry tells the physical offset of the row in the data file  In InnoDB:  PK index has the data. Secondary indexes store PK as a pointer. Key on field F is (F, PK) - good for sorting and covering index MySQL: Indexing for Better Performance9
  • 10. Jehad Keriaki 2014 Cardinality and Selectivity  Cardinality: Number of distinct values  Selectivity: Cardinality / total number of rows  What values are better  Optimize  Stats Update MySQL: Indexing for Better Performance10
  • 11. Jehad Keriaki 2014 One Column Index  This index is on one column only  Query example:  SELECT * FROM employee WHERE first_name LIKE 'stephane';  Index solution:  ALTER TABLE employee ADD INDEX (first_name);  Notes:  Index the first n char of the char/varchar/text fields  Do not use a function. i.e.  WHERE md5(field)='1bc29b36f623ba82aaf6724fd3b16718' MySQL: Indexing for Better Performance11
  • 12. Jehad Keriaki 2014 Multi Column Index  What is it:  Index that involves more than one column.  Higher cardinality field goes first, with exceptions.  What 'left most' term is. [INDEX (A, B, C)]  Query example:  SELECT * FROM employee WHERE department = 5 AND last_name LIKE 'tran';  Index solution:  ALTER TABLE employee ADD INDEX (last_name, department); {WHY NOT (department, last_name)??} MySQL: Indexing for Better Performance12
  • 13. Jehad Keriaki 2014 Multi Column Index [Cont’d]  Query example:  SELECT * FROM employee WHERE department = 5 and hiring_date>='2014-01-01';  Index solution:  ALTER TABLE employee ADD INDEX (department, hiring_date);  Notes  Should it be (hiring_date, department)? Is this an exception?  Order of columns IS important  WILL NOT USE THE INDEX:  SELECT * FROM employee WHERE hiring_date>='2014-01-01'; MySQL: Indexing for Better Performance13
  • 14. Jehad Keriaki 2014 Partial Index  What is it: Index on the first n char of a field.  Query example:  email: varchar(255);  SELECT * FROM users WHERE email like 'richardmelo@yahoo.com';  Index solution  ALTER TABLE users ADD INDEX (email(12)); vs  ALTER TABLE users ADD INDEX (email);  Notes:  Save space, efficient writing, same performance  SELECT COUNT(DISTINCT(LEFT(field, 20))) FROM table  85% threshold? 90% maybe? MySQL: Indexing for Better Performance14
  • 15. Jehad Keriaki 2014 Joins and Indexes  Linking two or more tables to get related rows  Query example:  SELECT employee.first_name, employee.last_name, FROM department INNER JOIN employee ON departmant.id = employee.department WHERE department.location='MTL';  Index solution:  ALTER TABLE department ADD INDEX (location);  ALTER TABLE employee ADD INDEX (department);  Notes: The join could be on a non-indexed field on department, but an index has to exist on "employee's field" MySQL: Indexing for Better Performance15
  • 16. Jehad Keriaki 2014 Multiple Indexes OR Multi-Col Index  What is it:  ALTER TABLE ADD INDEX(field1), ADD INDEX(field2)  ALTER TABLE ADD INDEX(field1, field2)  Query example:  WHERE field1=1 OR field2=2 [multiple indexes]  WHERE field1=1 AND field2=2 [multi-col index] MySQL: Indexing for Better Performance16
  • 17. Jehad Keriaki 2014 Covering Index  When the index has the required data, no need to read data from table’s data!  Example:  employee(id, first_name, last_name, email, phone, hiring_date)  SELECT email FROM employee WHERE phone='123456789';  ALTER TABLE employee ADD INDEX(phone, email);  min(), max() functions use the index only. MySQL: Indexing for Better Performance17
  • 18. Jehad Keriaki 2014 Covering Index - Note  only in InnoDB:  myindex(col1,col2)  SELECT col1 FROM table1 WHERE col2 = 200 <<-- will use index  SELECT * FROM table1 where col2 = 200 <<-- will NOT use index. MySQL: Indexing for Better Performance18
  • 19. Jehad Keriaki 2014 ICP (Index Condition Pushdown) [5.6]  Lets the optimizer check in the index instead of checking in the table's data.  employee(id, first_name, last_name, department, phone, email, address)  INDEX(department, email)  SELECT * FROM employee WHERE department=5 AND email LIKE '%@beta.example%' [and address LIKE '%montreal%'];  Instead of stopping at department and then use where to check for email in the table's data, it will actually check in the index to see if the 2nd condition is satisfied, and then if yes, it will fetch the data from the table MySQL: Indexing for Better Performance19
  • 20. Jehad Keriaki 2014 Using Index for Sorting  ORDER BY x  (index on x)  WHERE x ORDER BY y  (index on x, y)  WHERE x ORDER BY x DESC, y DESC (index on x, y)  WHERE x ORDER BY x ASC, y DESC  (Can't use index) MySQL: Indexing for Better Performance20
  • 21. Jehad Keriaki 2014 Exceptions  E.g. Date index with other less cardinal field.  Status or Gender special cases MySQL: Indexing for Better Performance21
  • 22. Jehad Keriaki 2014 Overhead of indexing  IO: Each DML operation will modify the indexes  Disk space  More indexes => Higher possibility of deadlock MySQL: Indexing for Better Performance22
  • 23. Jehad Keriaki 2014 ABOUT EXPLAIN  It lets us know the plan of query execution  What index would be used, if any  Rows to be scanned MySQL: Indexing for Better Performance23
  • 24. MySQL: Indexing for Better Performance24 QUESTIONS & EXAMPLES
  • 25. MySQL: Indexing for Better Performance25 mysql> explain select * from md_table where id=50000G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: md_table type: const possible_keys: PRIMARY key: PRIMARY key_len: 4 ref: const rows: 1 Extra: 1 row in set (0.00 sec) mysql> explain select id from md_table where id=50000G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: md_table type: const possible_keys: PRIMARY key: PRIMARY key_len: 4 ref: const rows: 1 Extra: Using index 1 row in set (0.00 sec)
  • 26. MySQL: Indexing for Better Performance26 mysql> explain select id from md_table where hashed_id='1017bfd4673955ffee4641ad3d481b1c'G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: md_table type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 100000 Extra: Using where 1 row in set (0.00 sec) mysql> alter table md_table add index (hashed_id(15)); Query OK, 100000 rows affected (0.77 sec) Records: 100000 Duplicates: 0 Warnings: 0 mysql> explain select id from md_table where hashed_id='1017bfd4673955ffee4641ad3d481b1c'G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: md_table type: ref possible_keys: hashed_id key: hashed_id key_len: 46 ref: const rows: 1 Extra: Using where 1 row in set (0.01 sec)