SlideShare a Scribd company logo
1 of 28
Download to read offline
MySQL PerformanceMySQL Performance
OptimizationOptimization
Presenter:
Avishek Kumar Sharma
Mindfire Solutions
Date: 16/04/2014
OCP MySQL 5.0 - Oracle Certified Professional
Connect Me :
Facebook: https://www.facebook.com/avishekkumar.sharma.5
LinkedIn: http://in.linkedin.com/pub/avishek-kumar-sharma/31/798/509
Twitter: https://twitter.com/sharma_avishek
Google+: https://plus.google.com/103775319893123886681/posts
Blog:
http://avisheksharma.wordpress.com
Contact Me :
Email: avisheks@mindfiresolutions.com / avishekk111@gmail.com
Skype: mfsi_avisheks
About Me
3
Today's Talk
1. Choose Correct engine
2. Data Types and Schema Design
3. Understanding Query Execution plan
4. Profiling
5. Role of Indexing
6. Optimizing GROUP BY/ORDER BY
7. Covering index
8. Scaling data
9. Conclusion
4
Choose Correct engine
“You should use InnoDB for your tables unless you have a compelling need to use a different
engine” - High Performance MySQL by Peter Zaitsev
MyISAM vs InnoDBMyISAM vs InnoDB
InnoDB:
Transaction Support, Crash-safe
Row Level locking
Mix for mix of Updates and Select Statements
MyISAM:
Best for Read-heavy applications
Doesn't scale very well when there are a lot of writes.
Memory:
Best for small sized temp summary table, low latency, non-persistent
InnoDB also support “Full Text Search” in MySQL 5.6
5
Data Types and Schema Design
1. Add `id` to each table ( id INT(11) UNSIGNED PRIMARY KEY AUTO_INCREMENT)
2. Smaller sizes are usually better
3. Have a discussion on NULL VS blank VS 0. (choose not null for KEY
columns).
4. CHAR vs VARCHAR ( Space Vs Performance)
6
Data Types and Schema Design
5. ENUM : For storing strings values which have fixed and small sample
space use ENUM data type
6. Identifier for table joins should be of the same data type to
improve performance by reducing type conversion.
7. Normalization vs Denormalization (Faster Joins Vs Redundencies)
7
Have a look what procedure analyse() 's saying.
MySQLClint(DB:as_01):select id from dochead procedure analyse()G
*************************** 1. row ***************************
Field_name: as_01.dochead.id
Min_value: 1
Max_value: 11294
Min_length: 1
Max_length: 5
Empties_or_zeros: 0
Nulls: 0
Avg_value_or_avg_length: 5678.8494
Std: 3270.5730
Optimal_fieldtype: SMALLINT(5) UNSIGNED NOT NULL
1 row in set (0.01 sec)
This is what MySQL suggesting
the datatype to be
8
Query Execution Plan
Using the EXPLAIN keyword can give you insight on what
MySQL is doing to execute your query.
Eg: explain select col1 from <table_name> where col2=123 group by col3 order by col3;
9
Explain some field values
Some of the important columns we gonna consider are:
●
type: const, eq_ref, ref, fulltext, range, index, ALL(sort order by speed)
●
possible_keys: all the candicates for the query
●
key: selected index (could be more than one)
●
key_len: index length (agg for composite indexes)
●
rows: no of approximate rows traversal
●
extra: using filesort, using index, using temporary,using where
10
SET Profiling=ON
Profiling helps us analysing query resources
●
mysql> SET profiling=1;
●
mysql> run your query....
●
mysql> SHOW profiles;
●
mysql> SHOW profile [CPU] FOR QUERY 1;
11
Role of Indexing
Index optimization is perhaps the most powerful way to
improve query performance.
When performance problems occur:
– Add indexes
– Rewrite your queries
– Or both
Do you need to fetch data (often on disk) ?
– If the index contains the data, you don't
– If you don't, your query is covered by an index (=index-only
query)
12
Isolating the Column
MySQL generally can’t use indexes on columns unless the
columns are isolated in the query. “Isolating” the column means
it should not be part of an expression or be inside a function in
the query.
Wrong:
– mysql> SELECT actor_id FROM sakila.actor WHERE actor_id + 1 = 5;
Correct:
– mysql> SELECT actor_id FROM sakila.actor WHERE actor_id = 4;
13
Keep queries deterministic(Query Cache)
Since the return result of the function can change, MySQL
decides to disable query caching for that query.
// query cache does NOT work
$r = mysql_query("SELECT username FROM user WHERE signup_date >=
CURDATE()");
// query cache works!
$today = date("Y-m-d");
$r = mysql_query("SELECT username FROM user WHERE signup_date >=
'$today'");
NB: This applies to all non-deterministic functions like NOW() and RAND() etc
14
Column Prefix Indexes
● Smaller is usually better for obvious reasons
● Allow index BLOB/TEXT columns
CREATE TABLE user_address(
`id` INT UNSIGNED
...
...
`address` varchar(255)
PRIMARY KEY(`id`)
)
Eg: CREATE INDEX part_of_address ON user_address(address(10));
15
Choose correct prefix length
● Check the full selectivity of your column.
● Check selectivity of several prefix lengths.
16
Here we go
● Choose the prefix length having almost the same selectivity with
the full column selectivity. In the example, prefix length 7
selectivity is almost the same with the full column
selectivity so we will used it as the index.
● Create prefix indexes.
17
Optimize GROUP BY/ORDER BY
● GROUP BY and ORDER BY queries do post-retrieval
work
● GROUP BY compels to create “Temp Table”
● and ORDER BY “File Sort”
● Indexing can help get rid of this work.
18
Ignore GROUP BY sorting
● GROUP BY does implicit sorting
MySQLClint(DB:as_01)>
EXPLAIN
SELECT DISTINCT c.id,legal_name
FROM contractor c
JOIN dochead dh ON c.id=dh.contractor_to
WHERE
dh.system_id=623
AND invoice.doc_type=”invoice”
GROUP BY c.id
ORDER BY nullG
19
Check EXPLAIN's Extra
*************************** 1. row ***************************
id: 1
type: ref
....
possible_keys: dochead_contractor_to,dochead_system_id
key: dochead_system_id
key_len: 4
ref: const
rows: 306
Extra: Using where; Using temporary; Using filesort
20
Check EXPLAIN's Changes
*************************** 1. row ***************************
id: 1
type: ref
....
....
possible_keys: dochead_contractor_to,dochead_system_id
key: dochead_system_id
key_len: 4
ref: const
rows: 306
Extra: Using where; Using temporary; Using filesort
Using file sort will be vanished if
we dont bother for ordering
21
Sometimes derived tables help
● Logic is less amount of data rows has to be traverse
● Filter results by cheapest first
● Limitation is Indexes cannot be used, and it has to be less
row size.
22
Covering Index
● Indexes need to be designed for the whole query, not
just the WHERE clause. Contains (or “covers”) all the
data needed to satisfy a query.
Query with traditional index:Query with traditional index:
– Get right rows with indexGet right rows with index
– Get data from rowsGet data from rows
– Send data back to clientSend data back to client
Index-covered query:Index-covered query:
– Get right rows with indexGet right rows with index
– Get data from rowsGet data from rows
– Send data back to clientSend data back to client
23
Case Study
SELECT sum(value)SELECT sum(value)
FROM Table1FROM Table1
WHERE item_id=? AND category_id = ?WHERE item_id=? AND category_id = ?
GROUP BY customer_id;GROUP BY customer_id;
ALTER TABLE Table1ALTER TABLE Table1
ADD INDEX t1_index(item_id,category_id,customer_id,value)ADD INDEX t1_index(item_id,category_id,customer_id,value)
24
Check if used covering index
mysql> EXPLAIN SELECT sum(value)
FROM Table1
WHERE item_id=? AND category_id = ?
GROUP BY customer_id;
*************************** 1. row ***************************
table: Table1
.....
possible_keys: t1_index
key: t1_index
Extra: Using where;Using index
This signs that query used
covering index.
25
Column Order in Covering Index
1. Const or equality
WHERE a = 5
2. Range
WHERE a = 5 AND b > 5
3. Order or Group By
WHERE a = 5 AND b > 5 GROUP BY c
WHERE a = 5 AND b > 5 ORDER BY c DESC
4. Select
count(d), sum(d)
26
Lets put all together(Scaling)
●
Analyse explain and keep on trying/improving
– STRAIGHT_JOIN,
– FORCE INDEX/USE INDEX,
– IGNORE INDEX
●
Memory/Disk/CPU/Network
●
Upgrade MySQL Server
●
Move to Amazon RDS
– I strongly recommend, have personal experience
27
Thank you :)Thank you :)
28
https://www.facebook.com/MindfireSolutions
http://www.linkedin.com/company/mindfire-solutions
http://twitter.com/mindfires
www.mindfiresolutions.com
Contact Us @

More Related Content

What's hot

How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15oysteing
 
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 2013Jaime Crespo
 
TSQL Coding Guidelines
TSQL Coding GuidelinesTSQL Coding Guidelines
TSQL Coding GuidelinesChris Adkin
 
How to analyze and tune sql queries for better performance webinar
How to analyze and tune sql queries for better performance webinarHow to analyze and tune sql queries for better performance webinar
How to analyze and tune sql queries for better performance webinaroysteing
 
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 index optimization techniques
MySQL index optimization techniquesMySQL index optimization techniques
MySQL index optimization techniqueskumar gaurav
 
How to analyze and tune sql queries for better performance vts2016
How to analyze and tune sql queries for better performance vts2016How to analyze and tune sql queries for better performance vts2016
How to analyze and tune sql queries for better performance vts2016oysteing
 
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 Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index CookbookMYXPLAIN
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standardsAlessandro Baratella
 
Query parameterization
Query parameterizationQuery parameterization
Query parameterizationRiteshkiit
 
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 joins example table and query process
Mysql joins example table and query processMysql joins example table and query process
Mysql joins example table and query processAnandarasu Ramaiya
 
A testing framework for Microsoft SQL-Server
A testing framework for Microsoft SQL-ServerA testing framework for Microsoft SQL-Server
A testing framework for Microsoft SQL-Serverelliando dias
 

What's hot (20)

How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15
 
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
 
MySQL Indexes
MySQL IndexesMySQL Indexes
MySQL Indexes
 
TSQL Coding Guidelines
TSQL Coding GuidelinesTSQL Coding Guidelines
TSQL Coding Guidelines
 
How to analyze and tune sql queries for better performance webinar
How to analyze and tune sql queries for better performance webinarHow to analyze and tune sql queries for better performance webinar
How to analyze and tune sql queries for better performance webinar
 
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
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
 
MySQL index optimization techniques
MySQL index optimization techniquesMySQL index optimization techniques
MySQL index optimization techniques
 
How to analyze and tune sql queries for better performance vts2016
How to analyze and tune sql queries for better performance vts2016How to analyze and tune sql queries for better performance vts2016
How to analyze and tune sql queries for better performance vts2016
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
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 Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Query parameterization
Query parameterizationQuery parameterization
Query parameterization
 
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 joins example table and query process
Mysql joins example table and query processMysql joins example table and query process
Mysql joins example table and query process
 
MySQL basics
MySQL basicsMySQL basics
MySQL basics
 
A testing framework for Microsoft SQL-Server
A testing framework for Microsoft SQL-ServerA testing framework for Microsoft SQL-Server
A testing framework for Microsoft SQL-Server
 
Sql db optimization
Sql db optimizationSql db optimization
Sql db optimization
 

Similar to MySQL Performance Optimization Guide

My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the ServerdevObjective
 
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
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsDave Stokes
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statementsxKinAnx
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluationavniS
 
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...Dave Stokes
 
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 TricksMYXPLAIN
 
My Database Skills Killed the Server
My Database Skills Killed the ServerMy Database Skills Killed the Server
My Database Skills Killed the ServerColdFusionConference
 
Goldilocks and the Three MySQL Queries
Goldilocks and the Three MySQL QueriesGoldilocks and the Three MySQL Queries
Goldilocks and the Three MySQL QueriesDave Stokes
 
PostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_CheatsheetPostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_CheatsheetLucian Oprea
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB
 
Tunning sql query
Tunning sql queryTunning sql query
Tunning sql queryvuhaininh88
 
Sql Server Query Parameterization
Sql Server Query ParameterizationSql Server Query Parameterization
Sql Server Query ParameterizationMindfire Solutions
 
Confoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsConfoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsDave Stokes
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning Arno Huetter
 
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDave Stokes
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsNirav Shah
 

Similar to MySQL Performance Optimization Guide (20)

My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
 
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
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Mysql Optimization
Mysql OptimizationMysql Optimization
Mysql Optimization
 
MySQL performance tuning
MySQL performance tuningMySQL performance tuning
MySQL performance tuning
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
 
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
 
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
 
My Database Skills Killed the Server
My Database Skills Killed the ServerMy Database Skills Killed the Server
My Database Skills Killed the Server
 
Goldilocks and the Three MySQL Queries
Goldilocks and the Three MySQL QueriesGoldilocks and the Three MySQL Queries
Goldilocks and the Three MySQL Queries
 
PostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_CheatsheetPostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_Cheatsheet
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
 
Tunning sql query
Tunning sql queryTunning sql query
Tunning sql query
 
Sql Server Query Parameterization
Sql Server Query ParameterizationSql Server Query Parameterization
Sql Server Query Parameterization
 
Confoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsConfoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & Histograms
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
 
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
 

More from Mindfire Solutions (20)

Physician Search and Review
Physician Search and ReviewPhysician Search and Review
Physician Search and Review
 
diet management app
diet management appdiet management app
diet management app
 
Business Technology Solution
Business Technology SolutionBusiness Technology Solution
Business Technology Solution
 
Remote Health Monitoring
Remote Health MonitoringRemote Health Monitoring
Remote Health Monitoring
 
Influencer Marketing Solution
Influencer Marketing SolutionInfluencer Marketing Solution
Influencer Marketing Solution
 
ELMAH
ELMAHELMAH
ELMAH
 
High Availability of Azure Applications
High Availability of Azure ApplicationsHigh Availability of Azure Applications
High Availability of Azure Applications
 
IOT Hands On
IOT Hands OnIOT Hands On
IOT Hands On
 
Glimpse of Loops Vs Set
Glimpse of Loops Vs SetGlimpse of Loops Vs Set
Glimpse of Loops Vs Set
 
Oracle Sql Developer-Getting Started
Oracle Sql Developer-Getting StartedOracle Sql Developer-Getting Started
Oracle Sql Developer-Getting Started
 
Adaptive Layout In iOS 8
Adaptive Layout In iOS 8Adaptive Layout In iOS 8
Adaptive Layout In iOS 8
 
Introduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/MacIntroduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/Mac
 
LINQPad - utility Tool
LINQPad - utility ToolLINQPad - utility Tool
LINQPad - utility Tool
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit development
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Material Design in Android
Material Design in AndroidMaterial Design in Android
Material Design in Android
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
 
Ext js Part 2- MVC
Ext js Part 2- MVCExt js Part 2- MVC
Ext js Part 2- MVC
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Spring Security Introduction
Spring Security IntroductionSpring Security Introduction
Spring Security Introduction
 

Recently uploaded

Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
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
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
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
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 

Recently uploaded (20)

Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
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
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
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
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 

MySQL Performance Optimization Guide

  • 2. OCP MySQL 5.0 - Oracle Certified Professional Connect Me : Facebook: https://www.facebook.com/avishekkumar.sharma.5 LinkedIn: http://in.linkedin.com/pub/avishek-kumar-sharma/31/798/509 Twitter: https://twitter.com/sharma_avishek Google+: https://plus.google.com/103775319893123886681/posts Blog: http://avisheksharma.wordpress.com Contact Me : Email: avisheks@mindfiresolutions.com / avishekk111@gmail.com Skype: mfsi_avisheks About Me
  • 3. 3 Today's Talk 1. Choose Correct engine 2. Data Types and Schema Design 3. Understanding Query Execution plan 4. Profiling 5. Role of Indexing 6. Optimizing GROUP BY/ORDER BY 7. Covering index 8. Scaling data 9. Conclusion
  • 4. 4 Choose Correct engine “You should use InnoDB for your tables unless you have a compelling need to use a different engine” - High Performance MySQL by Peter Zaitsev MyISAM vs InnoDBMyISAM vs InnoDB InnoDB: Transaction Support, Crash-safe Row Level locking Mix for mix of Updates and Select Statements MyISAM: Best for Read-heavy applications Doesn't scale very well when there are a lot of writes. Memory: Best for small sized temp summary table, low latency, non-persistent InnoDB also support “Full Text Search” in MySQL 5.6
  • 5. 5 Data Types and Schema Design 1. Add `id` to each table ( id INT(11) UNSIGNED PRIMARY KEY AUTO_INCREMENT) 2. Smaller sizes are usually better 3. Have a discussion on NULL VS blank VS 0. (choose not null for KEY columns). 4. CHAR vs VARCHAR ( Space Vs Performance)
  • 6. 6 Data Types and Schema Design 5. ENUM : For storing strings values which have fixed and small sample space use ENUM data type 6. Identifier for table joins should be of the same data type to improve performance by reducing type conversion. 7. Normalization vs Denormalization (Faster Joins Vs Redundencies)
  • 7. 7 Have a look what procedure analyse() 's saying. MySQLClint(DB:as_01):select id from dochead procedure analyse()G *************************** 1. row *************************** Field_name: as_01.dochead.id Min_value: 1 Max_value: 11294 Min_length: 1 Max_length: 5 Empties_or_zeros: 0 Nulls: 0 Avg_value_or_avg_length: 5678.8494 Std: 3270.5730 Optimal_fieldtype: SMALLINT(5) UNSIGNED NOT NULL 1 row in set (0.01 sec) This is what MySQL suggesting the datatype to be
  • 8. 8 Query Execution Plan Using the EXPLAIN keyword can give you insight on what MySQL is doing to execute your query. Eg: explain select col1 from <table_name> where col2=123 group by col3 order by col3;
  • 9. 9 Explain some field values Some of the important columns we gonna consider are: ● type: const, eq_ref, ref, fulltext, range, index, ALL(sort order by speed) ● possible_keys: all the candicates for the query ● key: selected index (could be more than one) ● key_len: index length (agg for composite indexes) ● rows: no of approximate rows traversal ● extra: using filesort, using index, using temporary,using where
  • 10. 10 SET Profiling=ON Profiling helps us analysing query resources ● mysql> SET profiling=1; ● mysql> run your query.... ● mysql> SHOW profiles; ● mysql> SHOW profile [CPU] FOR QUERY 1;
  • 11. 11 Role of Indexing Index optimization is perhaps the most powerful way to improve query performance. When performance problems occur: – Add indexes – Rewrite your queries – Or both Do you need to fetch data (often on disk) ? – If the index contains the data, you don't – If you don't, your query is covered by an index (=index-only query)
  • 12. 12 Isolating the Column MySQL generally can’t use indexes on columns unless the columns are isolated in the query. “Isolating” the column means it should not be part of an expression or be inside a function in the query. Wrong: – mysql> SELECT actor_id FROM sakila.actor WHERE actor_id + 1 = 5; Correct: – mysql> SELECT actor_id FROM sakila.actor WHERE actor_id = 4;
  • 13. 13 Keep queries deterministic(Query Cache) Since the return result of the function can change, MySQL decides to disable query caching for that query. // query cache does NOT work $r = mysql_query("SELECT username FROM user WHERE signup_date >= CURDATE()"); // query cache works! $today = date("Y-m-d"); $r = mysql_query("SELECT username FROM user WHERE signup_date >= '$today'"); NB: This applies to all non-deterministic functions like NOW() and RAND() etc
  • 14. 14 Column Prefix Indexes ● Smaller is usually better for obvious reasons ● Allow index BLOB/TEXT columns CREATE TABLE user_address( `id` INT UNSIGNED ... ... `address` varchar(255) PRIMARY KEY(`id`) ) Eg: CREATE INDEX part_of_address ON user_address(address(10));
  • 15. 15 Choose correct prefix length ● Check the full selectivity of your column. ● Check selectivity of several prefix lengths.
  • 16. 16 Here we go ● Choose the prefix length having almost the same selectivity with the full column selectivity. In the example, prefix length 7 selectivity is almost the same with the full column selectivity so we will used it as the index. ● Create prefix indexes.
  • 17. 17 Optimize GROUP BY/ORDER BY ● GROUP BY and ORDER BY queries do post-retrieval work ● GROUP BY compels to create “Temp Table” ● and ORDER BY “File Sort” ● Indexing can help get rid of this work.
  • 18. 18 Ignore GROUP BY sorting ● GROUP BY does implicit sorting MySQLClint(DB:as_01)> EXPLAIN SELECT DISTINCT c.id,legal_name FROM contractor c JOIN dochead dh ON c.id=dh.contractor_to WHERE dh.system_id=623 AND invoice.doc_type=”invoice” GROUP BY c.id ORDER BY nullG
  • 19. 19 Check EXPLAIN's Extra *************************** 1. row *************************** id: 1 type: ref .... possible_keys: dochead_contractor_to,dochead_system_id key: dochead_system_id key_len: 4 ref: const rows: 306 Extra: Using where; Using temporary; Using filesort
  • 20. 20 Check EXPLAIN's Changes *************************** 1. row *************************** id: 1 type: ref .... .... possible_keys: dochead_contractor_to,dochead_system_id key: dochead_system_id key_len: 4 ref: const rows: 306 Extra: Using where; Using temporary; Using filesort Using file sort will be vanished if we dont bother for ordering
  • 21. 21 Sometimes derived tables help ● Logic is less amount of data rows has to be traverse ● Filter results by cheapest first ● Limitation is Indexes cannot be used, and it has to be less row size.
  • 22. 22 Covering Index ● Indexes need to be designed for the whole query, not just the WHERE clause. Contains (or “covers”) all the data needed to satisfy a query. Query with traditional index:Query with traditional index: – Get right rows with indexGet right rows with index – Get data from rowsGet data from rows – Send data back to clientSend data back to client Index-covered query:Index-covered query: – Get right rows with indexGet right rows with index – Get data from rowsGet data from rows – Send data back to clientSend data back to client
  • 23. 23 Case Study SELECT sum(value)SELECT sum(value) FROM Table1FROM Table1 WHERE item_id=? AND category_id = ?WHERE item_id=? AND category_id = ? GROUP BY customer_id;GROUP BY customer_id; ALTER TABLE Table1ALTER TABLE Table1 ADD INDEX t1_index(item_id,category_id,customer_id,value)ADD INDEX t1_index(item_id,category_id,customer_id,value)
  • 24. 24 Check if used covering index mysql> EXPLAIN SELECT sum(value) FROM Table1 WHERE item_id=? AND category_id = ? GROUP BY customer_id; *************************** 1. row *************************** table: Table1 ..... possible_keys: t1_index key: t1_index Extra: Using where;Using index This signs that query used covering index.
  • 25. 25 Column Order in Covering Index 1. Const or equality WHERE a = 5 2. Range WHERE a = 5 AND b > 5 3. Order or Group By WHERE a = 5 AND b > 5 GROUP BY c WHERE a = 5 AND b > 5 ORDER BY c DESC 4. Select count(d), sum(d)
  • 26. 26 Lets put all together(Scaling) ● Analyse explain and keep on trying/improving – STRAIGHT_JOIN, – FORCE INDEX/USE INDEX, – IGNORE INDEX ● Memory/Disk/CPU/Network ● Upgrade MySQL Server ● Move to Amazon RDS – I strongly recommend, have personal experience