SlideShare a Scribd company logo
1 of 50
OPTIMIZING MYSQL QUERIES
KhoaHD
OVERVIEW
• Optimization Overview
• Understanding the Query Execution
• Using explain
• Optimizing Specific Types of Queries
• Indexing
• Partitioning
• Demo partitioning
1. OPTIMIZATION OVERVIEW
1.1 Optimizing at the Database Level
• tables
• indexes
• storage engine
• locking strategy
• Are all memory areas used for caching sized correctly?
1. OPTIMIZATION OVERVIEW
1.2 Optimizing at the Hardware Level
• Disk seeks
• Disk reading and writing
• CPU cycles
• Memory bandwidth
2. UNDERSTANDING THE QUERY EXECUTION
2. UNDERSTANDING THE QUERY EXECUTION
1. The client sends the SQL statement to the server.
2. The server checks the query cache. If there’s a hit, it returns the stored result from
the cache; otherwise, it passes the SQL statement to the next step.
3. The server parses, preprocesses, and optimizes the SQL into a query execution
plan.
4. The query execution engine executes the plan by making calls to the storage
engine
API.
5. The server sends the result to the client.
3. USING EXPLAIN
3.1 Usage:
• EXPLAIN is used to obtain a query execution plan.
• EXPLAIN is useful for examining queries involving
partitioned tables.
• EXPLAIN works with SELECT, DELETE, INSERT, REPLACE,
and UPDATE statements.
3. USING EXPLAIN
3.1 Usage:
3. USING EXPLAIN
3.3 What should I care about?
3. USING EXPLAIN
3.3 What should I care about?
• Partitions
• Extra
• Type
3. USING EXPLAIN
3.3 What should I care about?
Partitions: show which partitions were used.
3. USING EXPLAIN
3.3 What should I care about?
Extra
• Using filesort
• Using temporary
• Using index
• Using index for group-by
• …
3. USING EXPLAIN
3.3 What should I care about?
Extra
• Using filesort: MySQL must do an extra pass to find out
how to retrieve the rows in sorted order. The sort is done
by going through all rows according to the join type and
storing the sort key and pointer to the row for all rows that
match the WHERE clause. The keys then are sorted and the
rows are retrieved in sorted order.
3. USING EXPLAIN
3.3 What should I care about?
Extra
• Using temporary: To resolve the query, MySQL needs to
create a temporary table to hold the result. This typically
happens if the query contains GROUP BY and ORDER BY
clauses that list columns differently.
3. USING EXPLAIN
3.3 What should I care about?
Extra
• Using index: The column information is retrieved from the
table using only information in the index tree without
having to do an additional seek to read the actual row. This
strategy can be used when the query uses only columns
that are part of a single index.
3. USING EXPLAIN
3.3 What should I care about?
Extra
• Using index for group-by: Similar to the Using index table
access method, Using index for group-by indicates that
MySQL found an index that can be used to retrieve all
columns of a GROUP BY or DISTINCT query without any
extra disk access to the actual table. Additionally, the index
is used in the most efficient way so that for each group,
only a few index entries are read.
3. USING EXPLAIN
3.3 What should I care about?
Type: describes how tables are joined. The following list
describes the join types, ordered from the best type to the
worst:
• System
• Const
• Eq_ref
• Ref
• Fulltext
3. USING EXPLAIN
3.3 What should I care about?
Type:
• Ref_or_null
• Index_merge
• Unique_subquery
• Index_subquery
• Range
• Index
• All
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.1 Count()
• SELECT COUNT(*) FROM world.City WHERE ID > 5;
• If you examine this query with SHOW STATUS, you’ll see
that it scans 4,079 rows. If you negate the conditions and
subtract the number of cities whose IDs are less than or
equal to 5 from the total number of cities, you can reduce
that to five rows:
• SELECT (SELECT COUNT(*) FROM world.City) - COUNT(*)
-> FROM world.City WHERE ID <= 5;
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.2 LIMIT and OFFSET
• One simple technique to improve efficiency is to do the offset on a covering index,
rather than the full rows. You can then join the result to the full row and retrieve the
additional columns you need. This can be much more efficient. Consider the following
query:
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.3 Group by
• The most general way to satisfy a GROUP BY clause is to scan the whole table and
create a new temporary table where all rows from each group are consecutive, and
then use this temporary table to discover groups and apply aggregate functions (if
any). In some cases, MySQL is able to do much better than that and to avoid
creation of temporary tables by using index access.
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.3 Group by
Loose Index Scan
If loose index scan is applicable to a query, the EXPLAIN output shows Using index for
group-by in the Extra column.
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.3 Group by
Loose Index Scan
Condition:
• The query is over a single table.
• The GROUP BY names only columns that form a leftmost prefix of the index and no
other columns. (If, instead of GROUP BY, the query has a DISTINCT clause, all distinct
attributes refer to columns that form a leftmost prefix of the index.)
• The only aggregate functions used in the select list (if any) are MIN() and MAX(), and
all of them refer to the same column. The column must be in the index and must
immediately follow the columns in the GROUP BY.
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.3 Group by
Loose Index Scan
Condition:
• Any other parts of the index than those from the GROUP BY referenced in the query
must be constants (that is, they must be referenced in equalities with constants),
except for the argument of MIN() or MAX() functions.
• For columns in the index, full column values must be indexed, not just a prefix. For
example, with c1 VARCHAR(20), INDEX (c1(10)), the index cannot be used for loose
index scan.
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.3 Group by
Loose Index Scan
Example: index(c1, c2, c3)
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.3 Group by
Loose Index Scan
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.3 Group by
Tight Index Scan
4. OPTIMIZING SPECIFIC TYPES OF QUERIES
4.3 UNION
• UNION ALL is much faster than UNION
• Move the WHERE inside each subquery
Example:
• Slow:
(SELECT type, release FROM short_sleeve)
UNION
(SELECT type, release FROM long_sleeve);
WHERE release >=2013;
• Fast:
(SELECT type, release FROM short_sleeve WHERE release >=2013)
UNION
(SELECT type, release FROM long_sleeve WHERE release >=2013);
5. INDEXING
5.1 B-Tree
• When people talk about an index without mentioning a
type, they’re probably referring
to a B-Tree index
• A B-Tree index speeds up data access because the storage
engine doesn’t have to scan
the whole table to find the desired data. Instead, it starts
at the root node (not shown
in this figure).
5. INDEXING
5.1 B-Tree
5. INDEXING
5.1 B-Tree
• Consider InnoDB whose page size is 16KB and suppose we have an index on a integer
column of size 4bytes, so a node can contain at most 16 * 1024 / 4 = 4096 keys, and a
node can have at most 4097 children.
• So for a B+tree of height 1, the root node has 4096 keys and the nodes at height 1
(the leaf nodes) have 4096 * 4097 = 16781312 key values.
5. INDEXING
5.1 B-Tree
5. INDEXING
5.1 B-Tree
Benefits:
• Match the full value: find a person named Cuba Allen who was born
on 1960-01-01.
• Match a leftmost prefix: find all people with the last name Allen
• Match a column prefix: all people whose last names begin with J
• Match a range of values: find people whose last names are between Allen and
Barrymore
• Match one part exactly and match a range on another part: find everyone whose last
name is Allen and whose first name starts with the letter K (Kim, Karl, etc.)
5. INDEXING
5.1 B-Tree
Limits:
• They are not useful if the lookup does not start from the leftmost side of the
indexed columns.
• You can’t skip columns in the index.
5. INDEXING
5.2 Hash indexes
A hash index is built on a hash table and is useful only for exact lookups that use
every column in the index. For each row, the storage engine computes a hash
code of the indexed columns, which is a small value that will probably differ
from the hash codes computed for other rows with different key values. It stores
the hash codes in the index and stores a pointer to each row in a hash table.
5. INDEXING
5.2 Hash indexes
5. INDEXING
5.2 Hash indexes
Limits:
• MySQL can’t use the values in the index to avoid reading the rows
• can’t use hash indexes for sorting
• don’t support partial key matching
• support only equality comparisons that use the =, IN(), and <=>
operators
• When there are collisions (multiple values with the same hash): slow
5. INDEXING
5.3 Indexing Strategies for High Performance
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.
SELECT actor_id FROM sakila.actor WHERE actor_id + 1 = 5;
• Here’s another example of a common mistake:
mysql> SELECT ... WHERE TO_DAYS(CURRENT_DATE) - TO_DAYS(date_col) <= 10;
5. INDEXING
5.3 Indexing Strategies for High Performance
Prefix Indexes and Index Selectivity
• Sometimes you need to index very long character columns, which makes your
indexes large and slow. The trick is to choose a prefix that’s long enough to give good
selectivity, but short enough to save space.
5. INDEXING
5.3 Indexing Strategies for High Performance
Choosing a Good Column Order
• place the most selective columns first in the index.
• Let’s use the following query as an example:
SELECT * FROM payment WHERE staff_id = 2 AND customer_id = 584;
• index on (staff_id, customer_id) OR (customer_id , staff_id) ???
5. INDEXING
5.3 Indexing Strategies for High Performance
Choosing a Good Column Order
5. INDEXING
5.3 Indexing Strategies for High Performance
Covering Indexes
• MySQL can also use an index to retrieve a column’s data, so it doesn’t have to read
the row at all. After all, the index’s leaf nodes contain the values they index;
• MySQL can use only B-Tree indexes to cover queries.
• The general rule is to choose the columns for filtering first (WHERE clause with
equality conditions), then sorting/grouping (GROUP BY and ORDER BY clauses) and
finally the data projection (SELECT clause).
5. INDEXING
5.3 Indexing Strategies for High Performance
Covering Indexes
5. INDEXING
5.3 Indexing Strategies for High Performance
Using Index Scans for Sorts
MySQL has two ways to produce ordered results: it can use a sort operation, or it can
scan an index in order. You can tell when MySQL plans to scan an index by looking for
“index” in the type column in EXPLAIN.
5. INDEXING
5.3 Indexing Strategies for High Performance
Using Index Scans for Sorts
Index on (rental_date,
inventory_id,
Customer_id)
5. INDEXING
5.3 Indexing Strategies for High Performance
Using Index Scans for Sorts
Index on (rental_date, inventory_id, customer_id)
5. INDEXING
5.3 Indexing Strategies for High Performance
Using Index Scans for Sorts
Index on
(rental_date,
inventory_id,
Customer_id)
6. PARTITIONING
6.1 scenarios:
• When the table is much too big to fit in memory, or when you have “hot” rows at the
end of a table that has lots of historical data.
• Partitioned data is easier to maintain than nonpartitioned data. For example, it’s easier
to discard old data by dropping an entire partition, which you can do quickly. You can
also optimize, check, and repair individual partitions.
• If you really need to, you can back up and restore individual partitions, which is very
helpful with extremely large datasets.
6. PARTITIONING
6.2 How Partitioning Works:
When you query a partitioned table, the partitioning layer opens and locks all of the
underlying partitions, the query optimizer determines whether any of the partitions can
be ignored (pruned), and then the partitioning layer forwards the handler API calls to
the storage engine that manages the partitions.
6. PARTITIONING
6.3 Types of Partitioning:
• MySQL supports several types of partitioning. The most common type we’ve seen
used is range partitioning.

More Related Content

What's hot

DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCAndy Butland
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQLJoel Brewer
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query OptimizationMongoDB
 
High Performance Systems in Go - GopherCon 2014
High Performance Systems in Go - GopherCon 2014High Performance Systems in Go - GopherCon 2014
High Performance Systems in Go - GopherCon 2014Derek Collison
 
Building Open Source Identity Management with FreeIPA
Building Open Source Identity Management with FreeIPABuilding Open Source Identity Management with FreeIPA
Building Open Source Identity Management with FreeIPALDAPCon
 
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 EditionGoing Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 EditionSoroush Dalili
 
Introduction to Sharding
Introduction to ShardingIntroduction to Sharding
Introduction to ShardingMongoDB
 
EKS에서 Opentelemetry로 코드실행 모니터링하기 - 신재현 (인덴트코퍼레이션) :: AWS Community Day Online...
EKS에서 Opentelemetry로 코드실행 모니터링하기 - 신재현 (인덴트코퍼레이션) :: AWS Community Day Online...EKS에서 Opentelemetry로 코드실행 모니터링하기 - 신재현 (인덴트코퍼레이션) :: AWS Community Day Online...
EKS에서 Opentelemetry로 코드실행 모니터링하기 - 신재현 (인덴트코퍼레이션) :: AWS Community Day Online...AWSKRUG - AWS한국사용자모임
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An IntroductionSmita Prasad
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourSoroush Dalili
 
MongoDB World 2019: The Sights (and Smells) of a Bad Query
MongoDB World 2019: The Sights (and Smells) of a Bad QueryMongoDB World 2019: The Sights (and Smells) of a Bad Query
MongoDB World 2019: The Sights (and Smells) of a Bad QueryMongoDB
 
Advanced Percona XtraDB Cluster in a nutshell... la suite
Advanced Percona XtraDB Cluster in a nutshell... la suiteAdvanced Percona XtraDB Cluster in a nutshell... la suite
Advanced Percona XtraDB Cluster in a nutshell... la suiteKenny Gryp
 
MongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDBMongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDBMongoDB
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performancejkeriaki
 
"Certified Kubernetes Administrator Exam – how it was" by Andrii Fedenishin
"Certified Kubernetes Administrator Exam – how it was" by Andrii Fedenishin"Certified Kubernetes Administrator Exam – how it was" by Andrii Fedenishin
"Certified Kubernetes Administrator Exam – how it was" by Andrii FedenishinKatherine Golovinova
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index CookbookMYXPLAIN
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvCodelyTV
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index TuningManikanda kumar
 

What's hot (20)

DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
High Performance Systems in Go - GopherCon 2014
High Performance Systems in Go - GopherCon 2014High Performance Systems in Go - GopherCon 2014
High Performance Systems in Go - GopherCon 2014
 
Building Open Source Identity Management with FreeIPA
Building Open Source Identity Management with FreeIPABuilding Open Source Identity Management with FreeIPA
Building Open Source Identity Management with FreeIPA
 
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 EditionGoing Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
 
Introduction to Sharding
Introduction to ShardingIntroduction to Sharding
Introduction to Sharding
 
EKS에서 Opentelemetry로 코드실행 모니터링하기 - 신재현 (인덴트코퍼레이션) :: AWS Community Day Online...
EKS에서 Opentelemetry로 코드실행 모니터링하기 - 신재현 (인덴트코퍼레이션) :: AWS Community Day Online...EKS에서 Opentelemetry로 코드실행 모니터링하기 - 신재현 (인덴트코퍼레이션) :: AWS Community Day Online...
EKS에서 Opentelemetry로 코드실행 모니터링하기 - 신재현 (인덴트코퍼레이션) :: AWS Community Day Online...
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An Introduction
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
 
MongoDB World 2019: The Sights (and Smells) of a Bad Query
MongoDB World 2019: The Sights (and Smells) of a Bad QueryMongoDB World 2019: The Sights (and Smells) of a Bad Query
MongoDB World 2019: The Sights (and Smells) of a Bad Query
 
Advanced Percona XtraDB Cluster in a nutshell... la suite
Advanced Percona XtraDB Cluster in a nutshell... la suiteAdvanced Percona XtraDB Cluster in a nutshell... la suite
Advanced Percona XtraDB Cluster in a nutshell... la suite
 
Get to know PostgreSQL!
Get to know PostgreSQL!Get to know PostgreSQL!
Get to know PostgreSQL!
 
MongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDBMongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDB
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
 
"Certified Kubernetes Administrator Exam – how it was" by Andrii Fedenishin
"Certified Kubernetes Administrator Exam – how it was" by Andrii Fedenishin"Certified Kubernetes Administrator Exam – how it was" by Andrii Fedenishin
"Certified Kubernetes Administrator Exam – how it was" by Andrii Fedenishin
 
Load Data Fast!
Load Data Fast!Load Data Fast!
Load Data Fast!
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytv
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 

Similar to Optimizing MySQL queries

02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-dbuncleRhyme
 
Amazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Web Services
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL ServerRajesh Gunasundaram
 
How oracle query works (The SQL Optimizers)
How oracle query works (The SQL Optimizers)How oracle query works (The SQL Optimizers)
How oracle query works (The SQL Optimizers)Hosein Zare
 
Guide To Mastering The MySQL Query Execution Plan
Guide To Mastering The MySQL Query Execution PlanGuide To Mastering The MySQL Query Execution Plan
Guide To Mastering The MySQL Query Execution PlanOptimiz DBA
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysisRiteshkiit
 
Optimized cluster index generation
Optimized cluster index generationOptimized cluster index generation
Optimized cluster index generationRutvik Pensionwar
 
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)Ontico
 
Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1Techglyphs
 
Tech Jam 01 - Database Querying
Tech Jam 01 - Database QueryingTech Jam 01 - Database Querying
Tech Jam 01 - Database QueryingRodger Oates
 
Db2 sql tuning and bmc catalog manager
Db2 sql tuning and bmc catalog manager Db2 sql tuning and bmc catalog manager
Db2 sql tuning and bmc catalog manager Krishan Singh
 
Goldilocks and the Three MySQL Queries
Goldilocks and the Three MySQL QueriesGoldilocks and the Three MySQL Queries
Goldilocks and the Three MySQL QueriesDave Stokes
 
Introduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]sIntroduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]sSveta Smirnova
 
MySQL: Know more about open Source Database
MySQL: Know more about open Source DatabaseMySQL: Know more about open Source Database
MySQL: Know more about open Source DatabaseMahesh Salaria
 

Similar to Optimizing MySQL queries (20)

Mysql Optimization
Mysql OptimizationMysql Optimization
Mysql Optimization
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
 
Amazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and Optimization
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL Server
 
How oracle query works (The SQL Optimizers)
How oracle query works (The SQL Optimizers)How oracle query works (The SQL Optimizers)
How oracle query works (The SQL Optimizers)
 
Guide To Mastering The MySQL Query Execution Plan
Guide To Mastering The MySQL Query Execution PlanGuide To Mastering The MySQL Query Execution Plan
Guide To Mastering The MySQL Query Execution Plan
 
Excel Tips 101
Excel Tips 101Excel Tips 101
Excel Tips 101
 
Excel tips
Excel tipsExcel tips
Excel tips
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysis
 
Optimized cluster index generation
Optimized cluster index generationOptimized cluster index generation
Optimized cluster index generation
 
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
 
Excel Tips.pptx
Excel Tips.pptxExcel Tips.pptx
Excel Tips.pptx
 
Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1
 
Sql performance tuning
Sql performance tuningSql performance tuning
Sql performance tuning
 
Tech Jam 01 - Database Querying
Tech Jam 01 - Database QueryingTech Jam 01 - Database Querying
Tech Jam 01 - Database Querying
 
Db2 sql tuning and bmc catalog manager
Db2 sql tuning and bmc catalog manager Db2 sql tuning and bmc catalog manager
Db2 sql tuning and bmc catalog manager
 
Goldilocks and the Three MySQL Queries
Goldilocks and the Three MySQL QueriesGoldilocks and the Three MySQL Queries
Goldilocks and the Three MySQL Queries
 
Introduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]sIntroduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]s
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sql
 
MySQL: Know more about open Source Database
MySQL: Know more about open Source DatabaseMySQL: Know more about open Source Database
MySQL: Know more about open Source Database
 

More from GMO-Z.com Vietnam Lab Center

高負荷に耐えうるWebApplication Serverの作り方
高負荷に耐えうるWebApplication Serverの作り方高負荷に耐えうるWebApplication Serverの作り方
高負荷に耐えうるWebApplication Serverの作り方GMO-Z.com Vietnam Lab Center
 
Phương pháp và chiến lược đối ứng tải trong Web Application Server
Phương pháp và chiến lược đối ứng tải trong Web Application ServerPhương pháp và chiến lược đối ứng tải trong Web Application Server
Phương pháp và chiến lược đối ứng tải trong Web Application ServerGMO-Z.com Vietnam Lab Center
 
Ứng dụng NLP vào việc xác định ý muốn người dùng (Intent Detection) và sửa lỗ...
Ứng dụng NLP vào việc xác định ý muốn người dùng (Intent Detection) và sửa lỗ...Ứng dụng NLP vào việc xác định ý muốn người dùng (Intent Detection) và sửa lỗ...
Ứng dụng NLP vào việc xác định ý muốn người dùng (Intent Detection) và sửa lỗ...GMO-Z.com Vietnam Lab Center
 
Tìm hiểu và triển khai ứng dụng Web với Kubernetes
Tìm hiểu và triển khai ứng dụng Web với KubernetesTìm hiểu và triển khai ứng dụng Web với Kubernetes
Tìm hiểu và triển khai ứng dụng Web với KubernetesGMO-Z.com Vietnam Lab Center
 
Xây dựng hệ thống quản lý sân bóng sử dụng Yii Framework
Xây dựng hệ thống quản lý sân bóng sử dụng Yii FrameworkXây dựng hệ thống quản lý sân bóng sử dụng Yii Framework
Xây dựng hệ thống quản lý sân bóng sử dụng Yii FrameworkGMO-Z.com Vietnam Lab Center
 
Nhận biết giao dịch lừa đảo sử dụng học máy
Nhận biết giao dịch lừa đảo sử dụng học máyNhận biết giao dịch lừa đảo sử dụng học máy
Nhận biết giao dịch lừa đảo sử dụng học máyGMO-Z.com Vietnam Lab Center
 
Hệ thống giám sát nhận diện khuôn mặt
Hệ thống giám sát nhận diện khuôn mặtHệ thống giám sát nhận diện khuôn mặt
Hệ thống giám sát nhận diện khuôn mặtGMO-Z.com Vietnam Lab Center
 
Blockchain & Smart Contract - Bắt đầu như thế nào và các ứng dụng
Blockchain & Smart Contract - Bắt đầu như thế nào và các ứng dụngBlockchain & Smart Contract - Bắt đầu như thế nào và các ứng dụng
Blockchain & Smart Contract - Bắt đầu như thế nào và các ứng dụngGMO-Z.com Vietnam Lab Center
 
Giới thiệu docker và ứng dụng trong ci-cd
Giới thiệu docker và ứng dụng trong ci-cdGiới thiệu docker và ứng dụng trong ci-cd
Giới thiệu docker và ứng dụng trong ci-cdGMO-Z.com Vietnam Lab Center
 
Tài liệu giới thiệu công ty GMO-Z.com Vietnam Lab Center
Tài liệu giới thiệu công ty GMO-Z.com Vietnam Lab CenterTài liệu giới thiệu công ty GMO-Z.com Vietnam Lab Center
Tài liệu giới thiệu công ty GMO-Z.com Vietnam Lab CenterGMO-Z.com Vietnam Lab Center
 
Create android app can send SMS and Email by React Natice
Create android app can send SMS and Email by React NaticeCreate android app can send SMS and Email by React Natice
Create android app can send SMS and Email by React NaticeGMO-Z.com Vietnam Lab Center
 

More from GMO-Z.com Vietnam Lab Center (20)

高負荷に耐えうるWebApplication Serverの作り方
高負荷に耐えうるWebApplication Serverの作り方高負荷に耐えうるWebApplication Serverの作り方
高負荷に耐えうるWebApplication Serverの作り方
 
Phương pháp và chiến lược đối ứng tải trong Web Application Server
Phương pháp và chiến lược đối ứng tải trong Web Application ServerPhương pháp và chiến lược đối ứng tải trong Web Application Server
Phương pháp và chiến lược đối ứng tải trong Web Application Server
 
Ứng dụng NLP vào việc xác định ý muốn người dùng (Intent Detection) và sửa lỗ...
Ứng dụng NLP vào việc xác định ý muốn người dùng (Intent Detection) và sửa lỗ...Ứng dụng NLP vào việc xác định ý muốn người dùng (Intent Detection) và sửa lỗ...
Ứng dụng NLP vào việc xác định ý muốn người dùng (Intent Detection) và sửa lỗ...
 
Tìm hiểu và triển khai ứng dụng Web với Kubernetes
Tìm hiểu và triển khai ứng dụng Web với KubernetesTìm hiểu và triển khai ứng dụng Web với Kubernetes
Tìm hiểu và triển khai ứng dụng Web với Kubernetes
 
Xây dựng hệ thống quản lý sân bóng sử dụng Yii Framework
Xây dựng hệ thống quản lý sân bóng sử dụng Yii FrameworkXây dựng hệ thống quản lý sân bóng sử dụng Yii Framework
Xây dựng hệ thống quản lý sân bóng sử dụng Yii Framework
 
Nhận biết giao dịch lừa đảo sử dụng học máy
Nhận biết giao dịch lừa đảo sử dụng học máyNhận biết giao dịch lừa đảo sử dụng học máy
Nhận biết giao dịch lừa đảo sử dụng học máy
 
Hệ thống giám sát nhận diện khuôn mặt
Hệ thống giám sát nhận diện khuôn mặtHệ thống giám sát nhận diện khuôn mặt
Hệ thống giám sát nhận diện khuôn mặt
 
Image Style Transfer
Image Style TransferImage Style Transfer
Image Style Transfer
 
Surveillance on slam technology
Surveillance on slam technologySurveillance on slam technology
Surveillance on slam technology
 
Blockchain & Smart Contract - Bắt đầu như thế nào và các ứng dụng
Blockchain & Smart Contract - Bắt đầu như thế nào và các ứng dụngBlockchain & Smart Contract - Bắt đầu như thế nào và các ứng dụng
Blockchain & Smart Contract - Bắt đầu như thế nào và các ứng dụng
 
Giới thiệu Embulk
Giới thiệu Embulk Giới thiệu Embulk
Giới thiệu Embulk
 
Giới thiệu docker và ứng dụng trong ci-cd
Giới thiệu docker và ứng dụng trong ci-cdGiới thiệu docker và ứng dụng trong ci-cd
Giới thiệu docker và ứng dụng trong ci-cd
 
Tài liệu giới thiệu công ty GMO-Z.com Vietnam Lab Center
Tài liệu giới thiệu công ty GMO-Z.com Vietnam Lab CenterTài liệu giới thiệu công ty GMO-Z.com Vietnam Lab Center
Tài liệu giới thiệu công ty GMO-Z.com Vietnam Lab Center
 
Chia se Agile
Chia se AgileChia se Agile
Chia se Agile
 
Agile retrospective
Agile retrospectiveAgile retrospective
Agile retrospective
 
Giới thiệu Agile + Scrum
Giới thiệu Agile + ScrumGiới thiệu Agile + Scrum
Giới thiệu Agile + Scrum
 
Create android app can send SMS and Email by React Natice
Create android app can send SMS and Email by React NaticeCreate android app can send SMS and Email by React Natice
Create android app can send SMS and Email by React Natice
 
Introduce React Native
Introduce React NativeIntroduce React Native
Introduce React Native
 
Spark tuning
Spark tuningSpark tuning
Spark tuning
 
Git in real product
Git in real productGit in real product
Git in real product
 

Recently uploaded

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Recently uploaded (20)

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

Optimizing MySQL queries

  • 2. OVERVIEW • Optimization Overview • Understanding the Query Execution • Using explain • Optimizing Specific Types of Queries • Indexing • Partitioning • Demo partitioning
  • 3. 1. OPTIMIZATION OVERVIEW 1.1 Optimizing at the Database Level • tables • indexes • storage engine • locking strategy • Are all memory areas used for caching sized correctly?
  • 4. 1. OPTIMIZATION OVERVIEW 1.2 Optimizing at the Hardware Level • Disk seeks • Disk reading and writing • CPU cycles • Memory bandwidth
  • 5. 2. UNDERSTANDING THE QUERY EXECUTION
  • 6. 2. UNDERSTANDING THE QUERY EXECUTION 1. The client sends the SQL statement to the server. 2. The server checks the query cache. If there’s a hit, it returns the stored result from the cache; otherwise, it passes the SQL statement to the next step. 3. The server parses, preprocesses, and optimizes the SQL into a query execution plan. 4. The query execution engine executes the plan by making calls to the storage engine API. 5. The server sends the result to the client.
  • 7. 3. USING EXPLAIN 3.1 Usage: • EXPLAIN is used to obtain a query execution plan. • EXPLAIN is useful for examining queries involving partitioned tables. • EXPLAIN works with SELECT, DELETE, INSERT, REPLACE, and UPDATE statements.
  • 9. 3. USING EXPLAIN 3.3 What should I care about?
  • 10. 3. USING EXPLAIN 3.3 What should I care about? • Partitions • Extra • Type
  • 11. 3. USING EXPLAIN 3.3 What should I care about? Partitions: show which partitions were used.
  • 12. 3. USING EXPLAIN 3.3 What should I care about? Extra • Using filesort • Using temporary • Using index • Using index for group-by • …
  • 13. 3. USING EXPLAIN 3.3 What should I care about? Extra • Using filesort: MySQL must do an extra pass to find out how to retrieve the rows in sorted order. The sort is done by going through all rows according to the join type and storing the sort key and pointer to the row for all rows that match the WHERE clause. The keys then are sorted and the rows are retrieved in sorted order.
  • 14. 3. USING EXPLAIN 3.3 What should I care about? Extra • Using temporary: To resolve the query, MySQL needs to create a temporary table to hold the result. This typically happens if the query contains GROUP BY and ORDER BY clauses that list columns differently.
  • 15. 3. USING EXPLAIN 3.3 What should I care about? Extra • Using index: The column information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row. This strategy can be used when the query uses only columns that are part of a single index.
  • 16. 3. USING EXPLAIN 3.3 What should I care about? Extra • Using index for group-by: Similar to the Using index table access method, Using index for group-by indicates that MySQL found an index that can be used to retrieve all columns of a GROUP BY or DISTINCT query without any extra disk access to the actual table. Additionally, the index is used in the most efficient way so that for each group, only a few index entries are read.
  • 17. 3. USING EXPLAIN 3.3 What should I care about? Type: describes how tables are joined. The following list describes the join types, ordered from the best type to the worst: • System • Const • Eq_ref • Ref • Fulltext
  • 18. 3. USING EXPLAIN 3.3 What should I care about? Type: • Ref_or_null • Index_merge • Unique_subquery • Index_subquery • Range • Index • All
  • 19. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.1 Count() • SELECT COUNT(*) FROM world.City WHERE ID > 5; • If you examine this query with SHOW STATUS, you’ll see that it scans 4,079 rows. If you negate the conditions and subtract the number of cities whose IDs are less than or equal to 5 from the total number of cities, you can reduce that to five rows: • SELECT (SELECT COUNT(*) FROM world.City) - COUNT(*) -> FROM world.City WHERE ID <= 5;
  • 20. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.2 LIMIT and OFFSET • One simple technique to improve efficiency is to do the offset on a covering index, rather than the full rows. You can then join the result to the full row and retrieve the additional columns you need. This can be much more efficient. Consider the following query:
  • 21. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.3 Group by • The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any). In some cases, MySQL is able to do much better than that and to avoid creation of temporary tables by using index access.
  • 22. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.3 Group by Loose Index Scan If loose index scan is applicable to a query, the EXPLAIN output shows Using index for group-by in the Extra column.
  • 23. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.3 Group by Loose Index Scan Condition: • The query is over a single table. • The GROUP BY names only columns that form a leftmost prefix of the index and no other columns. (If, instead of GROUP BY, the query has a DISTINCT clause, all distinct attributes refer to columns that form a leftmost prefix of the index.) • The only aggregate functions used in the select list (if any) are MIN() and MAX(), and all of them refer to the same column. The column must be in the index and must immediately follow the columns in the GROUP BY.
  • 24. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.3 Group by Loose Index Scan Condition: • Any other parts of the index than those from the GROUP BY referenced in the query must be constants (that is, they must be referenced in equalities with constants), except for the argument of MIN() or MAX() functions. • For columns in the index, full column values must be indexed, not just a prefix. For example, with c1 VARCHAR(20), INDEX (c1(10)), the index cannot be used for loose index scan.
  • 25. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.3 Group by Loose Index Scan Example: index(c1, c2, c3)
  • 26. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.3 Group by Loose Index Scan
  • 27. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.3 Group by Tight Index Scan
  • 28. 4. OPTIMIZING SPECIFIC TYPES OF QUERIES 4.3 UNION • UNION ALL is much faster than UNION • Move the WHERE inside each subquery Example: • Slow: (SELECT type, release FROM short_sleeve) UNION (SELECT type, release FROM long_sleeve); WHERE release >=2013; • Fast: (SELECT type, release FROM short_sleeve WHERE release >=2013) UNION (SELECT type, release FROM long_sleeve WHERE release >=2013);
  • 29. 5. INDEXING 5.1 B-Tree • When people talk about an index without mentioning a type, they’re probably referring to a B-Tree index • A B-Tree index speeds up data access because the storage engine doesn’t have to scan the whole table to find the desired data. Instead, it starts at the root node (not shown in this figure).
  • 31. 5. INDEXING 5.1 B-Tree • Consider InnoDB whose page size is 16KB and suppose we have an index on a integer column of size 4bytes, so a node can contain at most 16 * 1024 / 4 = 4096 keys, and a node can have at most 4097 children. • So for a B+tree of height 1, the root node has 4096 keys and the nodes at height 1 (the leaf nodes) have 4096 * 4097 = 16781312 key values.
  • 33. 5. INDEXING 5.1 B-Tree Benefits: • Match the full value: find a person named Cuba Allen who was born on 1960-01-01. • Match a leftmost prefix: find all people with the last name Allen • Match a column prefix: all people whose last names begin with J • Match a range of values: find people whose last names are between Allen and Barrymore • Match one part exactly and match a range on another part: find everyone whose last name is Allen and whose first name starts with the letter K (Kim, Karl, etc.)
  • 34. 5. INDEXING 5.1 B-Tree Limits: • They are not useful if the lookup does not start from the leftmost side of the indexed columns. • You can’t skip columns in the index.
  • 35. 5. INDEXING 5.2 Hash indexes A hash index is built on a hash table and is useful only for exact lookups that use every column in the index. For each row, the storage engine computes a hash code of the indexed columns, which is a small value that will probably differ from the hash codes computed for other rows with different key values. It stores the hash codes in the index and stores a pointer to each row in a hash table.
  • 37. 5. INDEXING 5.2 Hash indexes Limits: • MySQL can’t use the values in the index to avoid reading the rows • can’t use hash indexes for sorting • don’t support partial key matching • support only equality comparisons that use the =, IN(), and <=> operators • When there are collisions (multiple values with the same hash): slow
  • 38. 5. INDEXING 5.3 Indexing Strategies for High Performance 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. SELECT actor_id FROM sakila.actor WHERE actor_id + 1 = 5; • Here’s another example of a common mistake: mysql> SELECT ... WHERE TO_DAYS(CURRENT_DATE) - TO_DAYS(date_col) <= 10;
  • 39. 5. INDEXING 5.3 Indexing Strategies for High Performance Prefix Indexes and Index Selectivity • Sometimes you need to index very long character columns, which makes your indexes large and slow. The trick is to choose a prefix that’s long enough to give good selectivity, but short enough to save space.
  • 40. 5. INDEXING 5.3 Indexing Strategies for High Performance Choosing a Good Column Order • place the most selective columns first in the index. • Let’s use the following query as an example: SELECT * FROM payment WHERE staff_id = 2 AND customer_id = 584; • index on (staff_id, customer_id) OR (customer_id , staff_id) ???
  • 41. 5. INDEXING 5.3 Indexing Strategies for High Performance Choosing a Good Column Order
  • 42. 5. INDEXING 5.3 Indexing Strategies for High Performance Covering Indexes • MySQL can also use an index to retrieve a column’s data, so it doesn’t have to read the row at all. After all, the index’s leaf nodes contain the values they index; • MySQL can use only B-Tree indexes to cover queries. • The general rule is to choose the columns for filtering first (WHERE clause with equality conditions), then sorting/grouping (GROUP BY and ORDER BY clauses) and finally the data projection (SELECT clause).
  • 43. 5. INDEXING 5.3 Indexing Strategies for High Performance Covering Indexes
  • 44. 5. INDEXING 5.3 Indexing Strategies for High Performance Using Index Scans for Sorts MySQL has two ways to produce ordered results: it can use a sort operation, or it can scan an index in order. You can tell when MySQL plans to scan an index by looking for “index” in the type column in EXPLAIN.
  • 45. 5. INDEXING 5.3 Indexing Strategies for High Performance Using Index Scans for Sorts Index on (rental_date, inventory_id, Customer_id)
  • 46. 5. INDEXING 5.3 Indexing Strategies for High Performance Using Index Scans for Sorts Index on (rental_date, inventory_id, customer_id)
  • 47. 5. INDEXING 5.3 Indexing Strategies for High Performance Using Index Scans for Sorts Index on (rental_date, inventory_id, Customer_id)
  • 48. 6. PARTITIONING 6.1 scenarios: • When the table is much too big to fit in memory, or when you have “hot” rows at the end of a table that has lots of historical data. • Partitioned data is easier to maintain than nonpartitioned data. For example, it’s easier to discard old data by dropping an entire partition, which you can do quickly. You can also optimize, check, and repair individual partitions. • If you really need to, you can back up and restore individual partitions, which is very helpful with extremely large datasets.
  • 49. 6. PARTITIONING 6.2 How Partitioning Works: When you query a partitioned table, the partitioning layer opens and locks all of the underlying partitions, the query optimizer determines whether any of the partitions can be ignored (pruned), and then the partitioning layer forwards the handler API calls to the storage engine that manages the partitions.
  • 50. 6. PARTITIONING 6.3 Types of Partitioning: • MySQL supports several types of partitioning. The most common type we’ve seen used is range partitioning.

Editor's Notes

  1. https://dev.mysql.com/doc/refman/5.7/en/explain-output.html
  2. https://dev.mysql.com/doc/refman/5.7/en/explain-output.html#explain-extra-information
  3. https://dev.mysql.com/doc/refman/5.7/en/explain-output.html#explain-extra-information
  4. https://dev.mysql.com/doc/refman/5.7/en/explain-output.html#explain-extra-information
  5. https://dev.mysql.com/doc/refman/5.7/en/explain-output.html#explain-extra-information
  6. https://dev.mysql.com/doc/refman/5.7/en/explain-output.html#explain-extra-information
  7. https://dev.mysql.com/doc/refman/5.7/en/explain-output.html#explain-join-types
  8. This “deferred join” works because it lets the server examine as little data as possible in an index without accessing rows, and then, once the desired rows are found, join them against the full table to retrieve the other columns from the row.
  9. https://www.iheavy.com/2013/06/13/how-to-optimize-mysql-union-for-high-speed/
  10. https://www.cs.usfca.edu/~galles/visualization/BPlusTree.html http://www.ovaistariq.net/733/understanding-btree-indexes-and-how-they-impact-performance/#.WsMCtIhuaUk
  11. http://code-epicenter.com/prefixed-index-in-mysql-database/
  12. https://community.toadworld.com/platforms/mysql/b/weblog/archive/2017/04/06/speed-up-your-queries-using-the-covering-index-in-mysql
  13. If MySQL isn’t using the index to cover the query, it will have to look up each row it finds in the index. This is basically random I/O, so reading data in index order is usually much slower than a sequential table scan, especially for I/Obound workloads.
  14. Ordering the results by the index works only when the index’s order is exactly the same as the ORDER BY clause and all columns are sorted in the same direction (ascending or descending).12 If the query joins multiple tables, it works only when all columns in the ORDER BY clause refer to the first table. The ORDER BY clause also has the same limitation as lookup queries: it needs to form a leftmost prefix of the index. In all other cases, MySQL uses a sort.