SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
MySQL Queries Optimization
    Date and Location:   Zurich Fun tour
                         November 21 2007


    Presenting:
                         Peter Zaitsev,
                         Percona
-2-


                   Who do we have here ?
• MySQL Developers ?
• MySQL DBAs ?
• Managers ?




Название презентации или конференции (заполняется в колонтитулах)
-3-


              Query Optimization Basics
•   Avoid the query
•   Cache the query
    Simplify the query
•
•   Optimize the query




Название презентации или конференции (заполняется в колонтитулах)
-4-


                                Avoid the Query
• Do you really need this query run ?
      – Web applications quite frequently run queries and do not
        use results
• Can you get the same results from others queries
  result set ?
• Can you join several queries into one ?




Название презентации или конференции (заполняется в колонтитулах)
-5-


                               Cache the Query
• We assume you could not cache your page or page
  block which is even better
• Objects are often better to cache than query results
      – Contain results of multiple queries
      – Ready to use; save on result processing overhead
• Memcache is the leader though many variants
• Summary/Cache tables is another form of caching




Название презентации или конференции (заполняется в колонтитулах)
-6-


                            Simplify the Query
•   Simplify = make query to do less work for you
•   Are you really using all rows query delivers ?
    What is about columns ?
•
•   Can you possibly get rid of some joins to tables you
    do not use ?




Название презентации или конференции (заполняется в колонтитулах)
-7-


                           Optimize the Query
• Do it when you're sure query does just what it needs
  to
• Adding Indexes
• Changing Query
• Using special Tricks
• There is a whole next section about it




Название презентации или конференции (заполняется в колонтитулах)
-8-


      Do we really look at it this way?
• No we often have to take things from the bottom
• Look at MySQL Traffic (log and profile query load)
      – We have great patch for MySQL 5.0 to log queries with
        microsecond accuracy and a lot of other info
• Find queries which
      – Are simply too long (60 sec interactive search query)
      – Queries which cause most load on the server
• Fix them
      – Change queries and schema, cache them, rework
        application architecture if required

Название презентации или конференции (заполняется в колонтитулах)
-9-


                           Query Optimization
• Learn how MySQL Optimizer works
• Learn how MySQL Can execute queries
      – Could be it simply can't do what you want it to do
            • Especially frequent problem with Oracle converts
• Differ bad indexing from complex queries
• Have valid expectations
      – Group by of 10.000.000 rows will not be instant
• Learn to read EXPLAIN
• And profile queries to see what they do

Название презентации или конференции (заполняется в колонтитулах)
-10-


           Bad indexes or Bad Queries
• SELECT * FROM USER WHERE NAME =”Peter”
      – If this query does full table scan you have bad indexing
            • The query only needs rows with NAME=”Peter” to execute
                   – Add the index

• SELECT AVG(AGE) FROM USER GROUP BY CITY
      – This is complex query which needs to traverse all rows
      – You can make it to traverse shorter index records
            • Add index on (CITY,AGE)
      – But you can't limit it to just few records
            • Will need to rethink schema and add cache/summary table



Название презентации или конференции (заполняется в колонтитулах)
-11-


     How we build summary tables ?
• Use triggers in MySQL 5.0
      – Easy to use (single place code change)
      – Reliable as no updates can slip through
      – Can get expensive for heavy updates
• Application live Updates
      – More complex and tricky but allows optimization
            • Ie keeping counts on app side and updating once
• Periodically Refresh
      – Great if you can afford a bit stale data
      – Simple and does not affect updates
      – May be too slow on large data sizes
Название презентации или конференции (заполняется в колонтитулах)
-12-


                                Indexing Basics
• MySQL Can only use Prefixes of the index
• Index (A,B) can be used for
      – A=5, A=5 and B=5, A=5 and B>6
• But Can't be used for
      – B=6, B<2
• Only Equality/List allows second key part usage
      – A=5 and B>6 - will use 2 keyparts
      – A IN (1,2) and B=2 will use 2 key parts
      – A>5 and B=2 will use 1 key part only
            • B=2 will be checked while reading row/index only

Название презентации или конференции (заполняется в колонтитулах)
-13-


             Using Indexes for Order By
•   Even more restricted !
•   Having same index (A,B)
    A=5 ORDER BY B - Will use index
•
•   A>5 ORDER BY B - Will not use index
•   A IN (1,2) ORDER BY B – Does not help either
    A>5 ORDER BY A - Will
•
    ORDER BY A ASC B DESC – Does not
•
      – You have to do sorting in the same order for it to use index



Название презентации или конференции (заполняется в колонтитулах)
-14-


                              Covering Indexes
• Very Powerful, often forgotten choice
• Allows to read data from index only, not touching
  data file
• Helps because index is typically smaller and it is
  sorted
      – (appropriate data likely needs random access)
• SELECT NAME WHERE LOGIN=”Jack234”
      – KEY(LOGIN,NAME) avoid to skip data read
• It is all or none in MySQL 5.0
      – Either all columns should be checked from the index or
        data will be read
Название презентации или конференции (заполняется в колонтитулах)
-15-


                                                  LIMIT
• Limit result set. Do not fetch 100 rows if you use 10
      – Though “prefetching and caching” can be helpful ie for
        search applications
• LIMIT helps the most when you have index used for
  sorting
      – “Using Temporary”, “Using Filesort” take out most of the
        LIMIT benefit
• Beware of large Limit
      – LIMIT 100000,10 will fetch and discard first 100000 rows
      – Do not use LIMIT cycle in batch applications


Название презентации или конференции (заполняется в колонтитулах)
-16-


                             More about LIMIT
• Limit and Rankings
• If you can precompute positions do it
      – WHERE POS BETWEEN 1001 and 1010 works much
        better than LIMIT 1000,10
• Beware SQL_CALC_FOUND_ROWS
      – Extra count(*) may be faster because it can often use
        covering index
            • Still very slow for large result sets though
• Protect your application from large limits
      – People may not go to page 500 but search engine bots
        well may do.
Название презентации или конференции (заполняется в колонтитулах)
-17-


                                        GROUP BY
• Nasty one
      – hides complexity as you get just couple of rows back
• Multiple ways to execute GROUP BY
      – Index traversal (or skip-scan)
            • If index fully matches GROUP BY Clause
      – Using temporary table
            • Good for small result set, hint SQL_SMALL_RESULT
      – Using filesort
            • Good for large result set, hint SQL_BIG_RESULT
• Can use ORDER BY NULL to avoid extra sort
      – MySQL always sorts data for group by otherwise
Название презентации или конференции (заполняется в колонтитулах)
-18-


                                                  JOINs
• Joins are very expensive
      – 10-20 for in memory accesses, 100-1000 for disk
• MySQL only has (Optimized) nested loops joins
• If you're to traverse through a lot of rows –
  denormalize
      – There are other benefits as more flexible indexing
        strategies as well.
• “Delayed Join” - Join only to get full rows when you
  need


Название презентации или конференции (заполняется в колонтитулах)
-19-


                     Delayed Join Example
• SELECT visitor_id, url FROM (SELECT id FROM log
  WHERE ip=”123.45.67.89” ORDER BY ts DESC
  LIMIT 50,10) l JOIN log ON (l.id=log.id) JOIN url on
  (url.id=log.url_id) ORDER BY TS DESC;
• Looks silly but it works well
          Fetch from log records using covering index on (IP,TS,ID)
      –
      –   Perform LIMIT exclusion traversing index only
      –   When do self join to get other columns from log table
          And more info, such as page url from the joined url page
      –



Название презентации или конференции (заполняется в колонтитулах)
-20-


                                       Sub Queries
• Can be poorly optimized in MySQL 5.0
      – Though good work in progress for MySQL 6.0
• No In-Out transformation for subqueries
      – SELECT * FROM A WHERE ID IN (SELECT ID FROM B)
• No “Caching” of non-scalar resultset even when
  possible
• Subselects in FROM clause result in temporary
  tables without any indexes



Название презентации или конференции (заполняется в колонтитулах)
-21-


                             Views and Unions
• VIEWS – Never help performance
      – But can cause problems by hiding complexity
• Can be executed as MERGE or TEMORARY TABLE
• MySQL Can't push WHERE Clauses to temporary
  table
      – VIEW: SELECT country, COUNT(*) cnt FROM COUNTRY
        GROUP BY country;
      – SELECT * FROM v WHERE country=”USA”
            • Will create temporary table populate and discard the rest.
      – Same applies to ORDER BY/LIMIT w UNION
• UNION ALL also needs temporary table
Название презентации или конференции (заполняется в колонтитулах)
-22-


                                           That is it !
• It was short
      – But I hope you've learned something
      – Contact me with questions
            • pz@mysqlperformanceblog.com
      – Our blog
            • http://www.mysqlperformanceblog.com
      – Commercial Services
            • http://www.percona.com




Название презентации или конференции (заполняется в колонтитулах)

Mais conteúdo relacionado

Mais procurados

Sc2009autumn 次世代Daoフレームワーク Doma
Sc2009autumn 次世代Daoフレームワーク DomaSc2009autumn 次世代Daoフレームワーク Doma
Sc2009autumn 次世代Daoフレームワーク DomaToshihiro Nakamura
 
Web應用程式以及資安問題的探討
Web應用程式以及資安問題的探討Web應用程式以及資安問題的探討
Web應用程式以及資安問題的探討Mu Chun Wang
 
اف تي بي
اف تي بياف تي بي
اف تي بيnansyrigan
 
俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1482
俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1482俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1482
俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1482Turkmenistan Laws
 
ミクシィ決算説明資料 FY2008 2Q
ミクシィ決算説明資料 FY2008 2Qミクシィ決算説明資料 FY2008 2Q
ミクシィ決算説明資料 FY2008 2QMaki Fujita
 
PHP - עבר הווה ועתיד
PHP - עבר הווה ועתידPHP - עבר הווה ועתיד
PHP - עבר הווה ועתידShahar Evron
 
Austin macauley publishers
Austin macauley publishersAustin macauley publishers
Austin macauley publishersmahmoudAhmed681
 
Serendipitous searching for graded readers
Serendipitous searching for graded readersSerendipitous searching for graded readers
Serendipitous searching for graded readersDubhgan Hinchey
 
كتاب الذكاء العاطفي دانييل جولمان
كتاب الذكاء العاطفي   دانييل جولمانكتاب الذكاء العاطفي   دانييل جولمان
كتاب الذكاء العاطفي دانييل جولمانhamada13
 
FPGAによるホームサービスロボットのための組込脳型計算機システム
FPGAによるホームサービスロボットのための組込脳型計算機システムFPGAによるホームサービスロボットのための組込脳型計算機システム
FPGAによるホームサービスロボットのための組込脳型計算機システム直久 住川
 
Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信
Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信
Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信Yusuke Kawasaki
 
俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3088
俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3088俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3088
俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3088Azerbaijan Laws
 

Mais procurados (18)

Sc2009autumn 次世代Daoフレームワーク Doma
Sc2009autumn 次世代Daoフレームワーク DomaSc2009autumn 次世代Daoフレームワーク Doma
Sc2009autumn 次世代Daoフレームワーク Doma
 
Web應用程式以及資安問題的探討
Web應用程式以及資安問題的探討Web應用程式以及資安問題的探討
Web應用程式以及資安問題的探討
 
اف تي بي
اف تي بياف تي بي
اف تي بي
 
Spring Framework勉強会
Spring  Framework勉強会Spring  Framework勉強会
Spring Framework勉強会
 
俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1482
俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1482俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1482
俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1482
 
ミクシィ決算説明資料 FY2008 2Q
ミクシィ決算説明資料 FY2008 2Qミクシィ決算説明資料 FY2008 2Q
ミクシィ決算説明資料 FY2008 2Q
 
PHP - עבר הווה ועתיד
PHP - עבר הווה ועתידPHP - עבר הווה ועתיד
PHP - עבר הווה ועתיד
 
Austin macauley publishers
Austin macauley publishersAustin macauley publishers
Austin macauley publishers
 
20210119 OCIJP#14 オラクル大橋資料
20210119 OCIJP#14 オラクル大橋資料20210119 OCIJP#14 オラクル大橋資料
20210119 OCIJP#14 オラクル大橋資料
 
PHP超入門@LL温泉
PHP超入門@LL温泉PHP超入門@LL温泉
PHP超入門@LL温泉
 
Avinash Kuma1
Avinash Kuma1Avinash Kuma1
Avinash Kuma1
 
Serendipitous searching for graded readers
Serendipitous searching for graded readersSerendipitous searching for graded readers
Serendipitous searching for graded readers
 
كتاب الذكاء العاطفي دانييل جولمان
كتاب الذكاء العاطفي   دانييل جولمانكتاب الذكاء العاطفي   دانييل جولمان
كتاب الذكاء العاطفي دانييل جولمان
 
It Flyer Page08
It Flyer Page08It Flyer Page08
It Flyer Page08
 
FPGAによるホームサービスロボットのための組込脳型計算機システム
FPGAによるホームサービスロボットのための組込脳型計算機システムFPGAによるホームサービスロボットのための組込脳型計算機システム
FPGAによるホームサービスロボットのための組込脳型計算機システム
 
Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信
Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信
Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信
 
俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3088
俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3088俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3088
俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3088
 
Revista Digital Esika Junho 2013
Revista Digital Esika Junho 2013Revista Digital Esika Junho 2013
Revista Digital Esika Junho 2013
 

Destaque

Advanced MySQL Query Tuning
Advanced MySQL Query TuningAdvanced MySQL Query Tuning
Advanced MySQL Query TuningAlexander Rubin
 
Building High Performance MySql Query Systems And Analytic Applications
Building High Performance MySql Query Systems And Analytic ApplicationsBuilding High Performance MySql Query Systems And Analytic Applications
Building High Performance MySql Query Systems And Analytic Applicationsguest40cda0b
 
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
 
56 Query Optimization
56 Query Optimization56 Query Optimization
56 Query OptimizationMYXPLAIN
 
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxMYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxPythian
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimizationBaohua Cai
 
Query Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New TricksQuery Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New TricksMYXPLAIN
 
Tunning sql query
Tunning sql queryTunning sql query
Tunning sql queryvuhaininh88
 
MySQL Query tuning 101
MySQL Query tuning 101MySQL Query tuning 101
MySQL Query tuning 101Sveta Smirnova
 
Advanced MySQL Query and Schema Tuning
Advanced MySQL Query and Schema TuningAdvanced MySQL Query and Schema Tuning
Advanced MySQL Query and Schema TuningMYXPLAIN
 
MySQL Query Optimization
MySQL Query OptimizationMySQL Query Optimization
MySQL Query OptimizationMorgan Tocker
 
Webinar 2013 advanced_query_tuning
Webinar 2013 advanced_query_tuningWebinar 2013 advanced_query_tuning
Webinar 2013 advanced_query_tuning晓 周
 
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013Jaime Crespo
 
Query Optimization with MySQL 5.7 and MariaDB 10: Even newer tricks
Query Optimization with MySQL 5.7 and MariaDB 10: Even newer tricksQuery Optimization with MySQL 5.7 and MariaDB 10: Even newer tricks
Query Optimization with MySQL 5.7 and MariaDB 10: Even newer tricksJaime Crespo
 
MySQL Query Optimization (Basics)
MySQL Query Optimization (Basics)MySQL Query Optimization (Basics)
MySQL Query Optimization (Basics)Karthik .P.R
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index TuningManikanda kumar
 
Percona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationPercona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationmysqlops
 

Destaque (20)

Advanced MySQL Query Tuning
Advanced MySQL Query TuningAdvanced MySQL Query Tuning
Advanced MySQL Query Tuning
 
Building High Performance MySql Query Systems And Analytic Applications
Building High Performance MySql Query Systems And Analytic ApplicationsBuilding High Performance MySql Query Systems And Analytic Applications
Building High Performance MySql Query Systems And Analytic Applications
 
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
 
56 Query Optimization
56 Query Optimization56 Query Optimization
56 Query Optimization
 
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxMYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimization
 
Query Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New TricksQuery Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New Tricks
 
Tunning sql query
Tunning sql queryTunning sql query
Tunning sql query
 
MySQL Query tuning 101
MySQL Query tuning 101MySQL Query tuning 101
MySQL Query tuning 101
 
Advanced MySQL Query and Schema Tuning
Advanced MySQL Query and Schema TuningAdvanced MySQL Query and Schema Tuning
Advanced MySQL Query and Schema Tuning
 
MySQL Query Optimization
MySQL Query OptimizationMySQL Query Optimization
MySQL Query Optimization
 
My sql optimization
My sql optimizationMy sql optimization
My sql optimization
 
Webinar 2013 advanced_query_tuning
Webinar 2013 advanced_query_tuningWebinar 2013 advanced_query_tuning
Webinar 2013 advanced_query_tuning
 
MySQL Query Optimization.
MySQL Query Optimization.MySQL Query Optimization.
MySQL Query Optimization.
 
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
 
Query Optimization with MySQL 5.7 and MariaDB 10: Even newer tricks
Query Optimization with MySQL 5.7 and MariaDB 10: Even newer tricksQuery Optimization with MySQL 5.7 and MariaDB 10: Even newer tricks
Query Optimization with MySQL 5.7 and MariaDB 10: Even newer tricks
 
MySQL Query Optimization (Basics)
MySQL Query Optimization (Basics)MySQL Query Optimization (Basics)
MySQL Query Optimization (Basics)
 
Sql query patterns, optimized
Sql query patterns, optimizedSql query patterns, optimized
Sql query patterns, optimized
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
Percona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationPercona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimization
 

Semelhante a Zurich2007 MySQL Query Optimization

query optimization
query optimizationquery optimization
query optimizationDimara Hakim
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvcsef2009
 
20080424 Cdb2008 Postgresql News Bartunov
20080424 Cdb2008 Postgresql News Bartunov20080424 Cdb2008 Postgresql News Bartunov
20080424 Cdb2008 Postgresql News BartunovNikolay Samokhvalov
 
MySQL Clusterで高性能システムを構築する際のポイント
MySQL Clusterで高性能システムを構築する際のポイントMySQL Clusterで高性能システムを構築する際のポイント
MySQL Clusterで高性能システムを構築する際のポイントK H
 
11 Net Scaler Xa1
11 Net Scaler Xa111 Net Scaler Xa1
11 Net Scaler Xa1Liudmila Li
 
Что такое ASP.NET MVC?
Что такое ASP.NET MVC?Что такое ASP.NET MVC?
Что такое ASP.NET MVC?Dima Pasko
 
HA+DRBD+Postgres - PostgresWest '08
HA+DRBD+Postgres - PostgresWest '08HA+DRBD+Postgres - PostgresWest '08
HA+DRBD+Postgres - PostgresWest '08Jesse Young
 
P2P Bug Tracking with SD
P2P Bug Tracking with SDP2P Bug Tracking with SD
P2P Bug Tracking with SDJesse Vincent
 
20090323 Phpstudy
20090323 Phpstudy20090323 Phpstudy
20090323 PhpstudyYusuke Ando
 
тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009Liudmila Li
 
4200 Kte7.0 Training V1.0
4200 Kte7.0 Training V1.04200 Kte7.0 Training V1.0
4200 Kte7.0 Training V1.0wayneliao
 
Itpub电子杂志(第三期)
Itpub电子杂志(第三期)Itpub电子杂志(第三期)
Itpub电子杂志(第三期)yiditushe
 
421 Ch
421 Ch421 Ch
421 Chanjaan
 
Understanding Web Services
Understanding Web ServicesUnderstanding Web Services
Understanding Web Servicesaru85
 
Ruby on Rails at HackDay in Saint Petersburg
Ruby on Rails at HackDay in Saint PetersburgRuby on Rails at HackDay in Saint Petersburg
Ruby on Rails at HackDay in Saint PetersburgAlexander Krass
 

Semelhante a Zurich2007 MySQL Query Optimization (20)

query optimization
query optimizationquery optimization
query optimization
 
20070329 Phpconf2007 Training
20070329 Phpconf2007 Training20070329 Phpconf2007 Training
20070329 Phpconf2007 Training
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
20080424 Cdb2008 Postgresql News Bartunov
20080424 Cdb2008 Postgresql News Bartunov20080424 Cdb2008 Postgresql News Bartunov
20080424 Cdb2008 Postgresql News Bartunov
 
MySQL Clusterで高性能システムを構築する際のポイント
MySQL Clusterで高性能システムを構築する際のポイントMySQL Clusterで高性能システムを構築する際のポイント
MySQL Clusterで高性能システムを構築する際のポイント
 
11 Net Scaler Xa1
11 Net Scaler Xa111 Net Scaler Xa1
11 Net Scaler Xa1
 
Что такое ASP.NET MVC?
Что такое ASP.NET MVC?Что такое ASP.NET MVC?
Что такое ASP.NET MVC?
 
Grails紹介
Grails紹介Grails紹介
Grails紹介
 
HA+DRBD+Postgres - PostgresWest '08
HA+DRBD+Postgres - PostgresWest '08HA+DRBD+Postgres - PostgresWest '08
HA+DRBD+Postgres - PostgresWest '08
 
20070613 Rit2007 Training
20070613 Rit2007 Training20070613 Rit2007 Training
20070613 Rit2007 Training
 
P2P Bug Tracking with SD
P2P Bug Tracking with SDP2P Bug Tracking with SD
P2P Bug Tracking with SD
 
Practical MySQL
Practical MySQLPractical MySQL
Practical MySQL
 
20090323 Phpstudy
20090323 Phpstudy20090323 Phpstudy
20090323 Phpstudy
 
тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009
 
4200 Kte7.0 Training V1.0
4200 Kte7.0 Training V1.04200 Kte7.0 Training V1.0
4200 Kte7.0 Training V1.0
 
Itpub电子杂志(第三期)
Itpub电子杂志(第三期)Itpub电子杂志(第三期)
Itpub电子杂志(第三期)
 
Revisited
RevisitedRevisited
Revisited
 
421 Ch
421 Ch421 Ch
421 Ch
 
Understanding Web Services
Understanding Web ServicesUnderstanding Web Services
Understanding Web Services
 
Ruby on Rails at HackDay in Saint Petersburg
Ruby on Rails at HackDay in Saint PetersburgRuby on Rails at HackDay in Saint Petersburg
Ruby on Rails at HackDay in Saint Petersburg
 

Último

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Último (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Zurich2007 MySQL Query Optimization

  • 1. MySQL Queries Optimization Date and Location: Zurich Fun tour November 21 2007 Presenting: Peter Zaitsev, Percona
  • 2. -2- Who do we have here ? • MySQL Developers ? • MySQL DBAs ? • Managers ? Название презентации или конференции (заполняется в колонтитулах)
  • 3. -3- Query Optimization Basics • Avoid the query • Cache the query Simplify the query • • Optimize the query Название презентации или конференции (заполняется в колонтитулах)
  • 4. -4- Avoid the Query • Do you really need this query run ? – Web applications quite frequently run queries and do not use results • Can you get the same results from others queries result set ? • Can you join several queries into one ? Название презентации или конференции (заполняется в колонтитулах)
  • 5. -5- Cache the Query • We assume you could not cache your page or page block which is even better • Objects are often better to cache than query results – Contain results of multiple queries – Ready to use; save on result processing overhead • Memcache is the leader though many variants • Summary/Cache tables is another form of caching Название презентации или конференции (заполняется в колонтитулах)
  • 6. -6- Simplify the Query • Simplify = make query to do less work for you • Are you really using all rows query delivers ? What is about columns ? • • Can you possibly get rid of some joins to tables you do not use ? Название презентации или конференции (заполняется в колонтитулах)
  • 7. -7- Optimize the Query • Do it when you're sure query does just what it needs to • Adding Indexes • Changing Query • Using special Tricks • There is a whole next section about it Название презентации или конференции (заполняется в колонтитулах)
  • 8. -8- Do we really look at it this way? • No we often have to take things from the bottom • Look at MySQL Traffic (log and profile query load) – We have great patch for MySQL 5.0 to log queries with microsecond accuracy and a lot of other info • Find queries which – Are simply too long (60 sec interactive search query) – Queries which cause most load on the server • Fix them – Change queries and schema, cache them, rework application architecture if required Название презентации или конференции (заполняется в колонтитулах)
  • 9. -9- Query Optimization • Learn how MySQL Optimizer works • Learn how MySQL Can execute queries – Could be it simply can't do what you want it to do • Especially frequent problem with Oracle converts • Differ bad indexing from complex queries • Have valid expectations – Group by of 10.000.000 rows will not be instant • Learn to read EXPLAIN • And profile queries to see what they do Название презентации или конференции (заполняется в колонтитулах)
  • 10. -10- Bad indexes or Bad Queries • SELECT * FROM USER WHERE NAME =”Peter” – If this query does full table scan you have bad indexing • The query only needs rows with NAME=”Peter” to execute – Add the index • SELECT AVG(AGE) FROM USER GROUP BY CITY – This is complex query which needs to traverse all rows – You can make it to traverse shorter index records • Add index on (CITY,AGE) – But you can't limit it to just few records • Will need to rethink schema and add cache/summary table Название презентации или конференции (заполняется в колонтитулах)
  • 11. -11- How we build summary tables ? • Use triggers in MySQL 5.0 – Easy to use (single place code change) – Reliable as no updates can slip through – Can get expensive for heavy updates • Application live Updates – More complex and tricky but allows optimization • Ie keeping counts on app side and updating once • Periodically Refresh – Great if you can afford a bit stale data – Simple and does not affect updates – May be too slow on large data sizes Название презентации или конференции (заполняется в колонтитулах)
  • 12. -12- Indexing Basics • MySQL Can only use Prefixes of the index • Index (A,B) can be used for – A=5, A=5 and B=5, A=5 and B>6 • But Can't be used for – B=6, B<2 • Only Equality/List allows second key part usage – A=5 and B>6 - will use 2 keyparts – A IN (1,2) and B=2 will use 2 key parts – A>5 and B=2 will use 1 key part only • B=2 will be checked while reading row/index only Название презентации или конференции (заполняется в колонтитулах)
  • 13. -13- Using Indexes for Order By • Even more restricted ! • Having same index (A,B) A=5 ORDER BY B - Will use index • • A>5 ORDER BY B - Will not use index • A IN (1,2) ORDER BY B – Does not help either A>5 ORDER BY A - Will • ORDER BY A ASC B DESC – Does not • – You have to do sorting in the same order for it to use index Название презентации или конференции (заполняется в колонтитулах)
  • 14. -14- Covering Indexes • Very Powerful, often forgotten choice • Allows to read data from index only, not touching data file • Helps because index is typically smaller and it is sorted – (appropriate data likely needs random access) • SELECT NAME WHERE LOGIN=”Jack234” – KEY(LOGIN,NAME) avoid to skip data read • It is all or none in MySQL 5.0 – Either all columns should be checked from the index or data will be read Название презентации или конференции (заполняется в колонтитулах)
  • 15. -15- LIMIT • Limit result set. Do not fetch 100 rows if you use 10 – Though “prefetching and caching” can be helpful ie for search applications • LIMIT helps the most when you have index used for sorting – “Using Temporary”, “Using Filesort” take out most of the LIMIT benefit • Beware of large Limit – LIMIT 100000,10 will fetch and discard first 100000 rows – Do not use LIMIT cycle in batch applications Название презентации или конференции (заполняется в колонтитулах)
  • 16. -16- More about LIMIT • Limit and Rankings • If you can precompute positions do it – WHERE POS BETWEEN 1001 and 1010 works much better than LIMIT 1000,10 • Beware SQL_CALC_FOUND_ROWS – Extra count(*) may be faster because it can often use covering index • Still very slow for large result sets though • Protect your application from large limits – People may not go to page 500 but search engine bots well may do. Название презентации или конференции (заполняется в колонтитулах)
  • 17. -17- GROUP BY • Nasty one – hides complexity as you get just couple of rows back • Multiple ways to execute GROUP BY – Index traversal (or skip-scan) • If index fully matches GROUP BY Clause – Using temporary table • Good for small result set, hint SQL_SMALL_RESULT – Using filesort • Good for large result set, hint SQL_BIG_RESULT • Can use ORDER BY NULL to avoid extra sort – MySQL always sorts data for group by otherwise Название презентации или конференции (заполняется в колонтитулах)
  • 18. -18- JOINs • Joins are very expensive – 10-20 for in memory accesses, 100-1000 for disk • MySQL only has (Optimized) nested loops joins • If you're to traverse through a lot of rows – denormalize – There are other benefits as more flexible indexing strategies as well. • “Delayed Join” - Join only to get full rows when you need Название презентации или конференции (заполняется в колонтитулах)
  • 19. -19- Delayed Join Example • SELECT visitor_id, url FROM (SELECT id FROM log WHERE ip=”123.45.67.89” ORDER BY ts DESC LIMIT 50,10) l JOIN log ON (l.id=log.id) JOIN url on (url.id=log.url_id) ORDER BY TS DESC; • Looks silly but it works well Fetch from log records using covering index on (IP,TS,ID) – – Perform LIMIT exclusion traversing index only – When do self join to get other columns from log table And more info, such as page url from the joined url page – Название презентации или конференции (заполняется в колонтитулах)
  • 20. -20- Sub Queries • Can be poorly optimized in MySQL 5.0 – Though good work in progress for MySQL 6.0 • No In-Out transformation for subqueries – SELECT * FROM A WHERE ID IN (SELECT ID FROM B) • No “Caching” of non-scalar resultset even when possible • Subselects in FROM clause result in temporary tables without any indexes Название презентации или конференции (заполняется в колонтитулах)
  • 21. -21- Views and Unions • VIEWS – Never help performance – But can cause problems by hiding complexity • Can be executed as MERGE or TEMORARY TABLE • MySQL Can't push WHERE Clauses to temporary table – VIEW: SELECT country, COUNT(*) cnt FROM COUNTRY GROUP BY country; – SELECT * FROM v WHERE country=”USA” • Will create temporary table populate and discard the rest. – Same applies to ORDER BY/LIMIT w UNION • UNION ALL also needs temporary table Название презентации или конференции (заполняется в колонтитулах)
  • 22. -22- That is it ! • It was short – But I hope you've learned something – Contact me with questions • pz@mysqlperformanceblog.com – Our blog • http://www.mysqlperformanceblog.com – Commercial Services • http://www.percona.com Название презентации или конференции (заполняется в колонтитулах)