SlideShare une entreprise Scribd logo
1  sur  3
Use EXPLAIN to profile the query execution plan
 Use Slow Query Log (always have it on!)
 Don’t use DISTINCT when you have or could use GROUP BY
 Use proper data partitions

   1. For Cluster. Start thinking about Cluster *before* you need them

 Insert performance

   1. Batch INSERT and REPLACE
   2. Use LOAD DATA instead of INSERT

 LIMITm,n may not be as fast as it sounds
 Don’t use ORDER BY RAND() if you have > ~2K records
 Use SQL_NO_CACHE when you are SELECTing frequently updated data or large sets of
data
 avoid wildcards at the start of LIKE queries
 avoid correlated subqueries and in select and where clause (try to avoid in)
 configparams --
 no calculated comparisons -- isolate indexed columns
 innodb_flush_commit=0 can help slave lag
 ORDER BY and LIMIT work best with equalities and covered indexes
 isolate workloads don’t let administrative work interfere with customer performance. (ie
backups)
 use optimistic locking, not pessimistic locking. try to use shared lock, not exclusive lock.
share mode vs. FOR UPDATE
 use row-level instead of table-level locking for OLTP workloads
 Know your storage engines and what performs best for your needs, know that different
ones exist.

   1. use MERGE tables ARCHIVE tables for logs

 Optimize for data types, use consistent data types. Use PROCEDURE ANALYSE() to help
determine if you need less
 separate text/blobs from metadata, don’t put text/blobs in results if you don’t need them
 if you can, compress text/blobs
 compress static data
 don’t back up static data as often
 derived tables (subqueries in the FROM clause) can be useful for retrieving BLOBs w/out
sorting them. (self-join can speed up a query if 1st part finds the IDs and use it to fetch the
rest)
 enable and increase the query and buffer caches if appropriate
 ALTER TABLE…ORDER BY can take chronological data and re-order it by a different field
 InnoDB ALWAYS keeps the primary key as part of each index, so do not make the primary
key very large, be careful of redundant columns in an index, and this can make the query
faster
Do not duplicate indexes
 Utilize different storage engines on master/slave ie, if you need fulltext indexing on a
table.
 BLACKHOLE engine and replication is much faster than FEDERATED tables for things like
logs.
 Design sane query schemas. don’t be afraid of table joins, often they are faster than
denormalization
 Don’t use boolean flags
 Use a clever key and ORDER BY instead of MAX
 Keep the database host as clean as possible. Do you really need a windowing system on
that server?
 Utilize the strengths of the OS
 Hire a MySQL ™ Certified DBA
 Know that there are many consulting companies out there that can help, as well as
MySQL’s Professional Services.
 Config variables & tips:

   1. use one of the supplied config files
   2. key_buffer, unix cache (leave some RAM free), per-connection variables, innodb
       memory variables
   3. be aware of global vs. per-connection variables
   4. check SHOW STATUS and SHOW VARIABLES (GLOBAL|SESSION in 5.0 and up)
   5. be aware of swapping esp. with Linux, “swappiness” (bypass OS filecache for innodb
       data files, innodb_flush_method=O_DIRECT if possible (this is also OS specific))
   6. defragment tables, rebuild indexes, do table maintenance
   7. If you use innodb_flush_txn_commit=1, use a battery-backed hardware cache write
       controller
   8. more RAM is good so faster disk speed
   9. use 64-bit architectures

 Know when to split a complex query and join smaller ones
 Debugging sucks, testing rocks!
 Delete small amounts at a time if you can
 Archive old data -- don’t be a pack-rat! 2 common engines for this are ARCHIVE tables and
MERGE tables
 use INET_ATON and INET_NTOA for IP addresses, not char or varchar
 make it a habit to REVERSE() email addresses, so you can easily search domains
 --skip-name-resolve
 increasemyisam_sort_buffer_size to optimize large inserts (this is a per-connection
variable)
 look up memory tuning parameter for on-insert caching
 increase temp table size in a data warehousing environment (default is 32Mb) so it doesn’t
write to disk (also constrained by max_heap_table_size, default 16Mb)
 Normalize first, and denormalize where appropriate.
 Databases are not spreadsheets, even though Access really really looks like one. Then
again, Access isn’t a real database
 In 5.1 BOOL/BIT NOT NULL type is 1 bit, in previous versions it’s 1 byte.
A NULL data type can take more room to store than NOT NULL
 Choose appropriate character sets & collations -- UTF16 will store each character in 2
bytes, whether it needs it or not, latin1 is faster than UTF8.
 make similar queries consistent so cache is used
 Don’t use deprecated features
 Use Triggers wisely
 Run in SQL_MODE=STRICT to help identify warnings
 Turning OR on multiple index fields (<5.0) into UNION may speed things up (with LIMIT),
after 5.0 the index_merge should pick stuff up.
 /tmpdir on battery-backed write cache
 consider battery-backed RAM for innodblogfiles
 usemin_rows and max_rows to specify approximate data size so space can be pre-
allocated and reference points can be calculated.
 as your data grows, indexing may change (cardinality and selectivity change). Structuring
may want to change. Make your schema as modular as your code. Make your code able to
scale. Plan and embrace change, and get developers to do the same.
 pare down cron scripts
 create a test environment
 try out a few schemas and storage engines in your test environment before picking one.
 Use HASH indexing for indexing across columns with similar data prefixes
 Usemyisam_pack_keys for int data
 Don’t use COUNT * on Innodb tables for every search, do it a few times and/or summary
tables, or if you need it for the total # of rows, use SQL_CALC_FOUND_ROWS and SELECT
FOUND_ROWS()
 use --safe-updates for client
 Redundant data is redundant
 Use INSERT … ON DUPLICATE KEY update (INSERT IGNORE) to avoid having to SELECT
 usegroupwise maximum instead of subqueries
 be able to change your schema without ruining functionality of your code
 source control schema and config files
 for LVM innodb backups, restore to a different instance of MySQL so Innodb can roll
forward
 usemulti_query if appropriate to reduce round-trips
 partition appropriately
 partition your database when you have real data
 segregate tables/databases that benefit from different configuration variables

Contenu connexe

Tendances

Dwh lecture slides-week5&6
Dwh lecture slides-week5&6Dwh lecture slides-week5&6
Dwh lecture slides-week5&6Shani729
 
PostgreSQL Advanced Queries
PostgreSQL Advanced QueriesPostgreSQL Advanced Queries
PostgreSQL Advanced QueriesNur Hidayat
 
MDF and LDF in SQL Server
MDF and LDF in SQL ServerMDF and LDF in SQL Server
MDF and LDF in SQL ServerMasum Reza
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012Eduardo Castro
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008paulguerin
 
Microsoft SQL Server - Files and Filegroups
Microsoft SQL Server - Files and FilegroupsMicrosoft SQL Server - Files and Filegroups
Microsoft SQL Server - Files and FilegroupsNaji El Kotob
 
Sql introduction
Sql introductionSql introduction
Sql introductionvimal_guru
 
The design and implementation of modern column oriented databases
The design and implementation of modern column oriented databasesThe design and implementation of modern column oriented databases
The design and implementation of modern column oriented databasesTilak Patidar
 
Dwh lecture 08-denormalization tech
Dwh   lecture 08-denormalization techDwh   lecture 08-denormalization tech
Dwh lecture 08-denormalization techSulman Ahmed
 
Database Administrator interview questions and answers
Database Administrator interview questions and answersDatabase Administrator interview questions and answers
Database Administrator interview questions and answersMLR Institute of Technology
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL IISankhya_Analytics
 
SQL Server 2008 Development for Programmers
SQL Server 2008 Development for ProgrammersSQL Server 2008 Development for Programmers
SQL Server 2008 Development for ProgrammersAdam Hutson
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018Dave Stokes
 
Starburst by Umar danjuma maiwada presentation
Starburst by Umar danjuma maiwada presentationStarburst by Umar danjuma maiwada presentation
Starburst by Umar danjuma maiwada presentationumardanjumamaiwada
 

Tendances (18)

SKILLWISE-DB2 DBA
SKILLWISE-DB2 DBASKILLWISE-DB2 DBA
SKILLWISE-DB2 DBA
 
MySQL Overview
MySQL OverviewMySQL Overview
MySQL Overview
 
Dwh lecture slides-week5&6
Dwh lecture slides-week5&6Dwh lecture slides-week5&6
Dwh lecture slides-week5&6
 
PostgreSQL Advanced Queries
PostgreSQL Advanced QueriesPostgreSQL Advanced Queries
PostgreSQL Advanced Queries
 
MDF and LDF in SQL Server
MDF and LDF in SQL ServerMDF and LDF in SQL Server
MDF and LDF in SQL Server
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008
 
Unit 5-lecture-3
Unit 5-lecture-3Unit 5-lecture-3
Unit 5-lecture-3
 
Microsoft SQL Server - Files and Filegroups
Microsoft SQL Server - Files and FilegroupsMicrosoft SQL Server - Files and Filegroups
Microsoft SQL Server - Files and Filegroups
 
Sql introduction
Sql introductionSql introduction
Sql introduction
 
The design and implementation of modern column oriented databases
The design and implementation of modern column oriented databasesThe design and implementation of modern column oriented databases
The design and implementation of modern column oriented databases
 
Dwh lecture 08-denormalization tech
Dwh   lecture 08-denormalization techDwh   lecture 08-denormalization tech
Dwh lecture 08-denormalization tech
 
Database Administrator interview questions and answers
Database Administrator interview questions and answersDatabase Administrator interview questions and answers
Database Administrator interview questions and answers
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
SQL Server 2008 Development for Programmers
SQL Server 2008 Development for ProgrammersSQL Server 2008 Development for Programmers
SQL Server 2008 Development for Programmers
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018
 
Starburst by Umar danjuma maiwada presentation
Starburst by Umar danjuma maiwada presentationStarburst by Umar danjuma maiwada presentation
Starburst by Umar danjuma maiwada presentation
 
MySql:Basics
MySql:BasicsMySql:Basics
MySql:Basics
 

En vedette

Everything is fine with slide share
Everything is fine with slide shareEverything is fine with slide share
Everything is fine with slide sharesmittal81
 
Confira na íntegra a decisão que afastou Eduardo Cunha da Câmara
Confira na íntegra a decisão que afastou Eduardo Cunha da CâmaraConfira na íntegra a decisão que afastou Eduardo Cunha da Câmara
Confira na íntegra a decisão que afastou Eduardo Cunha da CâmaraMaria Santos
 
Power point de la naturaleza
Power point de la naturalezaPower point de la naturaleza
Power point de la naturalezakarmen17
 
Testing the result of side share
Testing the result of side shareTesting the result of side share
Testing the result of side sharesmittal81
 
Acelacare rock health app final
Acelacare rock health app finalAcelacare rock health app final
Acelacare rock health app finalPatricia Salber
 
Lista dos políticos favorecidos pela Odebrecht
Lista dos políticos favorecidos pela OdebrechtLista dos políticos favorecidos pela Odebrecht
Lista dos políticos favorecidos pela OdebrechtMaria Santos
 
Lei do Carnaval de Olinda - 5306/2001
Lei do Carnaval de Olinda - 5306/2001Lei do Carnaval de Olinda - 5306/2001
Lei do Carnaval de Olinda - 5306/2001Maria Santos
 
POLYCOM REAL PRESENCE DEBUT, VIDEOCONFERENCIA PARA PyMES
POLYCOM REAL PRESENCE DEBUT, VIDEOCONFERENCIA PARA PyMESPOLYCOM REAL PRESENCE DEBUT, VIDEOCONFERENCIA PARA PyMES
POLYCOM REAL PRESENCE DEBUT, VIDEOCONFERENCIA PARA PyMESANTONIO NIETO ATIENZA
 
Analysing texts
Analysing textsAnalysing texts
Analysing textsmillyollis
 
Resultado do vestibular da Unicap 20161
Resultado do vestibular da Unicap 20161 Resultado do vestibular da Unicap 20161
Resultado do vestibular da Unicap 20161 Maria Santos
 
SSA3 - Confira o resultado do vestibular da UPE
SSA3 - Confira o resultado do vestibular da UPESSA3 - Confira o resultado do vestibular da UPE
SSA3 - Confira o resultado do vestibular da UPEMaria Santos
 
Elle Magazine Cover Analysis
Elle Magazine Cover Analysis Elle Magazine Cover Analysis
Elle Magazine Cover Analysis millyollis
 

En vedette (16)

Everything is fine with slide share
Everything is fine with slide shareEverything is fine with slide share
Everything is fine with slide share
 
Confira na íntegra a decisão que afastou Eduardo Cunha da Câmara
Confira na íntegra a decisão que afastou Eduardo Cunha da CâmaraConfira na íntegra a decisão que afastou Eduardo Cunha da Câmara
Confira na íntegra a decisão que afastou Eduardo Cunha da Câmara
 
Power point de la naturaleza
Power point de la naturalezaPower point de la naturaleza
Power point de la naturaleza
 
IDA
IDAIDA
IDA
 
Testing the result of side share
Testing the result of side shareTesting the result of side share
Testing the result of side share
 
Acelacare rock health app final
Acelacare rock health app finalAcelacare rock health app final
Acelacare rock health app final
 
Caribbean social stratification_race
Caribbean social stratification_raceCaribbean social stratification_race
Caribbean social stratification_race
 
Lista dos políticos favorecidos pela Odebrecht
Lista dos políticos favorecidos pela OdebrechtLista dos políticos favorecidos pela Odebrecht
Lista dos políticos favorecidos pela Odebrecht
 
Lei do Carnaval de Olinda - 5306/2001
Lei do Carnaval de Olinda - 5306/2001Lei do Carnaval de Olinda - 5306/2001
Lei do Carnaval de Olinda - 5306/2001
 
Patient powered care
Patient powered carePatient powered care
Patient powered care
 
POLYCOM REAL PRESENCE DEBUT, VIDEOCONFERENCIA PARA PyMES
POLYCOM REAL PRESENCE DEBUT, VIDEOCONFERENCIA PARA PyMESPOLYCOM REAL PRESENCE DEBUT, VIDEOCONFERENCIA PARA PyMES
POLYCOM REAL PRESENCE DEBUT, VIDEOCONFERENCIA PARA PyMES
 
Analysing texts
Analysing textsAnalysing texts
Analysing texts
 
Resultado do vestibular da Unicap 20161
Resultado do vestibular da Unicap 20161 Resultado do vestibular da Unicap 20161
Resultado do vestibular da Unicap 20161
 
SSA3 - Confira o resultado do vestibular da UPE
SSA3 - Confira o resultado do vestibular da UPESSA3 - Confira o resultado do vestibular da UPE
SSA3 - Confira o resultado do vestibular da UPE
 
Plural society
Plural societyPlural society
Plural society
 
Elle Magazine Cover Analysis
Elle Magazine Cover Analysis Elle Magazine Cover Analysis
Elle Magazine Cover Analysis
 

Similaire à EXPLAIN to profile query execution plan

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
 
Basics on SQL queries
Basics on SQL queriesBasics on SQL queries
Basics on SQL queriesKnoldus Inc.
 
Perl and Elasticsearch
Perl and ElasticsearchPerl and Elasticsearch
Perl and ElasticsearchDean Hamstead
 
White paper on Spool space in teradata
White paper on Spool space in teradataWhite paper on Spool space in teradata
White paper on Spool space in teradataSanjeev Kumar Jaiswal
 
DB2 LUW V11.1 CERTIFICATION TRAINING PART #1
DB2 LUW V11.1 CERTIFICATION TRAINING PART #1DB2 LUW V11.1 CERTIFICATION TRAINING PART #1
DB2 LUW V11.1 CERTIFICATION TRAINING PART #1sunildupakuntla
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserverlochaaaa
 
Implementing the Databese Server session 02
Implementing the Databese Server session 02Implementing the Databese Server session 02
Implementing the Databese Server session 02Guillermo Julca
 
The thinking persons guide to data warehouse design
The thinking persons guide to data warehouse designThe thinking persons guide to data warehouse design
The thinking persons guide to data warehouse designCalpont
 
SQL Server 2008 Performance Enhancements
SQL Server 2008 Performance EnhancementsSQL Server 2008 Performance Enhancements
SQL Server 2008 Performance Enhancementsinfusiondev
 
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...javier ramirez
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning Arno Huetter
 
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...javier ramirez
 
Elasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep diveElasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep diveSematext Group, Inc.
 
jacobs_tuuri_performance
jacobs_tuuri_performancejacobs_tuuri_performance
jacobs_tuuri_performanceHiroshi Ono
 
Db2 performance tuning for dummies
Db2 performance tuning for dummiesDb2 performance tuning for dummies
Db2 performance tuning for dummiesAngel Dueñas Neyra
 
Large scale sql server best practices
Large scale sql server   best practicesLarge scale sql server   best practices
Large scale sql server best practicesmprabhuram
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standardsAlessandro Baratella
 
Building scalable application with sql server
Building scalable application with sql serverBuilding scalable application with sql server
Building scalable application with sql serverChris Adkin
 

Similaire à EXPLAIN to profile query execution plan (20)

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 For Developers
Mysql For DevelopersMysql For Developers
Mysql For Developers
 
Basics on SQL queries
Basics on SQL queriesBasics on SQL queries
Basics on SQL queries
 
Perl and Elasticsearch
Perl and ElasticsearchPerl and Elasticsearch
Perl and Elasticsearch
 
White paper on Spool space in teradata
White paper on Spool space in teradataWhite paper on Spool space in teradata
White paper on Spool space in teradata
 
DB2 LUW V11.1 CERTIFICATION TRAINING PART #1
DB2 LUW V11.1 CERTIFICATION TRAINING PART #1DB2 LUW V11.1 CERTIFICATION TRAINING PART #1
DB2 LUW V11.1 CERTIFICATION TRAINING PART #1
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
 
Implementing the Databese Server session 02
Implementing the Databese Server session 02Implementing the Databese Server session 02
Implementing the Databese Server session 02
 
The thinking persons guide to data warehouse design
The thinking persons guide to data warehouse designThe thinking persons guide to data warehouse design
The thinking persons guide to data warehouse design
 
SQL Server 2008 Performance Enhancements
SQL Server 2008 Performance EnhancementsSQL Server 2008 Performance Enhancements
SQL Server 2008 Performance Enhancements
 
Stored procedure tunning
Stored procedure tunningStored procedure tunning
Stored procedure tunning
 
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
 
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
 
Elasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep diveElasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep dive
 
jacobs_tuuri_performance
jacobs_tuuri_performancejacobs_tuuri_performance
jacobs_tuuri_performance
 
Db2 performance tuning for dummies
Db2 performance tuning for dummiesDb2 performance tuning for dummies
Db2 performance tuning for dummies
 
Large scale sql server best practices
Large scale sql server   best practicesLarge scale sql server   best practices
Large scale sql server best practices
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Building scalable application with sql server
Building scalable application with sql serverBuilding scalable application with sql server
Building scalable application with sql server
 

Plus de smittal81

Mohan Resume
Mohan ResumeMohan Resume
Mohan Resumesmittal81
 
Mohan has completed the slide share implementation
Mohan has completed the slide share implementationMohan has completed the slide share implementation
Mohan has completed the slide share implementationsmittal81
 
Mohan has completed the slide share implementation
Mohan has completed the slide share implementationMohan has completed the slide share implementation
Mohan has completed the slide share implementationsmittal81
 
Mohan has completed the slide share implementation
Mohan has completed the slide share implementationMohan has completed the slide share implementation
Mohan has completed the slide share implementationsmittal81
 
Mohan has completed the slide share implementation
Mohan has completed the slide share implementationMohan has completed the slide share implementation
Mohan has completed the slide share implementationsmittal81
 
My attempt to post slide on slide share via API
My attempt to post slide on slide share via APIMy attempt to post slide on slide share via API
My attempt to post slide on slide share via APIsmittal81
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!smittal81
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!smittal81
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!smittal81
 

Plus de smittal81 (9)

Mohan Resume
Mohan ResumeMohan Resume
Mohan Resume
 
Mohan has completed the slide share implementation
Mohan has completed the slide share implementationMohan has completed the slide share implementation
Mohan has completed the slide share implementation
 
Mohan has completed the slide share implementation
Mohan has completed the slide share implementationMohan has completed the slide share implementation
Mohan has completed the slide share implementation
 
Mohan has completed the slide share implementation
Mohan has completed the slide share implementationMohan has completed the slide share implementation
Mohan has completed the slide share implementation
 
Mohan has completed the slide share implementation
Mohan has completed the slide share implementationMohan has completed the slide share implementation
Mohan has completed the slide share implementation
 
My attempt to post slide on slide share via API
My attempt to post slide on slide share via APIMy attempt to post slide on slide share via API
My attempt to post slide on slide share via API
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 

EXPLAIN to profile query execution plan

  • 1. Use EXPLAIN to profile the query execution plan Use Slow Query Log (always have it on!) Don’t use DISTINCT when you have or could use GROUP BY Use proper data partitions 1. For Cluster. Start thinking about Cluster *before* you need them Insert performance 1. Batch INSERT and REPLACE 2. Use LOAD DATA instead of INSERT LIMITm,n may not be as fast as it sounds Don’t use ORDER BY RAND() if you have > ~2K records Use SQL_NO_CACHE when you are SELECTing frequently updated data or large sets of data avoid wildcards at the start of LIKE queries avoid correlated subqueries and in select and where clause (try to avoid in) configparams -- no calculated comparisons -- isolate indexed columns innodb_flush_commit=0 can help slave lag ORDER BY and LIMIT work best with equalities and covered indexes isolate workloads don’t let administrative work interfere with customer performance. (ie backups) use optimistic locking, not pessimistic locking. try to use shared lock, not exclusive lock. share mode vs. FOR UPDATE use row-level instead of table-level locking for OLTP workloads Know your storage engines and what performs best for your needs, know that different ones exist. 1. use MERGE tables ARCHIVE tables for logs Optimize for data types, use consistent data types. Use PROCEDURE ANALYSE() to help determine if you need less separate text/blobs from metadata, don’t put text/blobs in results if you don’t need them if you can, compress text/blobs compress static data don’t back up static data as often derived tables (subqueries in the FROM clause) can be useful for retrieving BLOBs w/out sorting them. (self-join can speed up a query if 1st part finds the IDs and use it to fetch the rest) enable and increase the query and buffer caches if appropriate ALTER TABLE…ORDER BY can take chronological data and re-order it by a different field InnoDB ALWAYS keeps the primary key as part of each index, so do not make the primary key very large, be careful of redundant columns in an index, and this can make the query faster
  • 2. Do not duplicate indexes Utilize different storage engines on master/slave ie, if you need fulltext indexing on a table. BLACKHOLE engine and replication is much faster than FEDERATED tables for things like logs. Design sane query schemas. don’t be afraid of table joins, often they are faster than denormalization Don’t use boolean flags Use a clever key and ORDER BY instead of MAX Keep the database host as clean as possible. Do you really need a windowing system on that server? Utilize the strengths of the OS Hire a MySQL ™ Certified DBA Know that there are many consulting companies out there that can help, as well as MySQL’s Professional Services. Config variables & tips: 1. use one of the supplied config files 2. key_buffer, unix cache (leave some RAM free), per-connection variables, innodb memory variables 3. be aware of global vs. per-connection variables 4. check SHOW STATUS and SHOW VARIABLES (GLOBAL|SESSION in 5.0 and up) 5. be aware of swapping esp. with Linux, “swappiness” (bypass OS filecache for innodb data files, innodb_flush_method=O_DIRECT if possible (this is also OS specific)) 6. defragment tables, rebuild indexes, do table maintenance 7. If you use innodb_flush_txn_commit=1, use a battery-backed hardware cache write controller 8. more RAM is good so faster disk speed 9. use 64-bit architectures Know when to split a complex query and join smaller ones Debugging sucks, testing rocks! Delete small amounts at a time if you can Archive old data -- don’t be a pack-rat! 2 common engines for this are ARCHIVE tables and MERGE tables use INET_ATON and INET_NTOA for IP addresses, not char or varchar make it a habit to REVERSE() email addresses, so you can easily search domains --skip-name-resolve increasemyisam_sort_buffer_size to optimize large inserts (this is a per-connection variable) look up memory tuning parameter for on-insert caching increase temp table size in a data warehousing environment (default is 32Mb) so it doesn’t write to disk (also constrained by max_heap_table_size, default 16Mb) Normalize first, and denormalize where appropriate. Databases are not spreadsheets, even though Access really really looks like one. Then again, Access isn’t a real database In 5.1 BOOL/BIT NOT NULL type is 1 bit, in previous versions it’s 1 byte.
  • 3. A NULL data type can take more room to store than NOT NULL Choose appropriate character sets & collations -- UTF16 will store each character in 2 bytes, whether it needs it or not, latin1 is faster than UTF8. make similar queries consistent so cache is used Don’t use deprecated features Use Triggers wisely Run in SQL_MODE=STRICT to help identify warnings Turning OR on multiple index fields (<5.0) into UNION may speed things up (with LIMIT), after 5.0 the index_merge should pick stuff up. /tmpdir on battery-backed write cache consider battery-backed RAM for innodblogfiles usemin_rows and max_rows to specify approximate data size so space can be pre- allocated and reference points can be calculated. as your data grows, indexing may change (cardinality and selectivity change). Structuring may want to change. Make your schema as modular as your code. Make your code able to scale. Plan and embrace change, and get developers to do the same. pare down cron scripts create a test environment try out a few schemas and storage engines in your test environment before picking one. Use HASH indexing for indexing across columns with similar data prefixes Usemyisam_pack_keys for int data Don’t use COUNT * on Innodb tables for every search, do it a few times and/or summary tables, or if you need it for the total # of rows, use SQL_CALC_FOUND_ROWS and SELECT FOUND_ROWS() use --safe-updates for client Redundant data is redundant Use INSERT … ON DUPLICATE KEY update (INSERT IGNORE) to avoid having to SELECT usegroupwise maximum instead of subqueries be able to change your schema without ruining functionality of your code source control schema and config files for LVM innodb backups, restore to a different instance of MySQL so Innodb can roll forward usemulti_query if appropriate to reduce round-trips partition appropriately partition your database when you have real data segregate tables/databases that benefit from different configuration variables