SlideShare a Scribd company logo
Goldilocks And The Three Queries –
MySQL's EXPLAIN Explained
 Dave Stokes
 MySQL Community Manager, North America
 David.Stokes@Oracle.Com
Please Read

 The following is intended to outline our general
product direction. It is intended for information
purposes only, and may not be incorporated into any
contract. It is not a commitment to deliver any
material, code, or functionality, and should not be
relied upon in making purchasing decisions.
The development, release, and timing of any
features or functionality described for Oracle’s
products remains at the sole discretion of Oracle.
Simple Introduction

EXPLAIN & EXPLAIN EXTENDED are tools to help
optimize queries. As tools there are only as
good as the crafts persons using them. There is
more to this subject than can be covered here in
a single presentation. But hopefully this session
will start you out on the right path for using
EXPLAIN.
Why worry about the optimizer?
Client sends statement to server
Server checks the query cache to see if it has already run statement. If
so, it retrieves stored result and sends it back to the Client.
Statement is parsed, preprocessed and optimized to make a Query
Execution Plan.
The query execution engine sends the QEP to the storage engine API.
Results sent to the Client.
Once upon a time ...
There was a PHP Programmer named Goldilocks who wanted to
get the phone number of her friend Little Red Riding Hood in
Networking’s phone number. She found an old, dusty piece of
code in the enchanted programmers library. Inside the code was
a special chant to get all the names and phone numbers of the
employees of Grimm-Fayre-Tails Corp. And so, Goldi tried that
special chant!
  SELECT name, phone
  FROM employees;
Oh-No!

But the special chant kept running, and running,
and running.
Eventually Goldi control-C-ed when she realized
that Grimm hired many, many folks after hearing
that the company had 10^10 employees in the
database.
A second chant
Goldi did some searching in the library and learned she could
add to the chant to look only for her friend Red.
 SELECT name, phone
 FROM employees
 WHERE name LIKE 'Red%';


Goldi crossed her fingers, held her breath, and let 'er rip.
What she got
Name, phone
Redford 1234
Redmund 2323
Redlegs 1234
Red Sox 1914
Redding 9021

     – But this was not what Goldilocks needed. So she asked a
         kindly old Java Owl for help
The Owl's chant

'Ah, you want the nickname field!' He re-
crafted her chant.
 SELECT first, nick, last, phone, group
 FROM employees
 WHERE nick LIKE '%red%';
Still too much data … but better


Betty, Big Red, Lopez, 4321, Accounting
Ethel, Little Red, Riding-Hoode, 127.0.0.1, Networks
Agatha, Red Herring, Christie, 007, Public Relations
Johnny, Reds Catcher, Bench, 421, Gaming
'We can tune the query better'

Cried the Owl.
  SELECT first, nick, name, phone, group
  WHERE nick LIKE 'Red%'
  AND group = 'Networking';
 But Goldi was too busy after she got the
data she needed to listen.
The preceding were
            obviously flawed queries
•
    But how do you check if queries are running
    efficiently?
•
    What does the query the MySQL server runs
    really look like? (the dreaded Query Execution
    Plan). What is cost based optimization?
•
    How can you make queries faster?
EXPLAIN & EXPLAIN EXTENDED
EXPLAIN [EXTENDED | PARTITIONS]
{
     SELECT statement
    | DELETE statement
    | INSERT statement
    | REPLACE statement
    | UPDATE statement
}
Or EXPLAIN tbl_name (same as DESCRIBE tbl_name)
What is being EXPLAINed
Prepending EXPLAIN to a statement* asks the optimizer how it would
   plan to execute that statement (and sometimes it guesses wrong) at
   lowest cost (measures in disk page seeks*).


What it can tell you:
--Where to add INDEXes to speed row access
--Check JOIN order


And Optimizer Tracing (more later) has been recently introduced!


* SELECT, DELETE, INSERT, REPLACE & UPDATE as of 5.6, only SELECT 5.5 & previous
* Does not know if page is in memory, on disk (storage engine's problem, not optimizer), see
    MySQL Manual 7.8.3
The Columns
id              Which SELECT
select_type     The SELECT type
table           Output row table
type            JOIN type
possible_keys   Potential indexes
key             Actual index used
key_ken         Length of actual
                index
ref             Columns used
                against index
rows            Estimate of rows
extra           Additional Info
A first look at EXPLAIN
...using World database




                 Will read all 4079
                   rows – all the
                 rows in this table
EXPLAIN EXTENDED -> query plan




             Filtered: Estimated % of rows filtered
                          By condition




  The query as seen by server (kind of, sort of, close)
Add in a WHERE clause
Time for a quick review of indexes

Advantages                      Disadvantages
     – Go right to desired           – Overhead*
         row(s) instead of                  • CRUD
         reading ALL                 – Not used on full table
         ROWS                            scans
     – Smaller than whole
         table (read from
         disk faster)                     * May need to run
     – Can 'carry' other data             ANALYZE TABLE to update
                                          statistics such as
         with compound                    cardinality to help optimizer
         indexes                          make better choices
Quiz: Why read 4079 rows when only
five are needed?
Information in the type Column

ALL – full table scan (to be avoided when possible)
CONST – WHERE ID=1
EQ_REF – WHERE a.ID = b.ID (uses indexes, 1 row returned)
REF – WHERE state='CA' (multiple rows for key values)
REF_OR_NULL – WHERE ID IS NULL (extra lookup needed for NULL)
INDEX_MERGE – WHERE ID = 10 OR state = 'CA'
RANGE – WHERE x IN (10,20,30)
INDEX – (usually faster when index file < data file)
UNIQUE_SUBQUERY –
INDEX-SUBQUERY –
SYSTEM – Table with 1 row or in-memory table
Full table scans VS Index

So lets create a copy of
  the World.City table that
  has no indexes. The
  optimizer estimates that
  it would require 4,279
  rows to be read to find
  the desired record – 5%
  more than actual rows.

And the table has only
  4,079 rows.
How does NULL change things?

Taking NOT NULL away
  from the ID field (plus
  the previous index)
  increases the estimated
  rows read to 4296!
  Roughly 5.5% more
  rows than actual in file.

Running ANALYZE TABLE
  reduces the count to
  3816 – still > 1
Both of the following return 1 row
EXPLAIN PARTITIONS -
Add 12 hash partitions to City
Some parts of your query
   may be hidden!!
Latin1 versus UTF8

Create a copy of the City
  table but with UTF8
  character set replacing
  Latin1. The three
  character key_len grows
  to nine characters. That
  is more data to read and
  more to compare which
  is pronounced 'slower'.
INDEX Length




               If a new index on
                   CountryCode with
                   length of 2 bytes, does it
                   work as well as the
                   original 3 bytes?
Forcing use of new shorter index ...

Still generates a
   guesstimate that 39
   rows must be read.

In some cases there is
   performance to be
   gained in using shorter
   indexes.
Subqueries

Run as part of EXPLAIN
  execution and may
  cause significant
  overhead. So be careful
  when testing.

Note here that #1 is not
  using an index. And that
  is why we recommend
  rewriting sub queries as
  joins.
EXAMPLE of covering Indexing




In this case, adding an
   index reduces the reads
   from 239 to 42.
Can we do better for this
   query?
Index on both Continent and
Government Form
                 With both Continent and
                    GovernmentForm indexed
                    together, we go from 42 rows
                    read to 19.
                 Using index means the data is
                    retrieved from index not table
                    (good)
                 Using index condition means
                    eval pushed down to storage
                    engine. This can reduce
                    storage engine read of table
                    and server reads of storage
                    engine (not bad)
Extra ***

USING INDEX – Getting data from the index rather
  than the table
USING FILESORT – Sorting was needed rather than
  using an index. Uses file system (slow)
ORDER BY can use indexes
USING TEMPORARY – A temp table was created –
  see tmp_table_size and max_heap_table_size
USING WHERE – filter outside storage engine
Using Join Buffer -- means no index used.
Things can get messy!
straight_join forces order of tables
Index Hints

                               Use only as a last resort –
index_hint:
                                 shifts in data can make
  USE {INDEX|KEY}
                                 this the 'long way
   [{FOR {JOIN|ORDER BY|
   GROUP BY}] ([index_list])     around'.
 | IGNORE {INDEX|KEY}
   [{FOR {JOIN|ORDER BY|
   GROUP BY}] (index_list)
 | FORCE {INDEX|KEY}
   [{FOR {JOIN|ORDER BY|
   GROUP BY}] (index_list)     http://dev.mysql.com/doc/refman/5.6/en/index-
                                     hints.html
Controlling the Optimizer

mysql> SELECT @@optimizer_switchG
                                                  You can turn on or off
*************************** 1. row
     ***************************                    certain optimizer
@@optimizer_switch:
  index_merge=on,index_merge_union=on,
                                                    settings for
              index_merge_sort_union=on,            GLOBAL or
              index_merge_intersection=on,          SESSION
              engine_condition_pushdown=on,
              index_condition_pushdown=on,
              mrr=on,mrr_cost_based=on,           See MySQL Manual
    block_nested_loop=on,batched_key_access=off
                                                    7.8.4.2 and know
                                                    your mileage may
                                                    vary.
Things to watch
 mysqladmin -r -i 10 extended-status
Slow_queries – number in last period
Select_scan – full table scans
Select_full_join full scans to complete
Created_tmp_disk_tables – file sorts
Key_read_requerts/Key_wrtie_requests – read/write
  weighting of application, may need to modify
  application
Optimizer Tracing (6.5.3 onward)

SET optimizer_trace="enabled=on";
SELECT Name FROM City WHERE ID=999;
SELECT trace into dumpfile '/tmp/foo' FROM
  INFORMATION_SCHEMA.OPTIMIZER_TRACE;


Shows more logic than EXPLAIN

The output shows much deeper detail on how the
  optimizer chooses to process a query. This level of
  detail is well past the level for this presentation.
Sample from the trace – but no clues
on optimizing for Joe Average DBA
Final Thoughts

1. READ chapter 7 of the MySQL Manual
2. Run ANALYZE TABLE periodically
3. Minimize disk I/o
Q&A
David.Stokes@Oracle.Com
Ad

More Related Content

What's hot (20)

Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practices
Smitha Padmanabhan
 
How mysql choose the execution plan
How mysql choose the execution planHow mysql choose the execution plan
How mysql choose the execution plan
辛鹤 李
 
Oracle views
Oracle viewsOracle views
Oracle views
Balqees Al.Mubarak
 
Webinar 2013 advanced_query_tuning
Webinar 2013 advanced_query_tuningWebinar 2013 advanced_query_tuning
Webinar 2013 advanced_query_tuning
晓 周
 
Explaining the explain_plan
Explaining the explain_planExplaining the explain_plan
Explaining the explain_plan
arief12H
 
MySQL index optimization techniques
MySQL index optimization techniquesMySQL index optimization techniques
MySQL index optimization techniques
kumar gaurav
 
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
Hemant Kumar Singh
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
Smitha Padmanabhan
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
Salman Memon
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
CoT
 
How to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better PerformanceHow to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better Performance
oysteing
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
Balqees Al.Mubarak
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
baabtra.com - No. 1 supplier of quality freshers
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
MYXPLAIN
 
Oracle query optimizer
Oracle query optimizerOracle query optimizer
Oracle query optimizer
Smitha Padmanabhan
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
Felipe Costa
 
plsql les01
 plsql les01 plsql les01
plsql les01
sasa_eldoby
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
Vikas Gupta
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
paulguerin
 
MySQL Optimizer Cost Model
MySQL Optimizer Cost ModelMySQL Optimizer Cost Model
MySQL Optimizer Cost Model
Olav Sandstå
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practices
Smitha Padmanabhan
 
How mysql choose the execution plan
How mysql choose the execution planHow mysql choose the execution plan
How mysql choose the execution plan
辛鹤 李
 
Webinar 2013 advanced_query_tuning
Webinar 2013 advanced_query_tuningWebinar 2013 advanced_query_tuning
Webinar 2013 advanced_query_tuning
晓 周
 
Explaining the explain_plan
Explaining the explain_planExplaining the explain_plan
Explaining the explain_plan
arief12H
 
MySQL index optimization techniques
MySQL index optimization techniquesMySQL index optimization techniques
MySQL index optimization techniques
kumar gaurav
 
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)MySQL Indexing : Improving Query Performance Using Index (Covering Index)
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
Hemant Kumar Singh
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
Salman Memon
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
CoT
 
How to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better PerformanceHow to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better Performance
oysteing
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
MYXPLAIN
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
Felipe Costa
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
paulguerin
 
MySQL Optimizer Cost Model
MySQL Optimizer Cost ModelMySQL Optimizer Cost Model
MySQL Optimizer Cost Model
Olav Sandstå
 

Viewers also liked (8)

Sql no sql
Sql no sqlSql no sql
Sql no sql
Dave Stokes
 
My SQL 101
My SQL 101My SQL 101
My SQL 101
Dave Stokes
 
MySQL 5.6 Updates
MySQL 5.6 UpdatesMySQL 5.6 Updates
MySQL 5.6 Updates
Dave Stokes
 
Better sq lqueries
Better sq lqueriesBetter sq lqueries
Better sq lqueries
Dave Stokes
 
Scaling MySQl 1 to N Servers -- Los Angelese MySQL User Group Feb 2014
Scaling MySQl 1 to N Servers -- Los Angelese MySQL User Group Feb 2014Scaling MySQl 1 to N Servers -- Los Angelese MySQL User Group Feb 2014
Scaling MySQl 1 to N Servers -- Los Angelese MySQL User Group Feb 2014
Dave Stokes
 
MySQL 5.7 New Features to Exploit -- PHPTek/Chicago MySQL User Group May 2014
MySQL 5.7 New Features to Exploit -- PHPTek/Chicago MySQL User Group May 2014MySQL 5.7 New Features to Exploit -- PHPTek/Chicago MySQL User Group May 2014
MySQL 5.7 New Features to Exploit -- PHPTek/Chicago MySQL User Group May 2014
Dave Stokes
 
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
Dave Stokes
 
MySql's NoSQL -- best of both worlds on the same disks
MySql's NoSQL -- best of both worlds on the same disksMySql's NoSQL -- best of both worlds on the same disks
MySql's NoSQL -- best of both worlds on the same disks
Dave Stokes
 
MySQL 5.6 Updates
MySQL 5.6 UpdatesMySQL 5.6 Updates
MySQL 5.6 Updates
Dave Stokes
 
Better sq lqueries
Better sq lqueriesBetter sq lqueries
Better sq lqueries
Dave Stokes
 
Scaling MySQl 1 to N Servers -- Los Angelese MySQL User Group Feb 2014
Scaling MySQl 1 to N Servers -- Los Angelese MySQL User Group Feb 2014Scaling MySQl 1 to N Servers -- Los Angelese MySQL User Group Feb 2014
Scaling MySQl 1 to N Servers -- Los Angelese MySQL User Group Feb 2014
Dave Stokes
 
MySQL 5.7 New Features to Exploit -- PHPTek/Chicago MySQL User Group May 2014
MySQL 5.7 New Features to Exploit -- PHPTek/Chicago MySQL User Group May 2014MySQL 5.7 New Features to Exploit -- PHPTek/Chicago MySQL User Group May 2014
MySQL 5.7 New Features to Exploit -- PHPTek/Chicago MySQL User Group May 2014
Dave Stokes
 
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
Dave Stokes
 
MySql's NoSQL -- best of both worlds on the same disks
MySql's NoSQL -- best of both worlds on the same disksMySql's NoSQL -- best of both worlds on the same disks
MySql's NoSQL -- best of both worlds on the same disks
Dave Stokes
 
Ad

Similar to Goldilocks and the Three MySQL Queries (20)

Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
guest9d79e073
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
Mark Ginnebaugh
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008
paulguerin
 
Sql scripting sorcerypaper
Sql scripting sorcerypaperSql scripting sorcerypaper
Sql scripting sorcerypaper
oracle documents
 
15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance
guest9912e5
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
Márton Kodok
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
Dave Stokes
 
Basics on SQL queries
Basics on SQL queriesBasics on SQL queries
Basics on SQL queries
Knoldus Inc.
 
Mohan Testing
Mohan TestingMohan Testing
Mohan Testing
smittal81
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
xKinAnx
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance Optimization
Mindfire Solutions
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
devObjective
 
Sql killedserver
Sql killedserverSql killedserver
Sql killedserver
ColdFusionConference
 
Conquering "big data": An introduction to shard query
Conquering "big data": An introduction to shard queryConquering "big data": An introduction to shard query
Conquering "big data": An introduction to shard query
Justin Swanhart
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
Nirav Shah
 
Tunning sql query
Tunning sql queryTunning sql query
Tunning sql query
vuhaininh88
 
Query parameterization
Query parameterizationQuery parameterization
Query parameterization
Riteshkiit
 
How to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon RedshiftHow to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon Redshift
AWS Germany
 
Cost Based Oracle
Cost Based OracleCost Based Oracle
Cost Based Oracle
Santosh Kangane
 
MySQL Scaling Presentation
MySQL Scaling PresentationMySQL Scaling Presentation
MySQL Scaling Presentation
Tommy Falgout
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
guest9d79e073
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
Mark Ginnebaugh
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008
paulguerin
 
Sql scripting sorcerypaper
Sql scripting sorcerypaperSql scripting sorcerypaper
Sql scripting sorcerypaper
oracle documents
 
15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance
guest9912e5
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
Márton Kodok
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
Dave Stokes
 
Basics on SQL queries
Basics on SQL queriesBasics on SQL queries
Basics on SQL queries
Knoldus Inc.
 
Mohan Testing
Mohan TestingMohan Testing
Mohan Testing
smittal81
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
xKinAnx
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance Optimization
Mindfire Solutions
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
devObjective
 
Conquering "big data": An introduction to shard query
Conquering "big data": An introduction to shard queryConquering "big data": An introduction to shard query
Conquering "big data": An introduction to shard query
Justin Swanhart
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
Nirav Shah
 
Tunning sql query
Tunning sql queryTunning sql query
Tunning sql query
vuhaininh88
 
Query parameterization
Query parameterizationQuery parameterization
Query parameterization
Riteshkiit
 
How to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon RedshiftHow to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon Redshift
AWS Germany
 
MySQL Scaling Presentation
MySQL Scaling PresentationMySQL Scaling Presentation
MySQL Scaling Presentation
Tommy Falgout
 
Ad

More from Dave Stokes (20)

Json within a relational database
Json within a relational databaseJson within a relational database
Json within a relational database
Dave Stokes
 
Database basics for new-ish developers -- All Things Open October 18th 2021
Database basics for new-ish developers  -- All Things Open October 18th 2021Database basics for new-ish developers  -- All Things Open October 18th 2021
Database basics for new-ish developers -- All Things Open October 18th 2021
Dave Stokes
 
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Php &amp; my sql  - how do pdo, mysq-li, and x devapi do what they doPhp &amp; my sql  - how do pdo, mysq-li, and x devapi do what they do
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Dave Stokes
 
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Dave Stokes
 
MySQL 8.0 New Features -- September 27th presentation for Open Source Summit
MySQL 8.0 New Features -- September 27th presentation for Open Source SummitMySQL 8.0 New Features -- September 27th presentation for Open Source Summit
MySQL 8.0 New Features -- September 27th presentation for Open Source Summit
Dave Stokes
 
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptJavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
Dave Stokes
 
Open Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational DatabaseOpen Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational Database
Dave Stokes
 
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dave Stokes
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
Dave Stokes
 
Midwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesMidwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL Features
Dave Stokes
 
Data Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database AnalyticsData Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database Analytics
Dave Stokes
 
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Dave Stokes
 
Confoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New FeaturesConfoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New Features
Dave Stokes
 
Confoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsConfoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & Histograms
Dave Stokes
 
Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my! Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my!
Dave Stokes
 
MySQL Replication Update - DEbconf 2020 presentation
MySQL Replication Update - DEbconf 2020 presentationMySQL Replication Update - DEbconf 2020 presentation
MySQL Replication Update - DEbconf 2020 presentation
Dave Stokes
 
MySQL 8.0 Operational Changes
MySQL 8.0 Operational ChangesMySQL 8.0 Operational Changes
MySQL 8.0 Operational Changes
Dave Stokes
 
cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven Features
Dave Stokes
 
A Step by Step Introduction to the MySQL Document Store
A Step by Step Introduction to the MySQL Document StoreA Step by Step Introduction to the MySQL Document Store
A Step by Step Introduction to the MySQL Document Store
Dave Stokes
 
Discover The Power of NoSQL + MySQL with MySQL
Discover The Power of NoSQL + MySQL with MySQLDiscover The Power of NoSQL + MySQL with MySQL
Discover The Power of NoSQL + MySQL with MySQL
Dave Stokes
 
Json within a relational database
Json within a relational databaseJson within a relational database
Json within a relational database
Dave Stokes
 
Database basics for new-ish developers -- All Things Open October 18th 2021
Database basics for new-ish developers  -- All Things Open October 18th 2021Database basics for new-ish developers  -- All Things Open October 18th 2021
Database basics for new-ish developers -- All Things Open October 18th 2021
Dave Stokes
 
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Php &amp; my sql  - how do pdo, mysq-li, and x devapi do what they doPhp &amp; my sql  - how do pdo, mysq-li, and x devapi do what they do
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Dave Stokes
 
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Dave Stokes
 
MySQL 8.0 New Features -- September 27th presentation for Open Source Summit
MySQL 8.0 New Features -- September 27th presentation for Open Source SummitMySQL 8.0 New Features -- September 27th presentation for Open Source Summit
MySQL 8.0 New Features -- September 27th presentation for Open Source Summit
Dave Stokes
 
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptJavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
Dave Stokes
 
Open Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational DatabaseOpen Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational Database
Dave Stokes
 
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dave Stokes
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
Dave Stokes
 
Midwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesMidwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL Features
Dave Stokes
 
Data Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database AnalyticsData Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database Analytics
Dave Stokes
 
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Dave Stokes
 
Confoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New FeaturesConfoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New Features
Dave Stokes
 
Confoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsConfoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & Histograms
Dave Stokes
 
Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my! Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my!
Dave Stokes
 
MySQL Replication Update - DEbconf 2020 presentation
MySQL Replication Update - DEbconf 2020 presentationMySQL Replication Update - DEbconf 2020 presentation
MySQL Replication Update - DEbconf 2020 presentation
Dave Stokes
 
MySQL 8.0 Operational Changes
MySQL 8.0 Operational ChangesMySQL 8.0 Operational Changes
MySQL 8.0 Operational Changes
Dave Stokes
 
cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven Features
Dave Stokes
 
A Step by Step Introduction to the MySQL Document Store
A Step by Step Introduction to the MySQL Document StoreA Step by Step Introduction to the MySQL Document Store
A Step by Step Introduction to the MySQL Document Store
Dave Stokes
 
Discover The Power of NoSQL + MySQL with MySQL
Discover The Power of NoSQL + MySQL with MySQLDiscover The Power of NoSQL + MySQL with MySQL
Discover The Power of NoSQL + MySQL with MySQL
Dave Stokes
 

Recently uploaded (20)

Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 

Goldilocks and the Three MySQL Queries

  • 1. Goldilocks And The Three Queries – MySQL's EXPLAIN Explained Dave Stokes MySQL Community Manager, North America [email protected]
  • 2. Please Read The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
  • 3. Simple Introduction EXPLAIN & EXPLAIN EXTENDED are tools to help optimize queries. As tools there are only as good as the crafts persons using them. There is more to this subject than can be covered here in a single presentation. But hopefully this session will start you out on the right path for using EXPLAIN.
  • 4. Why worry about the optimizer? Client sends statement to server Server checks the query cache to see if it has already run statement. If so, it retrieves stored result and sends it back to the Client. Statement is parsed, preprocessed and optimized to make a Query Execution Plan. The query execution engine sends the QEP to the storage engine API. Results sent to the Client.
  • 5. Once upon a time ... There was a PHP Programmer named Goldilocks who wanted to get the phone number of her friend Little Red Riding Hood in Networking’s phone number. She found an old, dusty piece of code in the enchanted programmers library. Inside the code was a special chant to get all the names and phone numbers of the employees of Grimm-Fayre-Tails Corp. And so, Goldi tried that special chant! SELECT name, phone FROM employees;
  • 6. Oh-No! But the special chant kept running, and running, and running. Eventually Goldi control-C-ed when she realized that Grimm hired many, many folks after hearing that the company had 10^10 employees in the database.
  • 7. A second chant Goldi did some searching in the library and learned she could add to the chant to look only for her friend Red. SELECT name, phone FROM employees WHERE name LIKE 'Red%'; Goldi crossed her fingers, held her breath, and let 'er rip.
  • 8. What she got Name, phone Redford 1234 Redmund 2323 Redlegs 1234 Red Sox 1914 Redding 9021 – But this was not what Goldilocks needed. So she asked a kindly old Java Owl for help
  • 9. The Owl's chant 'Ah, you want the nickname field!' He re- crafted her chant. SELECT first, nick, last, phone, group FROM employees WHERE nick LIKE '%red%';
  • 10. Still too much data … but better Betty, Big Red, Lopez, 4321, Accounting Ethel, Little Red, Riding-Hoode, 127.0.0.1, Networks Agatha, Red Herring, Christie, 007, Public Relations Johnny, Reds Catcher, Bench, 421, Gaming
  • 11. 'We can tune the query better' Cried the Owl. SELECT first, nick, name, phone, group WHERE nick LIKE 'Red%' AND group = 'Networking'; But Goldi was too busy after she got the data she needed to listen.
  • 12. The preceding were obviously flawed queries • But how do you check if queries are running efficiently? • What does the query the MySQL server runs really look like? (the dreaded Query Execution Plan). What is cost based optimization? • How can you make queries faster?
  • 13. EXPLAIN & EXPLAIN EXTENDED EXPLAIN [EXTENDED | PARTITIONS] { SELECT statement | DELETE statement | INSERT statement | REPLACE statement | UPDATE statement } Or EXPLAIN tbl_name (same as DESCRIBE tbl_name)
  • 14. What is being EXPLAINed Prepending EXPLAIN to a statement* asks the optimizer how it would plan to execute that statement (and sometimes it guesses wrong) at lowest cost (measures in disk page seeks*). What it can tell you: --Where to add INDEXes to speed row access --Check JOIN order And Optimizer Tracing (more later) has been recently introduced! * SELECT, DELETE, INSERT, REPLACE & UPDATE as of 5.6, only SELECT 5.5 & previous * Does not know if page is in memory, on disk (storage engine's problem, not optimizer), see MySQL Manual 7.8.3
  • 15. The Columns id Which SELECT select_type The SELECT type table Output row table type JOIN type possible_keys Potential indexes key Actual index used key_ken Length of actual index ref Columns used against index rows Estimate of rows extra Additional Info
  • 16. A first look at EXPLAIN ...using World database Will read all 4079 rows – all the rows in this table
  • 17. EXPLAIN EXTENDED -> query plan Filtered: Estimated % of rows filtered By condition The query as seen by server (kind of, sort of, close)
  • 18. Add in a WHERE clause
  • 19. Time for a quick review of indexes Advantages Disadvantages – Go right to desired – Overhead* row(s) instead of • CRUD reading ALL – Not used on full table ROWS scans – Smaller than whole table (read from disk faster) * May need to run – Can 'carry' other data ANALYZE TABLE to update statistics such as with compound cardinality to help optimizer indexes make better choices
  • 20. Quiz: Why read 4079 rows when only five are needed?
  • 21. Information in the type Column ALL – full table scan (to be avoided when possible) CONST – WHERE ID=1 EQ_REF – WHERE a.ID = b.ID (uses indexes, 1 row returned) REF – WHERE state='CA' (multiple rows for key values) REF_OR_NULL – WHERE ID IS NULL (extra lookup needed for NULL) INDEX_MERGE – WHERE ID = 10 OR state = 'CA' RANGE – WHERE x IN (10,20,30) INDEX – (usually faster when index file < data file) UNIQUE_SUBQUERY – INDEX-SUBQUERY – SYSTEM – Table with 1 row or in-memory table
  • 22. Full table scans VS Index So lets create a copy of the World.City table that has no indexes. The optimizer estimates that it would require 4,279 rows to be read to find the desired record – 5% more than actual rows. And the table has only 4,079 rows.
  • 23. How does NULL change things? Taking NOT NULL away from the ID field (plus the previous index) increases the estimated rows read to 4296! Roughly 5.5% more rows than actual in file. Running ANALYZE TABLE reduces the count to 3816 – still > 1
  • 24. Both of the following return 1 row
  • 25. EXPLAIN PARTITIONS - Add 12 hash partitions to City
  • 26. Some parts of your query may be hidden!!
  • 27. Latin1 versus UTF8 Create a copy of the City table but with UTF8 character set replacing Latin1. The three character key_len grows to nine characters. That is more data to read and more to compare which is pronounced 'slower'.
  • 28. INDEX Length If a new index on CountryCode with length of 2 bytes, does it work as well as the original 3 bytes?
  • 29. Forcing use of new shorter index ... Still generates a guesstimate that 39 rows must be read. In some cases there is performance to be gained in using shorter indexes.
  • 30. Subqueries Run as part of EXPLAIN execution and may cause significant overhead. So be careful when testing. Note here that #1 is not using an index. And that is why we recommend rewriting sub queries as joins.
  • 31. EXAMPLE of covering Indexing In this case, adding an index reduces the reads from 239 to 42. Can we do better for this query?
  • 32. Index on both Continent and Government Form With both Continent and GovernmentForm indexed together, we go from 42 rows read to 19. Using index means the data is retrieved from index not table (good) Using index condition means eval pushed down to storage engine. This can reduce storage engine read of table and server reads of storage engine (not bad)
  • 33. Extra *** USING INDEX – Getting data from the index rather than the table USING FILESORT – Sorting was needed rather than using an index. Uses file system (slow) ORDER BY can use indexes USING TEMPORARY – A temp table was created – see tmp_table_size and max_heap_table_size USING WHERE – filter outside storage engine Using Join Buffer -- means no index used.
  • 34. Things can get messy!
  • 36. Index Hints Use only as a last resort – index_hint: shifts in data can make USE {INDEX|KEY} this the 'long way [{FOR {JOIN|ORDER BY| GROUP BY}] ([index_list]) around'. | IGNORE {INDEX|KEY} [{FOR {JOIN|ORDER BY| GROUP BY}] (index_list) | FORCE {INDEX|KEY} [{FOR {JOIN|ORDER BY| GROUP BY}] (index_list) http://dev.mysql.com/doc/refman/5.6/en/index- hints.html
  • 37. Controlling the Optimizer mysql> SELECT @@optimizer_switchG You can turn on or off *************************** 1. row *************************** certain optimizer @@optimizer_switch: index_merge=on,index_merge_union=on, settings for index_merge_sort_union=on, GLOBAL or index_merge_intersection=on, SESSION engine_condition_pushdown=on, index_condition_pushdown=on, mrr=on,mrr_cost_based=on, See MySQL Manual block_nested_loop=on,batched_key_access=off 7.8.4.2 and know your mileage may vary.
  • 38. Things to watch mysqladmin -r -i 10 extended-status Slow_queries – number in last period Select_scan – full table scans Select_full_join full scans to complete Created_tmp_disk_tables – file sorts Key_read_requerts/Key_wrtie_requests – read/write weighting of application, may need to modify application
  • 39. Optimizer Tracing (6.5.3 onward) SET optimizer_trace="enabled=on"; SELECT Name FROM City WHERE ID=999; SELECT trace into dumpfile '/tmp/foo' FROM INFORMATION_SCHEMA.OPTIMIZER_TRACE; Shows more logic than EXPLAIN The output shows much deeper detail on how the optimizer chooses to process a query. This level of detail is well past the level for this presentation.
  • 40. Sample from the trace – but no clues on optimizing for Joe Average DBA
  • 41. Final Thoughts 1. READ chapter 7 of the MySQL Manual 2. Run ANALYZE TABLE periodically 3. Minimize disk I/o
  • 42. Q&A