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

More Related Content

What's hot

Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
oracle content
 
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
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
Mahabubur Rahaman
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
Salman Memon
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
Raveena Thakur
 
How to Use JSON in MySQL Wrong
How to Use JSON in MySQL WrongHow to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
Karwin Software Solutions LLC
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
Nilt1234
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
Hammad Rasheed
 
MySQL INDEXES
MySQL INDEXESMySQL INDEXES
MySQL INDEXES
HripsimeGhaltaghchya
 
MySQL Architecture and Engine
MySQL Architecture and EngineMySQL Architecture and Engine
MySQL Architecture and EngineAbdul Manaf
 
Mysql index
Mysql indexMysql index
Mysql indexYuan Yao
 
Sql commands
Sql commandsSql commands
Sql commands
Pooja Dixit
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
Saeid Zebardast
 
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
 
Sql Constraints
Sql ConstraintsSql Constraints
Sql Constraints
I L0V3 CODING DR
 
MySQL Basics
MySQL BasicsMySQL Basics
MySQL Basics
mysql content
 
B+Tree Indexes and InnoDB
B+Tree Indexes and InnoDBB+Tree Indexes and InnoDB
B+Tree Indexes and InnoDB
Ovais Tariq
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
Amrit Kaur
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
1keydata
 

What's hot (20)

Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
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
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
How to Use JSON in MySQL Wrong
How to Use JSON in MySQL WrongHow to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
MySQL INDEXES
MySQL INDEXESMySQL INDEXES
MySQL INDEXES
 
MySQL Architecture and Engine
MySQL Architecture and EngineMySQL Architecture and Engine
MySQL Architecture and Engine
 
Mysql index
Mysql indexMysql index
Mysql index
 
Sql commands
Sql commandsSql commands
Sql commands
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
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
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Sql Constraints
Sql ConstraintsSql Constraints
Sql Constraints
 
MySQL Basics
MySQL BasicsMySQL Basics
MySQL Basics
 
B+Tree Indexes and InnoDB
B+Tree Indexes and InnoDBB+Tree Indexes and InnoDB
B+Tree Indexes and InnoDB
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 

Viewers also liked

How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
Karwin Software Solutions LLC
 
My MySQL SQL Presentation
My MySQL SQL PresentationMy MySQL SQL Presentation
My MySQL SQL Presentation
Justin Rhinesmith
 
MySQL Views
MySQL ViewsMySQL Views
Mysql Indexing
Mysql IndexingMysql Indexing
Mysql Indexing
Tasawr Interactive
 
1 data types
1 data types1 data types
1 data types
Ram Kedem
 
3 indexes
3 indexes3 indexes
3 indexes
Ram Kedem
 
Database indexing framework
Database indexing frameworkDatabase indexing framework
Database indexing framework
Nitin Pande
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
Md.Mojibul Hoque
 
Database indexing techniques
Database indexing techniquesDatabase indexing techniques
Database indexing techniques
ahmadmughal0312
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
Md. Mahedee Hasan
 
Introduction to TFS 2013
Introduction to TFS 2013Introduction to TFS 2013
Introduction to TFS 2013
Md. Mahedee Hasan
 
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 ecosystem
Ronald Bradford
 
10x Performance Improvements - A Case Study
10x Performance Improvements - A Case Study10x Performance Improvements - A Case Study
10x Performance Improvements - A Case Study
Ronald Bradford
 
Lessons Learned Managing Large AWS Environments
Lessons Learned Managing Large AWS EnvironmentsLessons Learned Managing Large AWS Environments
Lessons Learned Managing Large AWS Environments
Ronald 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 Schema
Ted Wennmark
 
MySQL Performance - SydPHP October 2011
MySQL Performance - SydPHP October 2011MySQL Performance - SydPHP October 2011
MySQL Performance - SydPHP October 2011
Graham Weldon
 
MySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance SchemaMySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance Schema
Sveta 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
 

Viewers also liked (20)

How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
 
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
 
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)
 

Similar to 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 MySQL
Márton Kodok
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance Optimization
Mindfire 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 parameterization
Riteshkiit
 
MongoDB Tips and Tricks
MongoDB Tips and TricksMongoDB Tips and Tricks
MongoDB Tips and Tricks
M Malai
 
MySQL Indexing
MySQL IndexingMySQL Indexing
MySQL Indexing
BADR
 
Optimizer overviewoow2014
Optimizer overviewoow2014Optimizer overviewoow2014
Optimizer overviewoow2014
Mysql 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 performance
Mydbops
 
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
Frederic 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 Performance
guest9912e5
 
MySQL performance tuning
MySQL performance tuningMySQL performance tuning
MySQL performance tuning
Anurag Srivastava
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
BhupendraShahi6
 
Migration from mysql to elasticsearch
Migration from mysql to elasticsearchMigration from mysql to elasticsearch
Migration from mysql to elasticsearch
Ryosuke Nakamura
 
MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome Measures
Steven 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 Optimizations
Dave Stokes
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SabrinaShanta2
 

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

Recently uploaded

AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 

Recently uploaded (20)

AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 

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)