SlideShare a Scribd company logo
1 of 50
Download to read offline
How can MySQL boost
Your applications?
How can MySQL boost
Your applications?
Mmh, wait...
How can MySQL boost
(or kill)
Your applications?
€ whoami
● Federico Razzoli
● Freelance consultant
● Writing SQL since MySQL 2.23
https://federico-razzoli.com
hello@federico-razzoli.com
● I love open source, sharing,
Collaboration, win-win, etc
● I love MariaDB, MySQL, Postgres, etc
This talk applies to...
● MySQL
● Percona Server
● MariaDB
And most information applies, with some changes, to:
● All other relational DBMSs
This talk is about...
● Low hanging fruits to speed up your apps
● Hints you may want to investigate in the next days
This talk is not about...
● ORMs
● PHP code
● Query optimisation
● SQL_MODE
● Graphical interfaces
● MySQL characteristics that I don’t want to advertise
○ For a reason
○ But you are allowed to ask questions that I hope you
don’t ask
○ I will still say “thank you for your question”
Why do I want to
talk about MySQL
at a PHP event?
Good practices™
for your dev machine
Configuration
/etc/mysql/my.cnf should always contain:
log_slow = 1
long_query_time = 0
performance_schema = 1
Userstat = 1 -- MariaDB and Percona Server
Slow log
ls -1 $( mysql -e 'SELECT @@datadir' ) | grep slow
● Empty the slow log before a test
○ echo '' > /path/to/slowlog
● Check the slow log when you want to check your queries
○ Includes query duration, rows returned and some details on the execution
plan
Performance Schema
Before a test:
TRUNCATE TABLE
performance_schema.events_statements_summary_by_digest;
Queries that fail
SELECT
DIGEST_TEXT,
COUNT_STAR
FROM performance_schema.events_statements_summary_by_digest
WHERE
DIGEST_TEXT IS NOT NULL
AND SUM_ERRORS > 0 -- SUM_WARNINGS
ORDER BY COUNT_STAR DESC
LIMIT 10
G
Queries with no results
SELECT *
FROM performance_schema.events_statements_summary_by_digest
WHERE
(
TRIM(DIGEST_TEXT) LIKE 'SELECT%'
OR TRIM(DIGEST_TEXT) LIKE 'CREATE%TABLE%SELECT%'
OR TRIM(DIGEST_TEXT) LIKE 'DELETE%'
OR TRIM(DIGEST_TEXT) LIKE 'UPDATE%'
OR TRIM(DIGEST_TEXT) LIKE 'REPLACE%'
)
AND SUM_ROWS_SENT = 0
AND SUM_ROWS_AFFECTED = 0
ORDER BY SUM_ROWS_EXAMINED DESC
LIMIT 10
G
Non-optimised queries
SELECT
DIGEST_TEXT,
COUNT_STAR
FROM performance_schema.events_statements_summary_by_digest
WHERE
DIGEST_TEXT IS NOT NULL AND (
SUM_NO_INDEX_USED > 0 OR
SUM_CREATED_TMP_DISK_TABLES > 0
)
ORDER BY SUM_ROWS_EXAMINED DESC
LIMIT 10
G
More info
For more discussion on these queries, ask google:
Federico Razzoli "MySQL/MariaDB: run less queries!"
Indexes
An index is an ordered data structure
● Think to a phone book
● It is a table with an index on (last_name, first_name)
● First takeaway: the order of columns matters
● Your mind contains a pretty good SQL optimiser
● When you want to know which queries can be optimised with a certain index,
think to a phone book
Which queries can be optimised?
● WHERE last_name = 'Baker'
● WHERE first_name = 'Tom'
● WHERE first_name = 'Tom' AND last_name = 'Baker'
● WHERE last_name = 'Baker' AND first_name = 'Tom'
Rule #1:
A query can use a whole index
Or a leftmost part of an index
Which queries can be optimised?
● WHERE last_name = 'Baker'
● WHERE last_name <> 'Baker'
● WHERE last_name > 'Baker'
● WHERE last_name >= 'Baker'
● WHERE last_name < 'Baker'
● WHERE last_name =< 'Baker'
Which queries can be optimised?
● WHERE last_name > 'B' AND last_name < 'C'
● WHERE last_name BETWEEN 'B' AND 'BZZZZZZZZZZZ';
● WHERE last_name LIKE 'B%'
● WHERE last_name LIKE '%ake%'
● WHERE last_name LIKE '%r'
Rule #2:
You can use an index to find a value
Or a (closed/open) range
Which queries can be optimised?
● WHERE last_name = 'Nimoy' OR first_name = 'Leonard'
● WHERE last_name = 'Nimoy' OR last_name = 'Shatner'
Rule #3:
OR on different columns
Is not fully optimised
Which queries can be optimised?
● WHERE last_name = 'Nimoy' AND first_name = 'Leonard'
● WHERE last_name = 'Nimoy' AND first_name > 'Leonard'
● WHERE last_name > 'Nimoy' AND first_name = 'Leonard'
● WHERE last_name > 'Nimoy' AND first_name > 'Leonard'
Rule #4:
The index use
Stops at the first range
Use proper SQL
N + 1 problem
Don’t:
foreach row in ( SELECT * FROM author WHERE a.LIKE 'P%'; )
SELECT * FROM book WHERE author_id = ?;
Do:
SELECT a.first_name, a.last_name, b.*
FROM book b
JOIN author a
ON b.id = a.book_id
WHERE a.last_name = 'P%';
Count in SQL, not in PHP
Don’t:
foreach row in ( SELECT * FROM customer; )
$customer++;
Do:
SELECT count(*) FROM customer;
Dealing with duplicates
INSERT INTO product (id, ...) VALUES (24, ...);
INSERT IGNORE INTO product (id, ...) VALUES (24, ...);
INSERT INTO product (id, ...)
ON DUPLICATE KEY UPDATE name = 'Sonic screwdriver';
REPLACE INTO product (id, ...) VALUES (24, ...);
DELETE IGNORE ...
UPDATE IGNORE ...
Insert many rows
INSERT INTO user
(first_name, last_name, email)
VALUES
('William', 'Hartnell', 'first@bbc.co.uk'),
('Tom', 'Baker', 'tom@gmail.com'),
('Jody', 'Wittaker', 'first_lady@hotmail.com');
Insert into related tables
INSERT INTO `author` (name, surname) VALUES
('Arthur', 'Clarke');
INSERT INTO `book` (author_id, title) VALUES
(LAST_INSERT_ID(), '2001: A Space Odyssey');
Delete/Update many tables
DELETE `order`, user
FROM `order`
INNER JOIN `order`
ON order.user_id = user.id
WHERE user = 24;
UPDATE `order`, user
FROM `order`
INNER JOIN `order`
ON order.user_id = user.id
SET status = 'CANCELLED'
WHERE user = 24;
Read+Delete data
Only MariaDB:
DELETE FROM user
WHERE id = 2424
RETURNING first_name, last_name;
Creating table with rows
CREATE TABLE past_order LIKE `order`;
INSERT INTO past_order
SELECT * FROM `order`
WHERE status IN ('SHIPPED', 'CANCELLED');
Or:
CREATE TABLE customer
SELECT u.id, u.first_name, u.last_name
FROM user u JOIN `order` o
ON u.id = o.user_id
WHERE o.status <> 'CANCELED';
More info
For more info on this topic, ask Google:
Federico Razzoli "use sql properly to run less queries"
MySQL and Transactions
What are transactions?
ACID
● Atomicity
○ All writes in a transaction fail or succeed altogether.
● Consistency
○ Data always switch from one consistent point to another.
● Isolation
○ Transactions are logically sequential.
● Durability
○ Data changes persist after system failures (crashes).
Transactions syntax
START TRANSACTION;
SELECT … ;
UPDATE … ;
INSERT … ;
COMMIT;
START TRANSACTION;
DELETE … ;
INSERT … ;
ROLLBACK;
SET SESSION autocommit := 1; -- this is the default
DELETE … ;
Isolation levels
● READ UNCOMMITTED
○ You could see not-yet-committed changes.
● READ COMMITTED
○ Each query acquires a separate snapshot.
● REPEATABLE READ (default)
○ One snapshot for the whole transaction.
● SERIALIZABLE
○ Like REPEATABLE READ, but SELECTs are implicitly IN SHARE MODE
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
START TRANSACTION;
...
Use cases for READ UNCOMMITTED?
Use cases for READ UNCOMMITTED?
● Statistics (avg on 1M rows)
● “Hi Boris, your last access was on 12th December”
● Delete old data
Use cases for READ COMMITTED?
Use cases for READ COMMITTED?
● Delete/update rows by id from multiple tables
● Show user’s payment history
READ ONLY transactions
● Make sense with REPEATABLE READ
● 2 SELECTs will see consistent data
● Attempts to change data will return an error
● Performance optimisation
○ But not as much as READ UNCOMMITTED
START TRANSACTION READ ONLY;
Ways to kill MySQL
Having SELECT privilege is enough to kill MySQL!
(or any RDBMS)
Method 1:
START TRANSACTION;
SELECT * FROM `order`;
SELECT SLEEP(3600 * 12);
Ways to kill MySQL
Having SELECT privilege is enough to kill MySQL!
(or any RDBMS)
Method 2:
START TRANSACTION;
SELECT * FROM `order` WHERE id = 24 FOR UPDATE;
SELECT SLEEP(3600 * 12);
More info on transactions cost
For more info on how transactions work under the hood
and why they can be expensive, ask Google for:
Jeremy Cole "The basics of the InnoDB undo logging
and history system"
Thanks for being still awake!

More Related Content

Similar to How MySQL can boost (or kill) your application v2

MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)Federico Razzoli
 
M|18 Why Abstract Away the Underlying Database Infrastructure
M|18 Why Abstract Away the Underlying Database InfrastructureM|18 Why Abstract Away the Underlying Database Infrastructure
M|18 Why Abstract Away the Underlying Database InfrastructureMariaDB plc
 
Ledingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @LendingkartLedingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @LendingkartMukesh Singh
 
Advanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfAdvanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfFederico Razzoli
 
Evolution of DBA in the Cloud Era
 Evolution of DBA in the Cloud Era Evolution of DBA in the Cloud Era
Evolution of DBA in the Cloud EraMydbops
 
Performance schema in_my_sql_5.6_pluk2013
Performance schema in_my_sql_5.6_pluk2013Performance schema in_my_sql_5.6_pluk2013
Performance schema in_my_sql_5.6_pluk2013Valeriy Kravchuk
 
The Peoper Care and Feeding of a MySQL Server for Busy Linux Admin
The Peoper Care and Feeding of a MySQL Server for Busy Linux AdminThe Peoper Care and Feeding of a MySQL Server for Busy Linux Admin
The Peoper Care and Feeding of a MySQL Server for Busy Linux AdminDave Stokes
 
Validating big data jobs - Spark AI Summit EU
Validating big data jobs  - Spark AI Summit EUValidating big data jobs  - Spark AI Summit EU
Validating big data jobs - Spark AI Summit EUHolden Karau
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersJonathan Levin
 
Top Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowTop Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowKathy Brown
 
Tales from the Field
Tales from the FieldTales from the Field
Tales from the FieldMongoDB
 
Denver MuleSoft Meetup: Cool Features in DataWeave 2.3 and 2.4
Denver MuleSoft Meetup: Cool Features in DataWeave 2.3 and 2.4Denver MuleSoft Meetup: Cool Features in DataWeave 2.3 and 2.4
Denver MuleSoft Meetup: Cool Features in DataWeave 2.3 and 2.4Big Compass
 
My Query is slow, now what?
My Query is slow, now what?My Query is slow, now what?
My Query is slow, now what?Gianluca Sartori
 
15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performanceguest9912e5
 
Anatomy of Data Frame API : A deep dive into Spark Data Frame API
Anatomy of Data Frame API :  A deep dive into Spark Data Frame APIAnatomy of Data Frame API :  A deep dive into Spark Data Frame API
Anatomy of Data Frame API : A deep dive into Spark Data Frame APIdatamantra
 
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
 Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark... Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...Databricks
 
How to build TiDB
How to build TiDBHow to build TiDB
How to build TiDBPingCAP
 

Similar to How MySQL can boost (or kill) your application v2 (20)

MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)
 
MySQL performance tuning
MySQL performance tuningMySQL performance tuning
MySQL performance tuning
 
M|18 Why Abstract Away the Underlying Database Infrastructure
M|18 Why Abstract Away the Underlying Database InfrastructureM|18 Why Abstract Away the Underlying Database Infrastructure
M|18 Why Abstract Away the Underlying Database Infrastructure
 
Ledingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @LendingkartLedingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @Lendingkart
 
Advanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfAdvanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdf
 
Evolution of DBA in the Cloud Era
 Evolution of DBA in the Cloud Era Evolution of DBA in the Cloud Era
Evolution of DBA in the Cloud Era
 
Performance schema in_my_sql_5.6_pluk2013
Performance schema in_my_sql_5.6_pluk2013Performance schema in_my_sql_5.6_pluk2013
Performance schema in_my_sql_5.6_pluk2013
 
The Peoper Care and Feeding of a MySQL Server for Busy Linux Admin
The Peoper Care and Feeding of a MySQL Server for Busy Linux AdminThe Peoper Care and Feeding of a MySQL Server for Busy Linux Admin
The Peoper Care and Feeding of a MySQL Server for Busy Linux Admin
 
Validating big data jobs - Spark AI Summit EU
Validating big data jobs  - Spark AI Summit EUValidating big data jobs  - Spark AI Summit EU
Validating big data jobs - Spark AI Summit EU
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 
Top Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowTop Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To Know
 
Tales from the Field
Tales from the FieldTales from the Field
Tales from the Field
 
Really Big Elephants: PostgreSQL DW
Really Big Elephants: PostgreSQL DWReally Big Elephants: PostgreSQL DW
Really Big Elephants: PostgreSQL DW
 
Denver MuleSoft Meetup: Cool Features in DataWeave 2.3 and 2.4
Denver MuleSoft Meetup: Cool Features in DataWeave 2.3 and 2.4Denver MuleSoft Meetup: Cool Features in DataWeave 2.3 and 2.4
Denver MuleSoft Meetup: Cool Features in DataWeave 2.3 and 2.4
 
My Query is slow, now what?
My Query is slow, now what?My Query is slow, now what?
My Query is slow, now what?
 
15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance
 
Anatomy of Data Frame API : A deep dive into Spark Data Frame API
Anatomy of Data Frame API :  A deep dive into Spark Data Frame APIAnatomy of Data Frame API :  A deep dive into Spark Data Frame API
Anatomy of Data Frame API : A deep dive into Spark Data Frame API
 
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
 Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark... Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
 
How to build TiDB
How to build TiDBHow to build TiDB
How to build TiDB
 
Rails data migrations
Rails data migrationsRails data migrations
Rails data migrations
 

More from Federico Razzoli

Webinar - Unleash AI power with MySQL and MindsDB
Webinar - Unleash AI power with MySQL and MindsDBWebinar - Unleash AI power with MySQL and MindsDB
Webinar - Unleash AI power with MySQL and MindsDBFederico Razzoli
 
MariaDB Security Best Practices
MariaDB Security Best PracticesMariaDB Security Best Practices
MariaDB Security Best PracticesFederico Razzoli
 
A first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use themFederico Razzoli
 
MariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improvedFederico Razzoli
 
Webinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstrationWebinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstrationFederico Razzoli
 
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11Federico Razzoli
 
MariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsMariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsFederico Razzoli
 
Recent MariaDB features to learn for a happy life
Recent MariaDB features to learn for a happy lifeRecent MariaDB features to learn for a happy life
Recent MariaDB features to learn for a happy lifeFederico Razzoli
 
Automate MariaDB Galera clusters deployments with Ansible
Automate MariaDB Galera clusters deployments with AnsibleAutomate MariaDB Galera clusters deployments with Ansible
Automate MariaDB Galera clusters deployments with AnsibleFederico Razzoli
 
Creating Vagrant development machines with MariaDB
Creating Vagrant development machines with MariaDBCreating Vagrant development machines with MariaDB
Creating Vagrant development machines with MariaDBFederico Razzoli
 
MariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructuresMariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructuresFederico Razzoli
 
Playing with the CONNECT storage engine
Playing with the CONNECT storage enginePlaying with the CONNECT storage engine
Playing with the CONNECT storage engineFederico Razzoli
 
JSON in MySQL and MariaDB Databases
JSON in MySQL and MariaDB DatabasesJSON in MySQL and MariaDB Databases
JSON in MySQL and MariaDB DatabasesFederico Razzoli
 
Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)Federico Razzoli
 

More from Federico Razzoli (17)

Webinar - Unleash AI power with MySQL and MindsDB
Webinar - Unleash AI power with MySQL and MindsDBWebinar - Unleash AI power with MySQL and MindsDB
Webinar - Unleash AI power with MySQL and MindsDB
 
MariaDB Security Best Practices
MariaDB Security Best PracticesMariaDB Security Best Practices
MariaDB Security Best Practices
 
A first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use them
 
MariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improved
 
Webinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstrationWebinar - MariaDB Temporal Tables: a demonstration
Webinar - MariaDB Temporal Tables: a demonstration
 
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
 
MariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsMariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAs
 
Recent MariaDB features to learn for a happy life
Recent MariaDB features to learn for a happy lifeRecent MariaDB features to learn for a happy life
Recent MariaDB features to learn for a happy life
 
Automate MariaDB Galera clusters deployments with Ansible
Automate MariaDB Galera clusters deployments with AnsibleAutomate MariaDB Galera clusters deployments with Ansible
Automate MariaDB Galera clusters deployments with Ansible
 
Creating Vagrant development machines with MariaDB
Creating Vagrant development machines with MariaDBCreating Vagrant development machines with MariaDB
Creating Vagrant development machines with MariaDB
 
MariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructuresMariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructures
 
Playing with the CONNECT storage engine
Playing with the CONNECT storage enginePlaying with the CONNECT storage engine
Playing with the CONNECT storage engine
 
MariaDB Temporal Tables
MariaDB Temporal TablesMariaDB Temporal Tables
MariaDB Temporal Tables
 
MySQL and MariaDB Backups
MySQL and MariaDB BackupsMySQL and MariaDB Backups
MySQL and MariaDB Backups
 
JSON in MySQL and MariaDB Databases
JSON in MySQL and MariaDB DatabasesJSON in MySQL and MariaDB Databases
JSON in MySQL and MariaDB Databases
 
Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)
 
MariaDB Temporal Tables
MariaDB Temporal TablesMariaDB Temporal Tables
MariaDB Temporal Tables
 

Recently uploaded

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 

Recently uploaded (20)

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 

How MySQL can boost (or kill) your application v2

  • 1. How can MySQL boost Your applications?
  • 2. How can MySQL boost Your applications? Mmh, wait...
  • 3. How can MySQL boost (or kill) Your applications?
  • 4. € whoami ● Federico Razzoli ● Freelance consultant ● Writing SQL since MySQL 2.23 https://federico-razzoli.com hello@federico-razzoli.com ● I love open source, sharing, Collaboration, win-win, etc ● I love MariaDB, MySQL, Postgres, etc
  • 5. This talk applies to... ● MySQL ● Percona Server ● MariaDB And most information applies, with some changes, to: ● All other relational DBMSs
  • 6. This talk is about... ● Low hanging fruits to speed up your apps ● Hints you may want to investigate in the next days
  • 7. This talk is not about... ● ORMs ● PHP code ● Query optimisation ● SQL_MODE ● Graphical interfaces ● MySQL characteristics that I don’t want to advertise ○ For a reason ○ But you are allowed to ask questions that I hope you don’t ask ○ I will still say “thank you for your question”
  • 8. Why do I want to talk about MySQL at a PHP event?
  • 10. Configuration /etc/mysql/my.cnf should always contain: log_slow = 1 long_query_time = 0 performance_schema = 1 Userstat = 1 -- MariaDB and Percona Server
  • 11. Slow log ls -1 $( mysql -e 'SELECT @@datadir' ) | grep slow ● Empty the slow log before a test ○ echo '' > /path/to/slowlog ● Check the slow log when you want to check your queries ○ Includes query duration, rows returned and some details on the execution plan
  • 12. Performance Schema Before a test: TRUNCATE TABLE performance_schema.events_statements_summary_by_digest;
  • 13. Queries that fail SELECT DIGEST_TEXT, COUNT_STAR FROM performance_schema.events_statements_summary_by_digest WHERE DIGEST_TEXT IS NOT NULL AND SUM_ERRORS > 0 -- SUM_WARNINGS ORDER BY COUNT_STAR DESC LIMIT 10 G
  • 14. Queries with no results SELECT * FROM performance_schema.events_statements_summary_by_digest WHERE ( TRIM(DIGEST_TEXT) LIKE 'SELECT%' OR TRIM(DIGEST_TEXT) LIKE 'CREATE%TABLE%SELECT%' OR TRIM(DIGEST_TEXT) LIKE 'DELETE%' OR TRIM(DIGEST_TEXT) LIKE 'UPDATE%' OR TRIM(DIGEST_TEXT) LIKE 'REPLACE%' ) AND SUM_ROWS_SENT = 0 AND SUM_ROWS_AFFECTED = 0 ORDER BY SUM_ROWS_EXAMINED DESC LIMIT 10 G
  • 15. Non-optimised queries SELECT DIGEST_TEXT, COUNT_STAR FROM performance_schema.events_statements_summary_by_digest WHERE DIGEST_TEXT IS NOT NULL AND ( SUM_NO_INDEX_USED > 0 OR SUM_CREATED_TMP_DISK_TABLES > 0 ) ORDER BY SUM_ROWS_EXAMINED DESC LIMIT 10 G
  • 16. More info For more discussion on these queries, ask google: Federico Razzoli "MySQL/MariaDB: run less queries!"
  • 18. An index is an ordered data structure ● Think to a phone book ● It is a table with an index on (last_name, first_name) ● First takeaway: the order of columns matters ● Your mind contains a pretty good SQL optimiser ● When you want to know which queries can be optimised with a certain index, think to a phone book
  • 19. Which queries can be optimised? ● WHERE last_name = 'Baker' ● WHERE first_name = 'Tom' ● WHERE first_name = 'Tom' AND last_name = 'Baker' ● WHERE last_name = 'Baker' AND first_name = 'Tom'
  • 20. Rule #1: A query can use a whole index Or a leftmost part of an index
  • 21. Which queries can be optimised? ● WHERE last_name = 'Baker' ● WHERE last_name <> 'Baker' ● WHERE last_name > 'Baker' ● WHERE last_name >= 'Baker' ● WHERE last_name < 'Baker' ● WHERE last_name =< 'Baker'
  • 22. Which queries can be optimised? ● WHERE last_name > 'B' AND last_name < 'C' ● WHERE last_name BETWEEN 'B' AND 'BZZZZZZZZZZZ'; ● WHERE last_name LIKE 'B%' ● WHERE last_name LIKE '%ake%' ● WHERE last_name LIKE '%r'
  • 23. Rule #2: You can use an index to find a value Or a (closed/open) range
  • 24. Which queries can be optimised? ● WHERE last_name = 'Nimoy' OR first_name = 'Leonard' ● WHERE last_name = 'Nimoy' OR last_name = 'Shatner'
  • 25. Rule #3: OR on different columns Is not fully optimised
  • 26. Which queries can be optimised? ● WHERE last_name = 'Nimoy' AND first_name = 'Leonard' ● WHERE last_name = 'Nimoy' AND first_name > 'Leonard' ● WHERE last_name > 'Nimoy' AND first_name = 'Leonard' ● WHERE last_name > 'Nimoy' AND first_name > 'Leonard'
  • 27. Rule #4: The index use Stops at the first range
  • 29. N + 1 problem Don’t: foreach row in ( SELECT * FROM author WHERE a.LIKE 'P%'; ) SELECT * FROM book WHERE author_id = ?; Do: SELECT a.first_name, a.last_name, b.* FROM book b JOIN author a ON b.id = a.book_id WHERE a.last_name = 'P%';
  • 30. Count in SQL, not in PHP Don’t: foreach row in ( SELECT * FROM customer; ) $customer++; Do: SELECT count(*) FROM customer;
  • 31. Dealing with duplicates INSERT INTO product (id, ...) VALUES (24, ...); INSERT IGNORE INTO product (id, ...) VALUES (24, ...); INSERT INTO product (id, ...) ON DUPLICATE KEY UPDATE name = 'Sonic screwdriver'; REPLACE INTO product (id, ...) VALUES (24, ...); DELETE IGNORE ... UPDATE IGNORE ...
  • 32. Insert many rows INSERT INTO user (first_name, last_name, email) VALUES ('William', 'Hartnell', 'first@bbc.co.uk'), ('Tom', 'Baker', 'tom@gmail.com'), ('Jody', 'Wittaker', 'first_lady@hotmail.com');
  • 33. Insert into related tables INSERT INTO `author` (name, surname) VALUES ('Arthur', 'Clarke'); INSERT INTO `book` (author_id, title) VALUES (LAST_INSERT_ID(), '2001: A Space Odyssey');
  • 34. Delete/Update many tables DELETE `order`, user FROM `order` INNER JOIN `order` ON order.user_id = user.id WHERE user = 24; UPDATE `order`, user FROM `order` INNER JOIN `order` ON order.user_id = user.id SET status = 'CANCELLED' WHERE user = 24;
  • 35. Read+Delete data Only MariaDB: DELETE FROM user WHERE id = 2424 RETURNING first_name, last_name;
  • 36. Creating table with rows CREATE TABLE past_order LIKE `order`; INSERT INTO past_order SELECT * FROM `order` WHERE status IN ('SHIPPED', 'CANCELLED'); Or: CREATE TABLE customer SELECT u.id, u.first_name, u.last_name FROM user u JOIN `order` o ON u.id = o.user_id WHERE o.status <> 'CANCELED';
  • 37. More info For more info on this topic, ask Google: Federico Razzoli "use sql properly to run less queries"
  • 39. What are transactions? ACID ● Atomicity ○ All writes in a transaction fail or succeed altogether. ● Consistency ○ Data always switch from one consistent point to another. ● Isolation ○ Transactions are logically sequential. ● Durability ○ Data changes persist after system failures (crashes).
  • 40. Transactions syntax START TRANSACTION; SELECT … ; UPDATE … ; INSERT … ; COMMIT; START TRANSACTION; DELETE … ; INSERT … ; ROLLBACK; SET SESSION autocommit := 1; -- this is the default DELETE … ;
  • 41. Isolation levels ● READ UNCOMMITTED ○ You could see not-yet-committed changes. ● READ COMMITTED ○ Each query acquires a separate snapshot. ● REPEATABLE READ (default) ○ One snapshot for the whole transaction. ● SERIALIZABLE ○ Like REPEATABLE READ, but SELECTs are implicitly IN SHARE MODE SET TRANSACTION ISOLATION LEVEL READ COMMITTED; START TRANSACTION; ...
  • 42. Use cases for READ UNCOMMITTED?
  • 43. Use cases for READ UNCOMMITTED? ● Statistics (avg on 1M rows) ● “Hi Boris, your last access was on 12th December” ● Delete old data
  • 44. Use cases for READ COMMITTED?
  • 45. Use cases for READ COMMITTED? ● Delete/update rows by id from multiple tables ● Show user’s payment history
  • 46. READ ONLY transactions ● Make sense with REPEATABLE READ ● 2 SELECTs will see consistent data ● Attempts to change data will return an error ● Performance optimisation ○ But not as much as READ UNCOMMITTED START TRANSACTION READ ONLY;
  • 47. Ways to kill MySQL Having SELECT privilege is enough to kill MySQL! (or any RDBMS) Method 1: START TRANSACTION; SELECT * FROM `order`; SELECT SLEEP(3600 * 12);
  • 48. Ways to kill MySQL Having SELECT privilege is enough to kill MySQL! (or any RDBMS) Method 2: START TRANSACTION; SELECT * FROM `order` WHERE id = 24 FOR UPDATE; SELECT SLEEP(3600 * 12);
  • 49. More info on transactions cost For more info on how transactions work under the hood and why they can be expensive, ask Google for: Jeremy Cole "The basics of the InnoDB undo logging and history system"
  • 50. Thanks for being still awake!