SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
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




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

Weitere ähnliche Inhalte

Was ist angesagt?

Itpub电子杂志(第一期)
Itpub电子杂志(第一期)Itpub电子杂志(第一期)
Itpub电子杂志(第一期)
yiditushe
 
JBoss Application Server 入門 ~ Seasar2を動かして見よう!~ on Seasar Conference 2009 White
JBoss Application Server 入門~ Seasar2を動かして見よう!~ on Seasar Conference 2009 WhiteJBoss Application Server 入門~ Seasar2を動かして見よう!~ on Seasar Conference 2009 White
JBoss Application Server 入門 ~ Seasar2を動かして見よう!~ on Seasar Conference 2009 White
bose999
 
ミクシィ決算説明資料 FY2008 2Q
ミクシィ決算説明資料 FY2008 2Qミクシィ決算説明資料 FY2008 2Q
ミクシィ決算説明資料 FY2008 2Q
Maki Fujita
 
技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac
terada
 
اف تي بي
اف تي بياف تي بي
اف تي بي
nansyrigan
 
Sc2009autumn 次世代Daoフレームワーク Doma
Sc2009autumn 次世代Daoフレームワーク DomaSc2009autumn 次世代Daoフレームワーク Doma
Sc2009autumn 次世代Daoフレームワーク Doma
Toshihiro Nakamura
 
Linux Commands
Linux CommandsLinux Commands
Linux Commands
iwata
 

Was ist angesagt? (19)

MySQL Clusterで高性能システムを構築する際のポイント
MySQL Clusterで高性能システムを構築する際のポイントMySQL Clusterで高性能システムを構築する際のポイント
MySQL Clusterで高性能システムを構築する際のポイント
 
mohsin khan ki kitab
mohsin khan ki kitabmohsin khan ki kitab
mohsin khan ki kitab
 
俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3705
俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3705俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3705
俄语GOST标准,技术规范,法律,法规,中文英语,目录编号RG 3705
 
Ruby on Rails Tutorial Part I
Ruby on Rails Tutorial Part IRuby on Rails Tutorial Part I
Ruby on Rails Tutorial Part I
 
20210119 OCIJP#14 オラクル大橋資料
20210119 OCIJP#14 オラクル大橋資料20210119 OCIJP#14 オラクル大橋資料
20210119 OCIJP#14 オラクル大橋資料
 
Itpub电子杂志(第一期)
Itpub电子杂志(第一期)Itpub电子杂志(第一期)
Itpub电子杂志(第一期)
 
Spring Framework勉強会
Spring  Framework勉強会Spring  Framework勉強会
Spring Framework勉強会
 
ZOZOTOWNのマルチクラウドへの挑戦と挫折、そして未来
ZOZOTOWNのマルチクラウドへの挑戦と挫折、そして未来ZOZOTOWNのマルチクラウドへの挑戦と挫折、そして未来
ZOZOTOWNのマルチクラウドへの挑戦と挫折、そして未来
 
JBoss Application Server 入門 ~ Seasar2を動かして見よう!~ on Seasar Conference 2009 White
JBoss Application Server 入門~ Seasar2を動かして見よう!~ on Seasar Conference 2009 WhiteJBoss Application Server 入門~ Seasar2を動かして見よう!~ on Seasar Conference 2009 White
JBoss Application Server 入門 ~ Seasar2を動かして見よう!~ on Seasar Conference 2009 White
 
ミクシィ決算説明資料 FY2008 2Q
ミクシィ決算説明資料 FY2008 2Qミクシィ決算説明資料 FY2008 2Q
ミクシィ決算説明資料 FY2008 2Q
 
技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac
 
اف تي بي
اف تي بياف تي بي
اف تي بي
 
俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1457
俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1457俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1457
俄罗斯进出口标准,技术规格,法律,法规,中英文,目录编号RG 1457
 
PHP超入門@LL温泉
PHP超入門@LL温泉PHP超入門@LL温泉
PHP超入門@LL温泉
 
Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信
Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信
Cloud era -『クラウド時代』マッシュアップ技術による地方からの世界発信
 
自作言語でお絵描き
自作言語でお絵描き自作言語でお絵描き
自作言語でお絵描き
 
FPGAによるホームサービスロボットのための組込脳型計算機システム
FPGAによるホームサービスロボットのための組込脳型計算機システムFPGAによるホームサービスロボットのための組込脳型計算機システム
FPGAによるホームサービスロボットのための組込脳型計算機システム
 
Sc2009autumn 次世代Daoフレームワーク Doma
Sc2009autumn 次世代Daoフレームワーク DomaSc2009autumn 次世代Daoフレームワーク Doma
Sc2009autumn 次世代Daoフレームワーク Doma
 
Linux Commands
Linux CommandsLinux Commands
Linux Commands
 

Andere mochten auch

Pemrograman Modular
Pemrograman ModularPemrograman Modular
Pemrograman Modular
Dimara Hakim
 
Simulasi - Pertemuan I
Simulasi - Pertemuan ISimulasi - Pertemuan I
Simulasi - Pertemuan I
Dimara Hakim
 
Struktur Level Data
Struktur Level DataStruktur Level Data
Struktur Level Data
Dimara Hakim
 
Simulasi - Pertemuan III
Simulasi - Pertemuan IIISimulasi - Pertemuan III
Simulasi - Pertemuan III
Dimara Hakim
 
JENI Slides-Intro1-Bab06-Struktur kontrol
JENI Slides-Intro1-Bab06-Struktur kontrolJENI Slides-Intro1-Bab06-Struktur kontrol
JENI Slides-Intro1-Bab06-Struktur kontrol
Dimara Hakim
 
Struktur Level Program
Struktur Level ProgramStruktur Level Program
Struktur Level Program
Dimara Hakim
 
Simulasi - Pertemuan IV
Simulasi - Pertemuan IVSimulasi - Pertemuan IV
Simulasi - Pertemuan IV
Dimara Hakim
 
Simulasi - Pertemuan II
Simulasi - Pertemuan IISimulasi - Pertemuan II
Simulasi - Pertemuan II
Dimara Hakim
 
Tugas simulasi 5211100111
Tugas simulasi 5211100111Tugas simulasi 5211100111
Tugas simulasi 5211100111
Aula Ayubi
 
ANALISA SISTEM ANTRIAN PADA PELAYANAN PENGISIAN BBM DI SPBU PERTAMINA
ANALISA SISTEM ANTRIAN PADA PELAYANAN PENGISIAN BBM DI SPBU PERTAMINAANALISA SISTEM ANTRIAN PADA PELAYANAN PENGISIAN BBM DI SPBU PERTAMINA
ANALISA SISTEM ANTRIAN PADA PELAYANAN PENGISIAN BBM DI SPBU PERTAMINA
Perguruan Tinggi Raharja
 
Contoh soal Teori antrian khusus Poisson
Contoh soal Teori antrian khusus PoissonContoh soal Teori antrian khusus Poisson
Contoh soal Teori antrian khusus Poisson
Lilies DLiestyowati
 

Andere mochten auch (19)

Pemrograman Modular
Pemrograman ModularPemrograman Modular
Pemrograman Modular
 
Simulasi - Pertemuan I
Simulasi - Pertemuan ISimulasi - Pertemuan I
Simulasi - Pertemuan I
 
Struktur Level Data
Struktur Level DataStruktur Level Data
Struktur Level Data
 
Simulasi - Pertemuan III
Simulasi - Pertemuan IIISimulasi - Pertemuan III
Simulasi - Pertemuan III
 
JENI Slides-Intro1-Bab06-Struktur kontrol
JENI Slides-Intro1-Bab06-Struktur kontrolJENI Slides-Intro1-Bab06-Struktur kontrol
JENI Slides-Intro1-Bab06-Struktur kontrol
 
Struktur Level Program
Struktur Level ProgramStruktur Level Program
Struktur Level Program
 
Simulasi - Pertemuan IV
Simulasi - Pertemuan IVSimulasi - Pertemuan IV
Simulasi - Pertemuan IV
 
Desain Top Down
Desain Top DownDesain Top Down
Desain Top Down
 
Makalah teori antrian (SISTEM ANTRIAN MM TAK HINGGA)
Makalah teori antrian (SISTEM ANTRIAN MM TAK HINGGA)Makalah teori antrian (SISTEM ANTRIAN MM TAK HINGGA)
Makalah teori antrian (SISTEM ANTRIAN MM TAK HINGGA)
 
Simulasi - Pertemuan II
Simulasi - Pertemuan IISimulasi - Pertemuan II
Simulasi - Pertemuan II
 
Denormalisasi
DenormalisasiDenormalisasi
Denormalisasi
 
Tugas simulasi 5211100111
Tugas simulasi 5211100111Tugas simulasi 5211100111
Tugas simulasi 5211100111
 
Transaction
TransactionTransaction
Transaction
 
PENDAHULUAN. SISTEM, MODEL, DAN SIMULASI
PENDAHULUAN. SISTEM, MODEL, DAN SIMULASIPENDAHULUAN. SISTEM, MODEL, DAN SIMULASI
PENDAHULUAN. SISTEM, MODEL, DAN SIMULASI
 
Teori antrian
Teori antrianTeori antrian
Teori antrian
 
ANALISA SISTEM ANTRIAN PADA PELAYANAN PENGISIAN BBM DI SPBU PERTAMINA
ANALISA SISTEM ANTRIAN PADA PELAYANAN PENGISIAN BBM DI SPBU PERTAMINAANALISA SISTEM ANTRIAN PADA PELAYANAN PENGISIAN BBM DI SPBU PERTAMINA
ANALISA SISTEM ANTRIAN PADA PELAYANAN PENGISIAN BBM DI SPBU PERTAMINA
 
Contoh tugas besar pemodelan sistem
Contoh tugas besar pemodelan sistemContoh tugas besar pemodelan sistem
Contoh tugas besar pemodelan sistem
 
Contoh soal Teori antrian khusus Poisson
Contoh soal Teori antrian khusus PoissonContoh soal Teori antrian khusus Poisson
Contoh soal Teori antrian khusus Poisson
 
ANALISIS SISTEM ANTRIAN SERVICE MOBIL DI PT. TUNAS MOBILINDO PERKASA DENGAN M...
ANALISIS SISTEM ANTRIAN SERVICE MOBIL DI PT. TUNAS MOBILINDO PERKASA DENGAN M...ANALISIS SISTEM ANTRIAN SERVICE MOBIL DI PT. TUNAS MOBILINDO PERKASA DENGAN M...
ANALISIS SISTEM ANTRIAN SERVICE MOBIL DI PT. TUNAS MOBILINDO PERKASA DENGAN M...
 

Ähnlich wie query optimization

Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
sef2009
 
11 Net Scaler Xa1
11 Net Scaler Xa111 Net Scaler Xa1
11 Net Scaler Xa1
Liudmila Li
 
20090323 Phpstudy
20090323 Phpstudy20090323 Phpstudy
20090323 Phpstudy
Yusuke Ando
 
тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009
Liudmila Li
 
Understanding Web Services
Understanding Web ServicesUnderstanding Web Services
Understanding Web Services
aru85
 
Understanding Web Services
Understanding Web ServicesUnderstanding Web Services
Understanding Web Services
aru85
 
11 Ban Net Scaler Xa
11 Ban Net Scaler Xa11 Ban Net Scaler Xa
11 Ban Net Scaler Xa
Liudmila Li
 
企业级搜索引擎Solr交流
企业级搜索引擎Solr交流企业级搜索引擎Solr交流
企业级搜索引擎Solr交流
chuan liang
 

Ähnlich wie query optimization (20)

Zurich2007 MySQL Query Optimization
Zurich2007 MySQL Query OptimizationZurich2007 MySQL Query Optimization
Zurich2007 MySQL Query Optimization
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
20070329 Phpconf2007 Training
20070329 Phpconf2007 Training20070329 Phpconf2007 Training
20070329 Phpconf2007 Training
 
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?
 
HA+DRBD+Postgres - PostgresWest '08
HA+DRBD+Postgres - PostgresWest '08HA+DRBD+Postgres - PostgresWest '08
HA+DRBD+Postgres - PostgresWest '08
 
P2P Bug Tracking with SD
P2P Bug Tracking with SDP2P Bug Tracking with SD
P2P Bug Tracking with SD
 
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
 
Mysql Optimization
Mysql OptimizationMysql Optimization
Mysql Optimization
 
Practical MySQL
Practical MySQLPractical MySQL
Practical MySQL
 
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
 
Understanding Web Services
Understanding Web ServicesUnderstanding Web Services
Understanding Web Services
 
Revisited
RevisitedRevisited
Revisited
 
Основы работы с Memcached
Основы работы с MemcachedОсновы работы с Memcached
Основы работы с Memcached
 
Understanding Web Services
Understanding Web ServicesUnderstanding Web Services
Understanding Web Services
 
11 Ban Net Scaler Xa
11 Ban Net Scaler Xa11 Ban Net Scaler Xa
11 Ban Net Scaler Xa
 
企业级搜索引擎Solr交流
企业级搜索引擎Solr交流企业级搜索引擎Solr交流
企业级搜索引擎Solr交流
 
Перевірка роботи McAfee ENS. MVISION Insights SUNBURST.
Перевірка роботи McAfee ENS. MVISION Insights SUNBURST.Перевірка роботи McAfee ENS. MVISION Insights SUNBURST.
Перевірка роботи McAfee ENS. MVISION Insights SUNBURST.
 

Mehr von Dimara Hakim

Disk-based storage
Disk-based storageDisk-based storage
Disk-based storage
Dimara Hakim
 
Physical elements of data
Physical elements of dataPhysical elements of data
Physical elements of data
Dimara Hakim
 
b - Normalizing a Data Model
b - Normalizing a Data Modelb - Normalizing a Data Model
b - Normalizing a Data Model
Dimara Hakim
 
a - Normalizing a Data Model
a - Normalizing a Data Modela - Normalizing a Data Model
a - Normalizing a Data Model
Dimara Hakim
 
Data Access Technologies
Data Access TechnologiesData Access Technologies
Data Access Technologies
Dimara Hakim
 
Database Management Systems (DBMS)
Database Management Systems (DBMS)Database Management Systems (DBMS)
Database Management Systems (DBMS)
Dimara Hakim
 
Bab 1b The Structure Of A Computer Program
Bab 1b   The Structure Of A Computer ProgramBab 1b   The Structure Of A Computer Program
Bab 1b The Structure Of A Computer Program
Dimara Hakim
 
Bab 2 Rekayasa Perangkat Lunak 5
Bab 2   Rekayasa Perangkat Lunak  5Bab 2   Rekayasa Perangkat Lunak  5
Bab 2 Rekayasa Perangkat Lunak 5
Dimara Hakim
 
Bab 2 Rekayasa Perangkat Lunak 3
Bab 2   Rekayasa Perangkat Lunak  3Bab 2   Rekayasa Perangkat Lunak  3
Bab 2 Rekayasa Perangkat Lunak 3
Dimara Hakim
 
Bab 2 Rekayasa Perangkat Lunak 2
Bab 2   Rekayasa Perangkat Lunak  2Bab 2   Rekayasa Perangkat Lunak  2
Bab 2 Rekayasa Perangkat Lunak 2
Dimara Hakim
 
Bab 2 Rekayasa Perangkat Lunak 1
Bab 2   Rekayasa Perangkat Lunak  1Bab 2   Rekayasa Perangkat Lunak  1
Bab 2 Rekayasa Perangkat Lunak 1
Dimara Hakim
 

Mehr von Dimara Hakim (18)

modul6
modul6modul6
modul6
 
ELS
ELSELS
ELS
 
ASC
ASCASC
ASC
 
Tugas 1
Tugas 1Tugas 1
Tugas 1
 
Disk-based storage
Disk-based storageDisk-based storage
Disk-based storage
 
Index
IndexIndex
Index
 
Physical elements of data
Physical elements of dataPhysical elements of data
Physical elements of data
 
Normalisasi
NormalisasiNormalisasi
Normalisasi
 
b - Normalizing a Data Model
b - Normalizing a Data Modelb - Normalizing a Data Model
b - Normalizing a Data Model
 
a - Normalizing a Data Model
a - Normalizing a Data Modela - Normalizing a Data Model
a - Normalizing a Data Model
 
Data Access Technologies
Data Access TechnologiesData Access Technologies
Data Access Technologies
 
Database Management Systems (DBMS)
Database Management Systems (DBMS)Database Management Systems (DBMS)
Database Management Systems (DBMS)
 
Bab 1b The Structure Of A Computer Program
Bab 1b   The Structure Of A Computer ProgramBab 1b   The Structure Of A Computer Program
Bab 1b The Structure Of A Computer Program
 
OOP
OOPOOP
OOP
 
Bab 2 Rekayasa Perangkat Lunak 5
Bab 2   Rekayasa Perangkat Lunak  5Bab 2   Rekayasa Perangkat Lunak  5
Bab 2 Rekayasa Perangkat Lunak 5
 
Bab 2 Rekayasa Perangkat Lunak 3
Bab 2   Rekayasa Perangkat Lunak  3Bab 2   Rekayasa Perangkat Lunak  3
Bab 2 Rekayasa Perangkat Lunak 3
 
Bab 2 Rekayasa Perangkat Lunak 2
Bab 2   Rekayasa Perangkat Lunak  2Bab 2   Rekayasa Perangkat Lunak  2
Bab 2 Rekayasa Perangkat Lunak 2
 
Bab 2 Rekayasa Perangkat Lunak 1
Bab 2   Rekayasa Perangkat Lunak  1Bab 2   Rekayasa Perangkat Lunak  1
Bab 2 Rekayasa Perangkat Lunak 1
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

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 Название презентации или конференции (заполняется в колонтитулах)