SlideShare a Scribd company logo
1 of 48
San Diego
                               PHP
                               Aug 2
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 Database 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




                 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
            ROWS                            table scans
      ●
          Smaller than whole
            table (read from
            disk faster)                    * May need to run
      ●
          Can 'carry' other                 ANALYZE TABLE to
                                            update statistics such as
            data with                       cardinality to help
            compound                        optimizer make better
                                            choices
            indexes
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 characters,
                   does it work as well as
                   the original 3 chars?
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.
Avoiding file sort

Select from attendees where Id = 2 order by Name

Add index sss (ID,Name)
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 – fielsorts
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 on EXPLAIN

1. READ chapter 7 of the MySQL Manual
2. Add index on columns in WHERE clause
3. Run ANALYZE TABLE periodically
4. Adjust buffer pool size, minimize disk I/o
Common Programming Problems

1. SCRUB Your Data
2. Check return codes

$result = mysqli_query(“SELECT Id FROM City
                  WHERE Id = '$city_id'”);




If ($result) {
           // Code where query executed
} else {
           // Code when query did not execute
}
3. Use Prepared Statements

If ($stmt = mysqli_>prepare(“INSERT INTO FOO
         VALUES (?,?,?)”);
$stmt->bind_param('ssd',$first,$last,$age);
$first = 'Joe';
$last='Jones';
$age='22';
$stmt->execute();
If (!mysqli_stmt_affected_rows($stmt)) {
         // PROBLEM
}
4. Be careful reporting problems

mysqli_query(“DROP TABLE foo.bar”);
$result = mysqli_stmt_execute($stmt);

If (!$result) { // Did NOT EXECUTE
            printf("Error: %s.n",
               mysqli_stmt_error($stmt));
}

                  Can give hackers
                  clues!
5. Ask for what you need for speed

SELECT *           SELECT Name, Phone,
FROM foo             Customer_id
WHERE id = $id     FROM foo
                   WHERE id=$id




SLOW!              FASTER!!
Q&A

More Related Content

What's hot

Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsNirav Shah
 
MySQL Optimizer Overview
MySQL Optimizer OverviewMySQL Optimizer Overview
MySQL Optimizer OverviewOlav Sandstå
 
How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15oysteing
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesSmitha Padmanabhan
 
How to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better PerformanceHow to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better Performanceoysteing
 
MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MYXPLAIN
 
How mysql choose the execution plan
How mysql choose the execution planHow mysql choose the execution plan
How mysql choose the execution plan辛鹤 李
 
Cost Based Optimizer - Part 1 of 2
Cost Based Optimizer - Part 1 of 2Cost Based Optimizer - Part 1 of 2
Cost Based Optimizer - Part 1 of 2Mahesh Vallampati
 
Oracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse SupportOracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse Supportnkarag
 
Db2 performance tuning for dummies
Db2 performance tuning for dummiesDb2 performance tuning for dummies
Db2 performance tuning for dummiesAngel Dueñas Neyra
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesMaria Colgan
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLMárton Kodok
 
Explain the explain_plan
Explain the explain_planExplain the explain_plan
Explain the explain_planMaria Colgan
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQLCoT
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 Richie Rump
 
Identify SQL Tuning Opportunities
Identify SQL Tuning OpportunitiesIdentify SQL Tuning Opportunities
Identify SQL Tuning OpportunitiesCuneyt Goksu
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserverlochaaaa
 

What's hot (20)

Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
 
MySQL Optimizer Overview
MySQL Optimizer OverviewMySQL Optimizer Overview
MySQL Optimizer Overview
 
How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practices
 
How to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better PerformanceHow to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better Performance
 
MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
 
How mysql choose the execution plan
How mysql choose the execution planHow mysql choose the execution plan
How mysql choose the execution plan
 
Cost Based Optimizer - Part 1 of 2
Cost Based Optimizer - Part 1 of 2Cost Based Optimizer - Part 1 of 2
Cost Based Optimizer - Part 1 of 2
 
Oracle query optimizer
Oracle query optimizerOracle query optimizer
Oracle query optimizer
 
Oracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse SupportOracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse Support
 
Db2 performance tuning for dummies
Db2 performance tuning for dummiesDb2 performance tuning for dummies
Db2 performance tuning for dummies
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
 
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
 
Explain the explain_plan
Explain the explain_planExplain the explain_plan
Explain the explain_plan
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012
 
Identify SQL Tuning Opportunities
Identify SQL Tuning OpportunitiesIdentify SQL Tuning Opportunities
Identify SQL Tuning Opportunities
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 

Viewers also liked

Better sq lqueries
Better sq lqueriesBetter sq lqueries
Better sq lqueriesDave Stokes
 
MySQL 5.6 Updates
MySQL 5.6 UpdatesMySQL 5.6 Updates
MySQL 5.6 UpdatesDave 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 2014Dave 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 2014Dave 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 2014Dave 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 disksDave Stokes
 

Viewers also liked (8)

My SQL 101
My SQL 101My SQL 101
My SQL 101
 
Sql no sql
Sql no sqlSql no sql
Sql no sql
 
Better sq lqueries
Better sq lqueriesBetter sq lqueries
Better sq lqueries
 
MySQL 5.6 Updates
MySQL 5.6 UpdatesMySQL 5.6 Updates
MySQL 5.6 Updates
 
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
 
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
 
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
 
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
 

Similar to San diegophp

Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09guest9d79e073
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Mark Ginnebaugh
 
Sql scripting sorcerypaper
Sql scripting sorcerypaperSql scripting sorcerypaper
Sql scripting sorcerypaperoracle documents
 
Mohan Testing
Mohan TestingMohan Testing
Mohan Testingsmittal81
 
15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performanceguest9912e5
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statementsxKinAnx
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008paulguerin
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsDave Stokes
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the ServerdevObjective
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance OptimizationMindfire Solutions
 
Elasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep diveElasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep diveSematext Group, Inc.
 
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 queryJustin Swanhart
 
Optimizing MySQL Queries
Optimizing MySQL QueriesOptimizing MySQL Queries
Optimizing MySQL QueriesAchievers Tech
 
Basics on SQL queries
Basics on SQL queriesBasics on SQL queries
Basics on SQL queriesKnoldus Inc.
 
SPL_ALL_EN.pptx
SPL_ALL_EN.pptxSPL_ALL_EN.pptx
SPL_ALL_EN.pptx政宏 张
 
How to Think Like the SQL Server Engine
How to Think Like the SQL Server EngineHow to Think Like the SQL Server Engine
How to Think Like the SQL Server EngineBrent Ozar
 
Db performance optimization with indexing
Db performance optimization with indexingDb performance optimization with indexing
Db performance optimization with indexingRajeev Kumar
 
Tunning sql query
Tunning sql queryTunning sql query
Tunning sql queryvuhaininh88
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL ServerRajesh Gunasundaram
 

Similar to San diegophp (20)

Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
 
Sql scripting sorcerypaper
Sql scripting sorcerypaperSql scripting sorcerypaper
Sql scripting sorcerypaper
 
Mohan Testing
Mohan TestingMohan Testing
Mohan Testing
 
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
 
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
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
 
Sql killedserver
Sql killedserverSql killedserver
Sql killedserver
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance Optimization
 
Elasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep diveElasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep dive
 
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
 
Optimizing MySQL Queries
Optimizing MySQL QueriesOptimizing MySQL Queries
Optimizing MySQL Queries
 
Basics on SQL queries
Basics on SQL queriesBasics on SQL queries
Basics on SQL queries
 
SPL_ALL_EN.pptx
SPL_ALL_EN.pptxSPL_ALL_EN.pptx
SPL_ALL_EN.pptx
 
How to Think Like the SQL Server Engine
How to Think Like the SQL Server EngineHow to Think Like the SQL Server Engine
How to Think Like the SQL Server Engine
 
Db performance optimization with indexing
Db performance optimization with indexingDb performance optimization with indexing
Db performance optimization with indexing
 
Tunning sql query
Tunning sql queryTunning sql query
Tunning sql query
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL Server
 

More from Dave Stokes

Json within a relational database
Json within a relational databaseJson within a relational database
Json within a relational databaseDave 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 2021Dave 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 doDave 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 SummitDave 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 JavaScriptDave 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 DatabaseDave 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 HistogramsDave Stokes
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationDave Stokes
 
Midwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesMidwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesDave 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 AnalyticsDave 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 FeaturesDave Stokes
 
Confoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsConfoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsDave 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 presentationDave Stokes
 
MySQL 8.0 Operational Changes
MySQL 8.0 Operational ChangesMySQL 8.0 Operational Changes
MySQL 8.0 Operational ChangesDave 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 FeaturesDave 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 StoreDave 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 MySQLDave Stokes
 

More from Dave Stokes (20)

Json within a relational database
Json within a relational databaseJson within a relational database
Json within a relational database
 
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
 
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
 
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 ...
 
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
 
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
 
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
 
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
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
 
Midwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesMidwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL Features
 
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
 
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...
 
Confoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New FeaturesConfoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New Features
 
Confoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsConfoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & Histograms
 
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!
 
MySQL Replication Update - DEbconf 2020 presentation
MySQL Replication Update - DEbconf 2020 presentationMySQL Replication Update - DEbconf 2020 presentation
MySQL Replication Update - DEbconf 2020 presentation
 
MySQL 8.0 Operational Changes
MySQL 8.0 Operational ChangesMySQL 8.0 Operational Changes
MySQL 8.0 Operational Changes
 
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
 
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
 
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
 

Recently uploaded

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 

San diegophp

  • 1. San Diego PHP Aug 2 Goldilocks And The Three Queries – MySQL's EXPLAIN Explained Dave Stokes MySQL Community Manager, North America David.Stokes@Oracle.Com
  • 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 Database 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 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 ROWS table scans ● Smaller than whole table (read from disk faster) * May need to run ● Can 'carry' other ANALYZE TABLE to update statistics such as data with cardinality to help compound optimizer make better choices indexes
  • 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 characters, does it work as well as the original 3 chars?
  • 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. Avoiding file sort Select from attendees where Id = 2 order by Name Add index sss (ID,Name)
  • 35. Things can get messy!
  • 37. 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
  • 38. 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.
  • 39. 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 – fielsorts Key_read_requerts/Key_wrtie_requests – read/write weighting of application, may need to modify application
  • 40. 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.
  • 41. Sample from the trace – but no clues on optimizing for Joe Average DBA
  • 42. Final Thoughts on EXPLAIN 1. READ chapter 7 of the MySQL Manual 2. Add index on columns in WHERE clause 3. Run ANALYZE TABLE periodically 4. Adjust buffer pool size, minimize disk I/o
  • 44. 2. Check return codes $result = mysqli_query(“SELECT Id FROM City WHERE Id = '$city_id'”); If ($result) { // Code where query executed } else { // Code when query did not execute }
  • 45. 3. Use Prepared Statements If ($stmt = mysqli_>prepare(“INSERT INTO FOO VALUES (?,?,?)”); $stmt->bind_param('ssd',$first,$last,$age); $first = 'Joe'; $last='Jones'; $age='22'; $stmt->execute(); If (!mysqli_stmt_affected_rows($stmt)) { // PROBLEM }
  • 46. 4. Be careful reporting problems mysqli_query(“DROP TABLE foo.bar”); $result = mysqli_stmt_execute($stmt); If (!$result) { // Did NOT EXECUTE printf("Error: %s.n", mysqli_stmt_error($stmt)); } Can give hackers clues!
  • 47. 5. Ask for what you need for speed SELECT * SELECT Name, Phone, FROM foo Customer_id WHERE id = $id FROM foo WHERE id=$id SLOW! FASTER!!
  • 48. Q&A

Editor's Notes

  1. Thanks for coming Intro What is new in MySQL 5.5
  2. Lawyer stuff
  3. A single 40 minute session can not turn you into a good DBA than the same time to turn a novice into a good system admin. We have been promoting MySQL on generic hardware – but sometimes you need better performance and that may require specialized hardware.
  4. Most Linux based services are CPU bound – not database servers
  5. Databases are the heart of the LAMP stack. Poor hardware choice is like an unhealthy heart.
  6. This session will cover much of what you need to know for a solid foundation to make your MySQL database per optimally but …
  7. That last 20% is where a good DBA comes in to play Indy Car example
  8. Gross over simplification! Client wants phone number for Joe from database
  9. Database server parses query, finds record in memory, returns phone number
  10. Client program proceeds with phone number
  11. Rule 1
  12. The database needs to get data not in memory off storage Also updates need to get written to disk Disk is MUCH slower than memory
  13. Another vast over simplification
  14. I/O subsystem is critical to performance. Spend money here instead of latest speedy processor.