SlideShare a Scribd company logo
1 of 33
Download to read offline
MySQL Tricks
Tips and Tricks from the Phorum Team
Brian Moon, Lead Developer - Phorum
   2008 MySQL Conference & Expo
       http://www.phorum.org/
What is Phorum?
• Open Source message board system
• In use on MySQL.com and Innodb.com
• Developers obsessive about performance
 Come by out booth in the DotOrg Pavilion!
    Just look for the sleepy dog. DOH!
Quick Tips
SQL_COUNT_FOUND_ROWS
Saves the total row count a query matched
NOT including any LIMIT clause. YMMV

Usage:

SELECT SQL_COUNT_FOUND_ROWS
from really_big_table
LIMIT 0, 20

select found_rows()
Extra Layers
Don’t use PHP based abstraction layers
(PEAR::DB, ADOdb, etc.)

Remember this is a talk about speed. Calling
an extra function before the real MySQL
function is called will always be slower.

PDO is a C extension and is not slow.
Never Use Subqueries

• MySQL Subqueries are still a work in
  progress
• The inner query is run once for every row
  in the outer query
• Never say never? There is progress in this
  area. Stay tuned to the MySQL docs.
Be Careful With Joins

• Only join on indexed columns
• Do not use expression in your joins
  inner join t2 on t1.field1+10=t2.field2


• Very often, two queries are faster even with
  the programming overhead to merge them
Buffered vs. Unbuffered
What Are
     Buffered Queries?
• Data returned from the database is held in
  memory for use by other MySQL functions.
• Required for some MySQL functions to
  work. e.g. mysql_num_rows, mysql_seek
• This is the default behavior and most
  commonly used.
What Are
  Unbuffered Queries?
• Data is only sent from the server when it is
  requested.
• Some MySQL functions will not work. e.g.
  mysql_num_rows, mysql_seek
• The results must be fully read and the
  result freed before another query can run.
When To Use
    Unbuffered Queries
Anywhere you have code like this:

while($row = mysql_fetch_assoc($res)){
    $my_array[] = $row;
}

Which for me, is all over the place.

They are especially useful for large datasets.
When NOT To Use
  Unbuffered Queries
• Using mysql_num_rows() and other
  functions that use the buffered results
• Read from multiple result sets at one time
• Complex operations are done while
  reading data into user land
How to use
  Unbuffered Queries
• Older MySQL Extension offers the
  mysql_unbuffered_query function

• For MySQL Improved, pass
  MYSQLI_USE_RESULT to the third
  parameter of mysqli_query.

• For PDO, use PDOStatement::fetchAll()
You Can Pick Your Keys
Forcing your keys

• The MySQL optimizer has rules
• Sometimes, you need to break those rules
• You have to know your data
• You have to test a lot
select
     message_id, subject
from
     phorum_messages
where
     forum_id in (12,14,16,17,18,
     19,20,21,22,23,24,25,26,28,
     57,58,59,61,62,63,64,65,66,67)
     and status=2
     and moved=0
ORDER BY
     message_id DESC
limit 50;

50 rows in set (1.20 sec)
********* 1. row *********
           id: 1
  select_type: SIMPLE
        table: phorum_messages
         type: ref
possible_keys: status_forum,foru.....
          key: status_forum
      key_len: 1
          ref: const
         rows: 33985
        Extra: Using where; Using filesort
select
     message_id, subject
from
     phorum_messages use key (primary)
where
     forum_id in (12,14,16,17,18,
     19,20,21,22,23,24,25,26,28,
     57,58,59,61,62,63,64,65,66,67)
     and status=2
     and moved=0
ORDER BY
     message_id DESC
limit 50;

50 rows in set (0.00 sec)
********* 1. row *********
           id: 1
  select_type: SIMPLE
        table: phorum_messages
         type: index
possible_keys: NULL
          key: PRIMARY
      key_len: 4
          ref: NULL
         rows: 67970
        Extra: Using where
I Know My Data
• The majority of the rows in the table match
  the status in the query.
• Also, the majority of the rows will match
  the large IN clause.
• So, we can scan on a fast key and most of
  the rows will match the other things in the
  where clause.
Test Your Queries

• If EXPLAIN looks wrong, try using FORCE
  INDEX with another key.
• Actually run the query. Sometimes
  EXPLAIN is confusing.
• Test how the query will scale when it is
  being run 100 times per second.
Full-Text > LIKE
Full-Text Search
• Pros
 • It is internal to MySQL
 • It is better than complicated LIKE queries
• Cons
 • Tricky with other indexes
 • Not all hosts enable it
 • Only works with MyISAM
Working With Full-Text
• Understand that MySQL will use only the
  FullText index for a query FullText queries
• Mixing other things into the where clause
  or ordering by ANY fields slows it down
• Returning loads of data to the application
  makes things slow and uses memory
• Phorum uses temporary heap tables to get
  around these issues
Creating The
        Temporary Table
CREATE TEMPORARY TABLE
foo ( KEY (message_id) ) ENGINE=HEAP
SELECT message_id
FROM   phorum_search
WHERE MATCH (search_text)
AGAINST ('+some +search' IN BOOLEAN MODE);
Joining The
        Temporary Table
SELECT SQL_CALC_FOUND_ROWS *
FROM   phorum_messages
INNER JOIN foo USING (message_id)
WHERE status=2
       and forum_id in (12,14,16,17,18,
       19,20,21,22,23,24,25,26,28,
       57,58,59,61,62,63,64,65,66,67)
       and datestamp > 1200390957
ORDER BY datestamp DESC
LIMIT 0, 30;
Adding other searches

• Search by author, subject, etc.
• Create more temporary tables
• Merge them together in yet another table
• Yes, this really is fast (unless the MySQL
  server is badly configured)
Alternatives
• Use old fashioned LIKE clauses (Phorum
  has this for poor users with bad hosts)
• Use an external system
 • Sphinx Search - They are in the DotOrg
    Pavilion as well.
 • Lucene - Java based full text engine.
    There is a Zend class for this as well.
PHP/MySQL Secret
PHP/MySQL Secret
• The current PHP mysql extensions use
  libmysqlclient
• This code is not “part of PHP”
• Therefore, it does not have to follow the
  PHP rules
• Things have to be copied over and over
mysqlnd, A New Hope
• mysqlnd “uses many of the proven and
  stable PHP internal functions”
• That means it respects memory limits
• It also means it can move data from MySQL
  directly into PHP data structures
• Available starting with PHP 5.3
# ./php-with-lib bigselect.php
All OK!


# ./php-with-nd bigselect.php

Fatal error: Allowed memory size of
2097152 bytes exhausted (tried to
allocate 800000 bytes) in /home/brian/
bigselect.php on line 14


       The first script used the memory.
       You just have no control over it!
MySQL Tricks
Tips and Tricks from the Phorum Team
Brian Moon, Lead Developer - Phorum
   2008 MySQL Conference & Expo
       http://www.phorum.org/

More Related Content

What's hot

Magento Meetup Wrocław 6. "Docker for Mac - possible solutions to performance...
Magento Meetup Wrocław 6. "Docker for Mac - possible solutions to performance...Magento Meetup Wrocław 6. "Docker for Mac - possible solutions to performance...
Magento Meetup Wrocław 6. "Docker for Mac - possible solutions to performance...Magento Meetup Wrocław
 
Distributed computing in browsers as client side attack
Distributed computing in browsers as client side attackDistributed computing in browsers as client side attack
Distributed computing in browsers as client side attackIvan Novikov
 
Erlang vs Ruby SOA Scheduling
Erlang vs Ruby SOA SchedulingErlang vs Ruby SOA Scheduling
Erlang vs Ruby SOA Schedulingmarfeyh
 
Rails hosting
Rails hostingRails hosting
Rails hostingwonko
 
Choosing a Web Architecture for Perl
Choosing a Web Architecture for PerlChoosing a Web Architecture for Perl
Choosing a Web Architecture for PerlPerrin Harkins
 
Caching Data For Performance
Caching Data For PerformanceCaching Data For Performance
Caching Data For PerformanceDave Ross
 
Ruby eventmachine pres at rubybdx
Ruby eventmachine pres at rubybdxRuby eventmachine pres at rubybdx
Ruby eventmachine pres at rubybdxMathieu Elie
 
Native Clients, more the merrier with GFProxy!
Native Clients, more the merrier with GFProxy!Native Clients, more the merrier with GFProxy!
Native Clients, more the merrier with GFProxy!Gluster.org
 
Web Performance Part 3 "Server-side tips"
Web Performance Part 3  "Server-side tips"Web Performance Part 3  "Server-side tips"
Web Performance Part 3 "Server-side tips"Binary Studio
 
RabbitMQ + CouchDB = Awesome
RabbitMQ + CouchDB = AwesomeRabbitMQ + CouchDB = Awesome
RabbitMQ + CouchDB = AwesomeLenz Gschwendtner
 
Soirée de lancement Visual Studio - .Net Core 3 et ASP.Net Core 3
Soirée de lancement Visual Studio - .Net Core 3 et ASP.Net Core 3Soirée de lancement Visual Studio - .Net Core 3 et ASP.Net Core 3
Soirée de lancement Visual Studio - .Net Core 3 et ASP.Net Core 3Cellenza
 
Server Side Apocalypse, JS
Server Side Apocalypse, JSServer Side Apocalypse, JS
Server Side Apocalypse, JSMd. Sohel Rana
 
Message Queues & Offline Processing with PHP
Message Queues & Offline Processing with PHPMessage Queues & Offline Processing with PHP
Message Queues & Offline Processing with PHPmarcelesser
 
Umleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appUmleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appLenz Gschwendtner
 
Cache hcm-topdev
Cache hcm-topdevCache hcm-topdev
Cache hcm-topdevThanh Chau
 
EasyEngine - Command-Line tool to manage WordPress Sites on Nginx
EasyEngine - Command-Line tool to manage WordPress Sites on NginxEasyEngine - Command-Line tool to manage WordPress Sites on Nginx
EasyEngine - Command-Line tool to manage WordPress Sites on NginxrtCamp
 

What's hot (20)

Magento Meetup Wrocław 6. "Docker for Mac - possible solutions to performance...
Magento Meetup Wrocław 6. "Docker for Mac - possible solutions to performance...Magento Meetup Wrocław 6. "Docker for Mac - possible solutions to performance...
Magento Meetup Wrocław 6. "Docker for Mac - possible solutions to performance...
 
Distributed computing in browsers as client side attack
Distributed computing in browsers as client side attackDistributed computing in browsers as client side attack
Distributed computing in browsers as client side attack
 
Velocity 2010 - ATS
Velocity 2010 - ATSVelocity 2010 - ATS
Velocity 2010 - ATS
 
WebSockets and Java
WebSockets and JavaWebSockets and Java
WebSockets and Java
 
04 web optimization
04 web optimization04 web optimization
04 web optimization
 
Erlang vs Ruby SOA Scheduling
Erlang vs Ruby SOA SchedulingErlang vs Ruby SOA Scheduling
Erlang vs Ruby SOA Scheduling
 
Rails hosting
Rails hostingRails hosting
Rails hosting
 
Choosing a Web Architecture for Perl
Choosing a Web Architecture for PerlChoosing a Web Architecture for Perl
Choosing a Web Architecture for Perl
 
Caching Data For Performance
Caching Data For PerformanceCaching Data For Performance
Caching Data For Performance
 
Ruby eventmachine pres at rubybdx
Ruby eventmachine pres at rubybdxRuby eventmachine pres at rubybdx
Ruby eventmachine pres at rubybdx
 
Native Clients, more the merrier with GFProxy!
Native Clients, more the merrier with GFProxy!Native Clients, more the merrier with GFProxy!
Native Clients, more the merrier with GFProxy!
 
Web Performance Part 3 "Server-side tips"
Web Performance Part 3  "Server-side tips"Web Performance Part 3  "Server-side tips"
Web Performance Part 3 "Server-side tips"
 
re7jweiss
re7jweissre7jweiss
re7jweiss
 
RabbitMQ + CouchDB = Awesome
RabbitMQ + CouchDB = AwesomeRabbitMQ + CouchDB = Awesome
RabbitMQ + CouchDB = Awesome
 
Soirée de lancement Visual Studio - .Net Core 3 et ASP.Net Core 3
Soirée de lancement Visual Studio - .Net Core 3 et ASP.Net Core 3Soirée de lancement Visual Studio - .Net Core 3 et ASP.Net Core 3
Soirée de lancement Visual Studio - .Net Core 3 et ASP.Net Core 3
 
Server Side Apocalypse, JS
Server Side Apocalypse, JSServer Side Apocalypse, JS
Server Side Apocalypse, JS
 
Message Queues & Offline Processing with PHP
Message Queues & Offline Processing with PHPMessage Queues & Offline Processing with PHP
Message Queues & Offline Processing with PHP
 
Umleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appUmleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB app
 
Cache hcm-topdev
Cache hcm-topdevCache hcm-topdev
Cache hcm-topdev
 
EasyEngine - Command-Line tool to manage WordPress Sites on Nginx
EasyEngine - Command-Line tool to manage WordPress Sites on NginxEasyEngine - Command-Line tool to manage WordPress Sites on Nginx
EasyEngine - Command-Line tool to manage WordPress Sites on Nginx
 

Viewers also liked

PresentacióN1
PresentacióN1PresentacióN1
PresentacióN1sandracpa
 
Lifelong Learning and Museums
Lifelong Learning and MuseumsLifelong Learning and Museums
Lifelong Learning and MuseumsLynda Kelly
 
OWASP PHPIDS talk slides
OWASP PHPIDS talk slidesOWASP PHPIDS talk slides
OWASP PHPIDS talk slidesguestd34230
 
CONVIVENCIA
CONVIVENCIACONVIVENCIA
CONVIVENCIAguisse21
 

Viewers also liked (6)

Security @ work
Security @ workSecurity @ work
Security @ work
 
Palabras
PalabrasPalabras
Palabras
 
PresentacióN1
PresentacióN1PresentacióN1
PresentacióN1
 
Lifelong Learning and Museums
Lifelong Learning and MuseumsLifelong Learning and Museums
Lifelong Learning and Museums
 
OWASP PHPIDS talk slides
OWASP PHPIDS talk slidesOWASP PHPIDS talk slides
OWASP PHPIDS talk slides
 
CONVIVENCIA
CONVIVENCIACONVIVENCIA
CONVIVENCIA
 

Similar to Phorum MySQL tricks

Оптимизация MySQL. Что должен знать каждый разработчик
Оптимизация MySQL. Что должен знать каждый разработчикОптимизация MySQL. Что должен знать каждый разработчик
Оптимизация MySQL. Что должен знать каждый разработчикAgnislav Onufrijchuk
 
My Database Skills Killed the Server
My Database Skills Killed the ServerMy Database Skills Killed the Server
My Database Skills Killed the ServerColdFusionConference
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the ServerdevObjective
 
MySQL Scaling Presentation
MySQL Scaling PresentationMySQL Scaling Presentation
MySQL Scaling PresentationTommy Falgout
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersJonathan Levin
 
Incredible ODI tips to work with Hyperion tools that you ever wanted to know
Incredible ODI tips to work with Hyperion tools that you ever wanted to knowIncredible ODI tips to work with Hyperion tools that you ever wanted to know
Incredible ODI tips to work with Hyperion tools that you ever wanted to knowRodrigo Radtke de Souza
 
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
 
Presto Meetup 2016 Small Start
Presto Meetup 2016 Small StartPresto Meetup 2016 Small Start
Presto Meetup 2016 Small StartHiroshi Toyama
 
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)Aurimas Mikalauskas
 
MongoDB performance
MongoDB performanceMongoDB performance
MongoDB performanceMydbops
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Developmentw3ondemand
 
Jdbcconnectivitytojava 190804164056
Jdbcconnectivitytojava 190804164056Jdbcconnectivitytojava 190804164056
Jdbcconnectivitytojava 190804164056SowmyaM45
 
MySQL 101 PHPTek 2017
MySQL 101 PHPTek 2017MySQL 101 PHPTek 2017
MySQL 101 PHPTek 2017Dave Stokes
 
Five Database Mistakes and how to fix them -- Confoo Vancouver
Five Database Mistakes and how to fix them -- Confoo VancouverFive Database Mistakes and how to fix them -- Confoo Vancouver
Five Database Mistakes and how to fix them -- Confoo VancouverDave Stokes
 

Similar to Phorum MySQL tricks (20)

Оптимизация MySQL. Что должен знать каждый разработчик
Оптимизация MySQL. Что должен знать каждый разработчикОптимизация MySQL. Что должен знать каждый разработчик
Оптимизация MySQL. Что должен знать каждый разработчик
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Golden Hammer - Shawn Oden
Golden Hammer - Shawn OdenGolden Hammer - Shawn Oden
Golden Hammer - Shawn Oden
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
 
My Database Skills Killed the Server
My Database Skills Killed the ServerMy Database Skills Killed the Server
My Database Skills Killed the Server
 
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 Scaling Presentation
MySQL Scaling PresentationMySQL Scaling Presentation
MySQL Scaling Presentation
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 
Incredible ODI tips to work with Hyperion tools that you ever wanted to know
Incredible ODI tips to work with Hyperion tools that you ever wanted to knowIncredible ODI tips to work with Hyperion tools that you ever wanted to know
Incredible ODI tips to work with Hyperion tools that you ever wanted to know
 
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
 
Presto Meetup 2016 Small Start
Presto Meetup 2016 Small StartPresto Meetup 2016 Small Start
Presto Meetup 2016 Small Start
 
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
 
MongoDB performance
MongoDB performanceMongoDB performance
MongoDB performance
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Development
 
Jdbcconnectivitytojava 190804164056
Jdbcconnectivitytojava 190804164056Jdbcconnectivitytojava 190804164056
Jdbcconnectivitytojava 190804164056
 
Jdbc connectivity to java
Jdbc connectivity to javaJdbc connectivity to java
Jdbc connectivity to java
 
MySQL 101 PHPTek 2017
MySQL 101 PHPTek 2017MySQL 101 PHPTek 2017
MySQL 101 PHPTek 2017
 
Five Database Mistakes and how to fix them -- Confoo Vancouver
Five Database Mistakes and how to fix them -- Confoo VancouverFive Database Mistakes and how to fix them -- Confoo Vancouver
Five Database Mistakes and how to fix them -- Confoo Vancouver
 

Recently uploaded

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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...apidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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 CVKhem
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
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...Neo4j
 
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 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
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...Drew Madelung
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
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...
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
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...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Phorum MySQL tricks

  • 1. MySQL Tricks Tips and Tricks from the Phorum Team Brian Moon, Lead Developer - Phorum 2008 MySQL Conference & Expo http://www.phorum.org/
  • 2. What is Phorum? • Open Source message board system • In use on MySQL.com and Innodb.com • Developers obsessive about performance Come by out booth in the DotOrg Pavilion! Just look for the sleepy dog. DOH!
  • 4. SQL_COUNT_FOUND_ROWS Saves the total row count a query matched NOT including any LIMIT clause. YMMV Usage: SELECT SQL_COUNT_FOUND_ROWS from really_big_table LIMIT 0, 20 select found_rows()
  • 5. Extra Layers Don’t use PHP based abstraction layers (PEAR::DB, ADOdb, etc.) Remember this is a talk about speed. Calling an extra function before the real MySQL function is called will always be slower. PDO is a C extension and is not slow.
  • 6. Never Use Subqueries • MySQL Subqueries are still a work in progress • The inner query is run once for every row in the outer query • Never say never? There is progress in this area. Stay tuned to the MySQL docs.
  • 7. Be Careful With Joins • Only join on indexed columns • Do not use expression in your joins inner join t2 on t1.field1+10=t2.field2 • Very often, two queries are faster even with the programming overhead to merge them
  • 9. What Are Buffered Queries? • Data returned from the database is held in memory for use by other MySQL functions. • Required for some MySQL functions to work. e.g. mysql_num_rows, mysql_seek • This is the default behavior and most commonly used.
  • 10. What Are Unbuffered Queries? • Data is only sent from the server when it is requested. • Some MySQL functions will not work. e.g. mysql_num_rows, mysql_seek • The results must be fully read and the result freed before another query can run.
  • 11. When To Use Unbuffered Queries Anywhere you have code like this: while($row = mysql_fetch_assoc($res)){ $my_array[] = $row; } Which for me, is all over the place. They are especially useful for large datasets.
  • 12. When NOT To Use Unbuffered Queries • Using mysql_num_rows() and other functions that use the buffered results • Read from multiple result sets at one time • Complex operations are done while reading data into user land
  • 13. How to use Unbuffered Queries • Older MySQL Extension offers the mysql_unbuffered_query function • For MySQL Improved, pass MYSQLI_USE_RESULT to the third parameter of mysqli_query. • For PDO, use PDOStatement::fetchAll()
  • 14. You Can Pick Your Keys
  • 15. Forcing your keys • The MySQL optimizer has rules • Sometimes, you need to break those rules • You have to know your data • You have to test a lot
  • 16. select message_id, subject from phorum_messages where forum_id in (12,14,16,17,18, 19,20,21,22,23,24,25,26,28, 57,58,59,61,62,63,64,65,66,67) and status=2 and moved=0 ORDER BY message_id DESC limit 50; 50 rows in set (1.20 sec)
  • 17. ********* 1. row ********* id: 1 select_type: SIMPLE table: phorum_messages type: ref possible_keys: status_forum,foru..... key: status_forum key_len: 1 ref: const rows: 33985 Extra: Using where; Using filesort
  • 18. select message_id, subject from phorum_messages use key (primary) where forum_id in (12,14,16,17,18, 19,20,21,22,23,24,25,26,28, 57,58,59,61,62,63,64,65,66,67) and status=2 and moved=0 ORDER BY message_id DESC limit 50; 50 rows in set (0.00 sec)
  • 19. ********* 1. row ********* id: 1 select_type: SIMPLE table: phorum_messages type: index possible_keys: NULL key: PRIMARY key_len: 4 ref: NULL rows: 67970 Extra: Using where
  • 20. I Know My Data • The majority of the rows in the table match the status in the query. • Also, the majority of the rows will match the large IN clause. • So, we can scan on a fast key and most of the rows will match the other things in the where clause.
  • 21. Test Your Queries • If EXPLAIN looks wrong, try using FORCE INDEX with another key. • Actually run the query. Sometimes EXPLAIN is confusing. • Test how the query will scale when it is being run 100 times per second.
  • 23. Full-Text Search • Pros • It is internal to MySQL • It is better than complicated LIKE queries • Cons • Tricky with other indexes • Not all hosts enable it • Only works with MyISAM
  • 24. Working With Full-Text • Understand that MySQL will use only the FullText index for a query FullText queries • Mixing other things into the where clause or ordering by ANY fields slows it down • Returning loads of data to the application makes things slow and uses memory • Phorum uses temporary heap tables to get around these issues
  • 25. Creating The Temporary Table CREATE TEMPORARY TABLE foo ( KEY (message_id) ) ENGINE=HEAP SELECT message_id FROM phorum_search WHERE MATCH (search_text) AGAINST ('+some +search' IN BOOLEAN MODE);
  • 26. Joining The Temporary Table SELECT SQL_CALC_FOUND_ROWS * FROM phorum_messages INNER JOIN foo USING (message_id) WHERE status=2 and forum_id in (12,14,16,17,18, 19,20,21,22,23,24,25,26,28, 57,58,59,61,62,63,64,65,66,67) and datestamp > 1200390957 ORDER BY datestamp DESC LIMIT 0, 30;
  • 27. Adding other searches • Search by author, subject, etc. • Create more temporary tables • Merge them together in yet another table • Yes, this really is fast (unless the MySQL server is badly configured)
  • 28. Alternatives • Use old fashioned LIKE clauses (Phorum has this for poor users with bad hosts) • Use an external system • Sphinx Search - They are in the DotOrg Pavilion as well. • Lucene - Java based full text engine. There is a Zend class for this as well.
  • 30. PHP/MySQL Secret • The current PHP mysql extensions use libmysqlclient • This code is not “part of PHP” • Therefore, it does not have to follow the PHP rules • Things have to be copied over and over
  • 31. mysqlnd, A New Hope • mysqlnd “uses many of the proven and stable PHP internal functions” • That means it respects memory limits • It also means it can move data from MySQL directly into PHP data structures • Available starting with PHP 5.3
  • 32. # ./php-with-lib bigselect.php All OK! # ./php-with-nd bigselect.php Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 800000 bytes) in /home/brian/ bigselect.php on line 14 The first script used the memory. You just have no control over it!
  • 33. MySQL Tricks Tips and Tricks from the Phorum Team Brian Moon, Lead Developer - Phorum 2008 MySQL Conference & Expo http://www.phorum.org/