SlideShare a Scribd company logo
Optimizando MySQL
Marcelo Altmann
Técnologo em Sistemas para Internet
MySQL DBA @ IEDR
Blogueiro - blog.marceloaltmann.com
Oracle ACE Associate - MySQL
Oracle Certified Professional , MySQL 5.6 Database Administrator
Oracle Certified Professional , MySQL 5 Database Administrator
Agenda
> Overview
> Configuração
> Índices
> Tabelas temporárias
> Identificação de queries
Overview
Overview
Fonte: http://www.oracle.com/technetwork/articles/java/mysql-acq-139875.html
Configuração
Configuração - Innodb Buffer Pool
Configuração - Innodb Buffer Pool
Configuração - Innodb Buffer Pool
Configuração - Innodb Buffer Pool
Configuração - Innodb Buffer Pool
● Monitorar: SHOW GLOBAL STATUS LIKE ‘Innodb_buffer_pool_read%’ :
○ Innodb_buffer_pool_reads - Leituras feitas direto no disco
○ Innodb_buffer_pool_read_requests - Leituras feitas na memória
● Innodb_buffer_pool_size (Padrão: 128M)
● Innodb_buffer_pool_dump_at_shutdown
● innodb_buffer_pool_load_at_startup
Configuração - transaction log (redo log)
Configuração - transaction log (redo log)
Configuração - transaction log (redo log)
Configuração - transaction log (redo log)
Configuração - transaction log (redo log)
● Monitorar: SHOW GLOBAL STATUS LIKE ‘Innodb_log_waits’
● Innodb_log_buffer_size
○ Padrão 8M - 5.5 / 5.6 / 5.7.5
○ Padrão 16M - 5.7.6
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=1
● Padrão (ACID)
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=1
● Padrão (ACID)
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=1
● Padrão (ACID)
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=1
● Padrão (ACID)
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=1
● Padrão (ACID)
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=0
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=0
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=0
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=2
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=2
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=2
Configuração - transaction log (redo log)
● Innodb_flush_log_at_trx_commit=2
Configuração
● Thread_cache_size
● Skip-name-resolve
○ root@104.10.25.210 vs root@marceloaltmann.com
Índices
Índices - Full table scan
CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1;
Índices - Full table scan
mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: city
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 4188
Extra: Using where
1 row in set (0.00 sec)
Índices - Full table scan
mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: city
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 4188
Extra: Using where
1 row in set (0.00 sec)
Índices - Left most part
ALTER TABLE city ADD KEY leftMost(CountryCode, Population, District);
mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND
Population > 1000000G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: city
type: range
possible_keys: leftMost
key: leftMost
key_len: 7
ref: NULL
rows: 13
Extra: Using index condition
1 row in set (0.00 sec)
Índices - Left most part
ALTER TABLE city ADD KEY leftMost(CountryCode, Population, District);
mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND
Population > 1000000G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: city
type: range
possible_keys: leftMost
key: leftMost
key_len: 7
ref: NULL
rows: 13
Extra: Using index condition
1 row in set (0.00 sec)
Índices - Left most part
mysql> EXPLAIN FORMAT=JSON SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000;
{
"query_block": {
"select_id": 1,
"table": {
"table_name": "city",
"access_type": "range",
"possible_keys": [
"CountryCode"
],
"key": "CountryCode",
"used_key_parts": [
"CountryCode",
"Population"
],
"key_length": "7",
"rows": 13,
"filtered": 100,
"index_condition": "((`world`.`city`.`CountryCode` = 'BRA') and (`world`.`city`.`Population` > 1000000))"
}
}
}
Índices - Covered index
ALTER TABLE city ADD KEY covered (CountryCode, Population, Name);
mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND
Population > 1000000G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: city
type: range
possible_keys: covered
key: covered
key_len: 7
ref: NULL
rows: 13
Extra: Using where; Using index
1 row in set (0.00 sec)
Índices - Covered index
ALTER TABLE city ADD KEY covered (CountryCode, Population, Name);
mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND
Population > 1000000G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: city
type: range
possible_keys: covered
key: covered
key_len: 7
ref: NULL
rows: 13
Extra: Using where; Using index
1 row in set (0.00 sec)
Tabelas temporárias
Tabelas temporárias
● GROUP BY
● UNION
● SUBQUERY + WHERE
● Memória: Memory Engine
● Disco:
○ 5.6 - MyIsam Engine
○ 5.7 - Innodb Engine
● Memory Engine:
○ Não tem suporte a campos BLOB / TEXT
● https://dev.mysql.com/doc/refman/5.6/en/internal-temporary-tables.html
Tabelas temporárias
● tmp_table_size - tamanho máximo de uma tabela temporária
● max_head_table_size - tamanho máximo de uma tabela que utiliza memory engine
● Tamanho tabela temporária:
○ Maior que tmp_table_size ou max_head_table_size = criada em disco
● Monitorar:
mysql> SHOW GLOBAL STATUS LIKE 'Created_tmp%tables';
+-------------------------+-------+
| Variable_name | Value |
+-------------------------+-------+
| Created_tmp_disk_tables | 3 |
| Created_tmp_tables | 17 |
+-------------------------+-------+
Identificação de queries
Identificação de queries
● SHOW [FULL] PROCESSLIST
● Slow query log
● performance_schema.events_statements_summary_by_digest
Identificação de queries - Processlist
● Mostra as conexões atuais e seus status
mysql> show processlist;
+----+------+-----------+-----------+---------+------+----------------+-----------------------------------------------------------------------------------------
---------+
| Id | User | Host | db | Command | Time | State | Info
|
+----+------+-----------+-----------+---------+------+----------------+-----------------------------------------------------------------------------------------
---------+
| 8 | root | localhost | employees | Query | 4 | Writing to net | SELECT MAX(salary) FROM salaries JOIN employees USING (emp_no) WHERE gender = 'M' GROUP
BY emp_no |
| 9 | root | localhost | employees | Query | 0 | init | show processlist
|
+----+------+-----------+-----------+---------+------+----------------+-----------------------------------------------------------------------------------------
---------+
2 rows in set (0.00 sec)
Identificação de queries - Slow Query
● Slow_query_log
● Long_query_time = N
Identificação de queries - Slow Query
# Time: 160908 17:38:01
# User@Host: root[root] @ localhost [] Id: 2
# Query_time: 1.127100 Lock_time: 0.000852 Rows_sent: 1000 Rows_examined: 297918
use employees;
SET timestamp=1473370681;
SELECT d.dept_name AS 'Dept', CONCAT(em.last_name, ' ', em.first_name) AS 'Manager last, first', CONCAT(e.last_name,' ',
e.first_name, ' ', t.title) AS 'Employee last, first (title)' FROM dept_manager AS dm LEFT JOIN dept_emp AS de ON de.dept_no
= dm.dept_no LEFT JOIN departments AS d ON d.dept_no = dm.dept_no LEFT JOIN employees AS e ON e.emp_no = de.emp_no LEFT JOIN
employees AS em ON em.emp_no = dm.emp_no LEFT JOIN titles AS t ON t.emp_no = e.emp_no WHERE dm.emp_no = e.emp_no AND
dept_name = 'Sales' OR dept_name = 'Marketing' AND dm.to_date >= '2012-05-07' AND t.to_date > '2012-05-07' AND de.to_date >
'2012-05-07' ORDER BY e.last_name, e.first_name limit 1000;
# Time: 160908 17:38:27
# User@Host: root[root] @ localhost [] Id: 2
# Query_time: 4.236115 Lock_time: 0.000377 Rows_sent: 179973 Rows_examined: 2366291
SET timestamp=1473370707;
SELECT MAX(salary) FROM salaries JOIN employees USING(emp_no) WHERE gender = 'M' GROUP BY emp_no;
# Time: 160908 17:38:33
# User@Host: root[root] @ localhost [] Id: 2
# Query_time: 3.268998 Lock_time: 0.000349 Rows_sent: 179973 Rows_examined: 2366291
SET timestamp=1473370713;
SELECT MAX(salary) FROM salaries JOIN employees USING(emp_no) WHERE gender = 'M' GROUP BY emp_no;
Identificação de queries - performance schema
● Ativado por padrão desde a versão 5.6.6
● DIGEST:
○ SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000;
○ SELECT Name, Population FROM city WHERE CountryCode='USA' AND Population > 5000000;
○ SELECT Name , Population FROM city WHERE CountryCode = ? AND Population > ?;
● Possibilita identificar queries :
○ Não utilizam index:
SELECT DIGEST_TEXT FROM events_statements_summary_by_digest WHERE SUM_NO_INDEX_USED > 0;
○ Usam tabelas temporárias no disco:
SELECT DIGEST_TEXT FROM events_statements_summary_by_digest WHERE SUM_CREATED_TMP_DISK_TABLES > 0;
Perguntas ?
Perguntas ?
● https://groups.google.com/group/mysqlbr
● @altmannmarcelo
● altmannmarcelo@gmail.com
● pt.planet.mysql.com
● Forum em português - http://forums.mysql.com/list.php?72

More Related Content

PDF
Efficient Pagination Using MySQL
ODP
PDF
Mnesiaで分散ノードに入門してみた
PDF
My SQL Idiosyncrasies That Bite OTN
PDF
Data Wrangling with dplyr
PPTX
망고100 보드로 놀아보자 7
PDF
Introduction to tibbles
PDF
tensorflow/keras model coding tutorial 勉強会
Efficient Pagination Using MySQL
Mnesiaで分散ノードに入門してみた
My SQL Idiosyncrasies That Bite OTN
Data Wrangling with dplyr
망고100 보드로 놀아보자 7
Introduction to tibbles
tensorflow/keras model coding tutorial 勉強会

What's hot (20)

ODP
PDF
Pre-Bootcamp introduction to Elixir
TXT
Quick reference for hql
PDF
Read data from Excel spreadsheets into R
TXT
Pop3ck sh
DOCX
Procedure To Store Database Object Size And Number Of Rows In Custom Table
PDF
Writing Readable Code with Pipes
ZIP
Ruby on Rails: Tasty Burgers
TXT
Quick reference for HBase shell commands
PDF
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
PDF
20190330 immutable data
PPTX
Super Advanced Python –act1
TXT
Bouncingballs sh
PDF
Read/Import data from flat/delimited files into R
TXT
Quick reference for solr
PDF
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
PPTX
Lecture2 mysql by okello erick
PDF
How fast ist it really? Benchmarking in practice
PDF
Explore Data using dplyr
PDF
New features in Performance Schema 5.7 in action
Pre-Bootcamp introduction to Elixir
Quick reference for hql
Read data from Excel spreadsheets into R
Pop3ck sh
Procedure To Store Database Object Size And Number Of Rows In Custom Table
Writing Readable Code with Pipes
Ruby on Rails: Tasty Burgers
Quick reference for HBase shell commands
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
20190330 immutable data
Super Advanced Python –act1
Bouncingballs sh
Read/Import data from flat/delimited files into R
Quick reference for solr
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
Lecture2 mysql by okello erick
How fast ist it really? Benchmarking in practice
Explore Data using dplyr
New features in Performance Schema 5.7 in action
Ad

Similar to Optimizando MySQL (20)

PDF
Introduction into MySQL Query Tuning
PDF
Explain2
PDF
MySQL Query tuning 101
PDF
MySQL Query And Index Tuning
PDF
Advance MySQL Training by Pratyush Majumdar
PDF
Advanced MySQL Query and Schema Tuning
PPTX
MySQL performance tuning
PDF
Webinar 2013 advanced_query_tuning
PPTX
What's New In MySQL 5.6
PPTX
Confoo 2021 - MySQL Indexes & Histograms
PPTX
MySQL Indexes
PDF
Advanced MySQL Query Tuning
PDF
Explaining the MySQL Explain
PDF
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
PDF
MySQL Indexes and Histograms - RMOUG Training Days 2022
PDF
MySQL Query Optimisation 101
PDF
Introduction into MySQL Query Tuning for Dev[Op]s
PDF
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
PPTX
Optimizing MySQL queries
PDF
Advanced MySQL Query Optimizations
Introduction into MySQL Query Tuning
Explain2
MySQL Query tuning 101
MySQL Query And Index Tuning
Advance MySQL Training by Pratyush Majumdar
Advanced MySQL Query and Schema Tuning
MySQL performance tuning
Webinar 2013 advanced_query_tuning
What's New In MySQL 5.6
Confoo 2021 - MySQL Indexes & Histograms
MySQL Indexes
Advanced MySQL Query Tuning
Explaining the MySQL Explain
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
MySQL Indexes and Histograms - RMOUG Training Days 2022
MySQL Query Optimisation 101
Introduction into MySQL Query Tuning for Dev[Op]s
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Optimizing MySQL queries
Advanced MySQL Query Optimizations
Ad

More from Marcelo Altmann (14)

PPTX
Backup Online no MySQL com Percona Xtrabackup
PPTX
Percona XtraBackup - New Features and Improvements
PPTX
Troubleshooting MySQL from a MySQL Developer Perspective
PDF
Backup para MySQL
PPTX
GDB e Análise de Bugs
PDF
Percona University - ProxySQL para MySQL
PPTX
DB Floripa - ProxySQL para MySQL
PPTX
Percona Xtrabackup Best Practices
PPTX
MySQL Backup Best Practices and Case Study- .ie Continuous Restore Process
PPTX
A Percona Support Engineer Walkthrough on pt-stalk
PPTX
MysQL melhores práticas de seguranca
PPTX
ProxySQL para mysql
PPTX
MySQL - Melhores práticas de replicação de dados
PPTX
Percona Live London 2014 - MySQL Backup Strategy @ IEDR
Backup Online no MySQL com Percona Xtrabackup
Percona XtraBackup - New Features and Improvements
Troubleshooting MySQL from a MySQL Developer Perspective
Backup para MySQL
GDB e Análise de Bugs
Percona University - ProxySQL para MySQL
DB Floripa - ProxySQL para MySQL
Percona Xtrabackup Best Practices
MySQL Backup Best Practices and Case Study- .ie Continuous Restore Process
A Percona Support Engineer Walkthrough on pt-stalk
MysQL melhores práticas de seguranca
ProxySQL para mysql
MySQL - Melhores práticas de replicação de dados
Percona Live London 2014 - MySQL Backup Strategy @ IEDR

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Spectroscopy.pptx food analysis technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
cuic standard and advanced reporting.pdf
PPTX
Cloud computing and distributed systems.
PDF
Approach and Philosophy of On baking technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
MYSQL Presentation for SQL database connectivity
Spectral efficient network and resource selection model in 5G networks
Spectroscopy.pptx food analysis technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Encapsulation_ Review paper, used for researhc scholars
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Chapter 3 Spatial Domain Image Processing.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Weekly Chronicles - August'25 Week I
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Mobile App Security Testing_ A Comprehensive Guide.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Review of recent advances in non-invasive hemoglobin estimation
cuic standard and advanced reporting.pdf
Cloud computing and distributed systems.
Approach and Philosophy of On baking technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy

Optimizando MySQL

  • 2. Marcelo Altmann Técnologo em Sistemas para Internet MySQL DBA @ IEDR Blogueiro - blog.marceloaltmann.com Oracle ACE Associate - MySQL Oracle Certified Professional , MySQL 5.6 Database Administrator Oracle Certified Professional , MySQL 5 Database Administrator
  • 3. Agenda > Overview > Configuração > Índices > Tabelas temporárias > Identificação de queries
  • 10. Configuração - Innodb Buffer Pool
  • 11. Configuração - Innodb Buffer Pool ● Monitorar: SHOW GLOBAL STATUS LIKE ‘Innodb_buffer_pool_read%’ : ○ Innodb_buffer_pool_reads - Leituras feitas direto no disco ○ Innodb_buffer_pool_read_requests - Leituras feitas na memória ● Innodb_buffer_pool_size (Padrão: 128M) ● Innodb_buffer_pool_dump_at_shutdown ● innodb_buffer_pool_load_at_startup
  • 16. Configuração - transaction log (redo log) ● Monitorar: SHOW GLOBAL STATUS LIKE ‘Innodb_log_waits’ ● Innodb_log_buffer_size ○ Padrão 8M - 5.5 / 5.6 / 5.7.5 ○ Padrão 16M - 5.7.6
  • 17. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=1 ● Padrão (ACID)
  • 18. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=1 ● Padrão (ACID)
  • 19. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=1 ● Padrão (ACID)
  • 20. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=1 ● Padrão (ACID)
  • 21. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=1 ● Padrão (ACID)
  • 22. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=0
  • 23. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=0
  • 24. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=0
  • 25. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=2
  • 26. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=2
  • 27. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=2
  • 28. Configuração - transaction log (redo log) ● Innodb_flush_log_at_trx_commit=2
  • 29. Configuração ● Thread_cache_size ● Skip-name-resolve ○ root@104.10.25.210 vs root@marceloaltmann.com
  • 31. Índices - Full table scan CREATE TABLE `city` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `Name` char(35) NOT NULL DEFAULT '', `CountryCode` char(3) NOT NULL DEFAULT '', `District` char(20) NOT NULL DEFAULT '', `Population` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1;
  • 32. Índices - Full table scan mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: city type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 4188 Extra: Using where 1 row in set (0.00 sec)
  • 33. Índices - Full table scan mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: city type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 4188 Extra: Using where 1 row in set (0.00 sec)
  • 34. Índices - Left most part ALTER TABLE city ADD KEY leftMost(CountryCode, Population, District); mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: city type: range possible_keys: leftMost key: leftMost key_len: 7 ref: NULL rows: 13 Extra: Using index condition 1 row in set (0.00 sec)
  • 35. Índices - Left most part ALTER TABLE city ADD KEY leftMost(CountryCode, Population, District); mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: city type: range possible_keys: leftMost key: leftMost key_len: 7 ref: NULL rows: 13 Extra: Using index condition 1 row in set (0.00 sec)
  • 36. Índices - Left most part mysql> EXPLAIN FORMAT=JSON SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000; { "query_block": { "select_id": 1, "table": { "table_name": "city", "access_type": "range", "possible_keys": [ "CountryCode" ], "key": "CountryCode", "used_key_parts": [ "CountryCode", "Population" ], "key_length": "7", "rows": 13, "filtered": 100, "index_condition": "((`world`.`city`.`CountryCode` = 'BRA') and (`world`.`city`.`Population` > 1000000))" } } }
  • 37. Índices - Covered index ALTER TABLE city ADD KEY covered (CountryCode, Population, Name); mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: city type: range possible_keys: covered key: covered key_len: 7 ref: NULL rows: 13 Extra: Using where; Using index 1 row in set (0.00 sec)
  • 38. Índices - Covered index ALTER TABLE city ADD KEY covered (CountryCode, Population, Name); mysql> EXPLAIN SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: city type: range possible_keys: covered key: covered key_len: 7 ref: NULL rows: 13 Extra: Using where; Using index 1 row in set (0.00 sec)
  • 40. Tabelas temporárias ● GROUP BY ● UNION ● SUBQUERY + WHERE ● Memória: Memory Engine ● Disco: ○ 5.6 - MyIsam Engine ○ 5.7 - Innodb Engine ● Memory Engine: ○ Não tem suporte a campos BLOB / TEXT ● https://dev.mysql.com/doc/refman/5.6/en/internal-temporary-tables.html
  • 41. Tabelas temporárias ● tmp_table_size - tamanho máximo de uma tabela temporária ● max_head_table_size - tamanho máximo de uma tabela que utiliza memory engine ● Tamanho tabela temporária: ○ Maior que tmp_table_size ou max_head_table_size = criada em disco ● Monitorar: mysql> SHOW GLOBAL STATUS LIKE 'Created_tmp%tables'; +-------------------------+-------+ | Variable_name | Value | +-------------------------+-------+ | Created_tmp_disk_tables | 3 | | Created_tmp_tables | 17 | +-------------------------+-------+
  • 43. Identificação de queries ● SHOW [FULL] PROCESSLIST ● Slow query log ● performance_schema.events_statements_summary_by_digest
  • 44. Identificação de queries - Processlist ● Mostra as conexões atuais e seus status mysql> show processlist; +----+------+-----------+-----------+---------+------+----------------+----------------------------------------------------------------------------------------- ---------+ | Id | User | Host | db | Command | Time | State | Info | +----+------+-----------+-----------+---------+------+----------------+----------------------------------------------------------------------------------------- ---------+ | 8 | root | localhost | employees | Query | 4 | Writing to net | SELECT MAX(salary) FROM salaries JOIN employees USING (emp_no) WHERE gender = 'M' GROUP BY emp_no | | 9 | root | localhost | employees | Query | 0 | init | show processlist | +----+------+-----------+-----------+---------+------+----------------+----------------------------------------------------------------------------------------- ---------+ 2 rows in set (0.00 sec)
  • 45. Identificação de queries - Slow Query ● Slow_query_log ● Long_query_time = N
  • 46. Identificação de queries - Slow Query # Time: 160908 17:38:01 # User@Host: root[root] @ localhost [] Id: 2 # Query_time: 1.127100 Lock_time: 0.000852 Rows_sent: 1000 Rows_examined: 297918 use employees; SET timestamp=1473370681; SELECT d.dept_name AS 'Dept', CONCAT(em.last_name, ' ', em.first_name) AS 'Manager last, first', CONCAT(e.last_name,' ', e.first_name, ' ', t.title) AS 'Employee last, first (title)' FROM dept_manager AS dm LEFT JOIN dept_emp AS de ON de.dept_no = dm.dept_no LEFT JOIN departments AS d ON d.dept_no = dm.dept_no LEFT JOIN employees AS e ON e.emp_no = de.emp_no LEFT JOIN employees AS em ON em.emp_no = dm.emp_no LEFT JOIN titles AS t ON t.emp_no = e.emp_no WHERE dm.emp_no = e.emp_no AND dept_name = 'Sales' OR dept_name = 'Marketing' AND dm.to_date >= '2012-05-07' AND t.to_date > '2012-05-07' AND de.to_date > '2012-05-07' ORDER BY e.last_name, e.first_name limit 1000; # Time: 160908 17:38:27 # User@Host: root[root] @ localhost [] Id: 2 # Query_time: 4.236115 Lock_time: 0.000377 Rows_sent: 179973 Rows_examined: 2366291 SET timestamp=1473370707; SELECT MAX(salary) FROM salaries JOIN employees USING(emp_no) WHERE gender = 'M' GROUP BY emp_no; # Time: 160908 17:38:33 # User@Host: root[root] @ localhost [] Id: 2 # Query_time: 3.268998 Lock_time: 0.000349 Rows_sent: 179973 Rows_examined: 2366291 SET timestamp=1473370713; SELECT MAX(salary) FROM salaries JOIN employees USING(emp_no) WHERE gender = 'M' GROUP BY emp_no;
  • 47. Identificação de queries - performance schema ● Ativado por padrão desde a versão 5.6.6 ● DIGEST: ○ SELECT Name, Population FROM city WHERE CountryCode='BRA' AND Population > 1000000; ○ SELECT Name, Population FROM city WHERE CountryCode='USA' AND Population > 5000000; ○ SELECT Name , Population FROM city WHERE CountryCode = ? AND Population > ?; ● Possibilita identificar queries : ○ Não utilizam index: SELECT DIGEST_TEXT FROM events_statements_summary_by_digest WHERE SUM_NO_INDEX_USED > 0; ○ Usam tabelas temporárias no disco: SELECT DIGEST_TEXT FROM events_statements_summary_by_digest WHERE SUM_CREATED_TMP_DISK_TABLES > 0;
  • 49. Perguntas ? ● https://groups.google.com/group/mysqlbr ● @altmannmarcelo ● altmannmarcelo@gmail.com ● pt.planet.mysql.com ● Forum em português - http://forums.mysql.com/list.php?72