SlideShare a Scribd company logo
SQL Query Optimization | SQL Query Optimization Techniques | SQL Basics | SQL Query | Simplilearn
Indexes For SQL Query Optimization
Indexing in SQL acts as a shortcut that helps the database find and retrieve data
much faster.
Types Of Indexes
Clustered Indexes - Clustered indexes physically sort and store
data based on actual column values.
Non Clustered Index Clustered Index
Types Of Indexes
Non Clustered Index Clustered Index
Non-Clustered Indexes –They create a separate lookup structure that points to
the actual data.
Types Of Indexes
Full-Text Indexes –Full-text indexes help by storing word positions, making
searches much faster instead of scanning the entire text.
How Indexing Speeds Up Queries
SELECT * FROM customers WHERE name = 'John Doe';
Without an index, the query scans every row:
But by creating an index on the ‘name’ column,
the query runs much faster.
CREATE INDEX idx_customer_name ON customers(name);
Avoid SELECT * And Use Necessary Columns
When you use **SELECT *** in your queries, you’re asking the database to retrieve
every single column, even if you only need a few.
SELECT * FROM customers.customer_profiles;
SELECT customer_name, customer_email, customer_phone FROM
customers.customer_profiles;
Optimizing JOIN Operations
If you use the wrong type of join, you might end up with duplicate records, slow query
performance, or unnecessary data bloating your results. Understanding INNER JOIN, OUTER
JOIN, LEFT JOIN, and RIGHT JOIN is crucial for writing efficient queries.
Outer Joins – Use with Caution!
OUTER JOIN is like keeping everything from both, even the unrelated data.
It can create duplicates and bloat your dataset unnecessarily.
Optimizing JOIN Operations
If you use the wrong type of join, you might end up with duplicate records, slow query
performance, or unnecessary data bloating your results. Understanding INNER JOIN, OUTER
JOIN, LEFT JOIN, and RIGHT JOIN is crucial for writing efficient queries.
INNER JOIN only returns records where there’s a match between both tables.
It keeps your dataset clean and ensures you only get the necessary data.
Inner Joins – Your Best Friend!
Optimizing JOIN Operations
If you use the wrong type of join, you might end up with duplicate records, slow query
performance, or unnecessary data bloating your results. Understanding INNER JOIN, OUTER
JOIN, LEFT JOIN, and RIGHT JOIN is crucial for writing efficient queries.
SELECT
customer_orders.customer_id,
order_details.order_id,
order_details.order_date
FROM customers.customer_orders customer_orders
INNER JOIN orders.order_details order_details
ON customer_orders.customer_id = order_details.customer_id
AND customer_orders.customer_order_id = order_details.order_id;
Optimizing JOIN Operations
LEFT JOIN Vs RIGHT JOIN
Use EXISTS Instead Of IN
When checking if a value exists in a smaller dataset, EXISTS is usually much faster than IN ,
because EXISTS stops searching as soon as it finds a match, whereas IN scans the entire
dataset before deciding—making it slower, especially with large tables.
SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers
WHERE active = TRUE);
SELECT * FROM orders o
WHERE EXISTS (SELECT 1 FROM customers c WHERE c.id = o.customer_id AND
c.active = TRUE);
Minimize Subqueries & Use CTEs Instead
1️
1️
⃣ Subqueries Can Get Messy – Using too many subqueries in SQL makes your code
hard to read, debug, and optimize, just like untangling a messy ball of wires.
2️
⃣ CTEs Make Queries Cleaner – Common Table Expressions (CTEs) break queries into
readable sections, making them easier to understand, troubleshoot, and maintain—
just like writing clear step-by-step instructions.
Minimize Subqueries & Use CTEs Instead
SELECT MAX(customer_signup) AS most_recent_signup
FROM (SELECT customer_name, customer_phone, customer_signup
FROM customer_details
WHERE YEAR(customer_signup) = 2023);
WITH
2023_signups AS (
SELECT customer_name, customer_phone, customer_signup
FROM customer_details
WHERE YEAR(customer_signup) = 2023
),
Most_recent_signup AS (
SELECT MAX(customer_signup) AS most_recent_signup
FROM 2023_signups
)
Avoid Queries Inside A Loop
When you run SQL queries inside a loop—it makes
execution unnecessarily slow and inefficient.
Loops like FOR, WHILE, and DO-WHILE run queries one at a time, causing
repeated parsing, compiling, and execution, which hurts performance and
scalability.
FOR EACH customer IN customer_list LOOP
UPDATE customers SET status = 'Active' WHERE id = customer.id;
END LOOP;
UPDATE customers
SET status = 'Active'
WHERE id IN (SELECT id FROM customer_list);
Avoid Queries Inside A Loop
Avoid Redundant Data Retrieval
The larger the dataset, the slower the query, and the more resources you
waste—which can increase costs, especially in cloud-based databases.
Select Only the Needed Columns – We’ve already covered why **SELECT *** is
inefficient, but it’s also important to limit the number of rows returned, not just
columns.
Use LIMIT to Control Output – Queries that return thousands or millions of rows
can drag down performance, so always limit the results when needed.
Avoid Redundant Data Retrieval
SELECT customer_name FROM customer_details
ORDER BY customer_signup DESC
LIMIT 100;
Instead of pulling all customers, retrieve only the latest 100 signups:
SELECT customer_name FROM customer_details
ORDER BY customer_signup DESC
LIMIT 100 OFFSET 20;
Want to skip the first 20 rows and get the next 100? Use OFFSET:
How to Create A Stored Procedure?
Let’s say we want to find the most recent customer signup. Instead of writing the query
every time, we can save it as a stored procedure:
CREATE PROCEDURE find_most_recent_customer
AS BEGIN
SELECT MAX(customer_signup) AS most_recent_signup
FROM 2023_signups;
END;
EXEC find_most_recent_customer;
How to Create A Stored Procedure?
Adding Parameters for Flexibility
CREATE PROCEDURE find_most_recent_customer @store_id
INT
AS BEGIN
SELECT MAX(customer_signup) AS most_recent_signup
FROM 2023_signups
WHERE store_id = @store_id;
END;
EXEC find_most_recent_customer @store_id = 1188;
Normalize Your Database Tables
1. First Normal Form (1NF) – No Nested Data!
Normalize Your Database Tables
2. Second Normal Form (2NF) – Split Multi-Value Fields
Normalize Your Database Tables
3. Third Normal Form (3NF) – Remove Column Dependencies
Monitoring Query Performance
When you run SQL queries without monitoring their performance—you have no idea
which queries are slowing down your database or costing you extra resources.
Identifies Slow Queries
Saves Costs in Cloud Databases
Prevents System Slowdowns
Monitoring Query Performance
Tools for Monitoring Query Performance
Query Profiling
Query Execution Plans
Database Logs & Server Monitoring
Monitoring Query Performance
Let’s say you have a slow query, and you want to analyze its
performance. You can use MySQL’s EXPLAIN statement:
EXPLAIN SELECT customer_name FROM customers
WHERE city = 'New York';
Use UNION ALL Instead Of UNION
If you use UNION, you’re double-checking every name to remove duplicates
before finalizing the list. But if you use UNION ALL, you simply combine both lists
as they are—faster, simpler, and without extra processing.
UNION – Combines results from two tables and removes duplicates (which takes
extra processing time).
UNION ALL – Combines results without checking for duplicates, making it faster
and more efficient.
Use UNION ALL Instead Of UNION
SELECT customer_name FROM customers_2023
UNION
SELECT customer_name FROM customers_2024;
SELECT customer_name FROM customers_2023
UNION ALL
SELECT customer_name FROM customers_2024;
Leverage Cloud Database-Specific Features
Cloud providers like Snowflake, BigQuery, and Redshift come with built-in
optimizations and custom SQL functions designed to improve performance,
simplify queries, and handle data more efficiently.
Built-in Functions
Optimized Performance
Cost Efficiency
Leverage Cloud Database-Specific Features
Example: Snowflake’s JSON Functions
SELECT
json_column:customer.name::STRING AS customer_name,
json_column:customer.email::STRING AS customer_email
FROM orders;

More Related Content

PPTX
Database optimization
EsraaAlattar1
 
PPTX
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
bhavaniteacher99
 
PDF
SQL command for daily use ddl dml dcl dql
kashyapdaksh29
 
PPT
INTRODUCTION TO SQL QUERIES REALTED BRIEF
VADAPALLYPRAVEENKUMA1
 
PDF
Building better SQL Server Databases
ColdFusionConference
 
PPTX
Database Basics
Abdel Moneim Emad
 
ODP
SQL Tunning
Dhananjay Goel
 
PDF
A Review of Data Access Optimization Techniques in a Distributed Database Man...
Editor IJCATR
 
Database optimization
EsraaAlattar1
 
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
bhavaniteacher99
 
SQL command for daily use ddl dml dcl dql
kashyapdaksh29
 
INTRODUCTION TO SQL QUERIES REALTED BRIEF
VADAPALLYPRAVEENKUMA1
 
Building better SQL Server Databases
ColdFusionConference
 
Database Basics
Abdel Moneim Emad
 
SQL Tunning
Dhananjay Goel
 
A Review of Data Access Optimization Techniques in a Distributed Database Man...
Editor IJCATR
 

Similar to SQL Query Optimization | SQL Query Optimization Techniques | SQL Basics | SQL Query | Simplilearn (20)

PDF
A Review of Data Access Optimization Techniques in a Distributed Database Man...
Editor IJCATR
 
PPT
Database performance tuning and query optimization
Usman Tariq
 
PPTX
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
PPTX
Tunning sql query
vuhaininh88
 
PPTX
PPT SQL CLASS.pptx
AngeOuattara
 
PPTX
How to Think Like the SQL Server Engine
Brent Ozar
 
PPTX
SQL Server 2008 Development for Programmers
Adam Hutson
 
PPTX
Crucial Tips to Improve MySQL Database Performance.pptx
Tosska Technology
 
PPTX
53 SQL Questions-Answers12121212121212.pptx
Ganesh Shirsat
 
DOCX
How to design a database that include planning
Kamal Golan
 
PPTX
53 SQL Questions-Answers=53 SQL Questions-Answers
marukochan23
 
PPTX
Query Optimization in SQL Server
Rajesh Gunasundaram
 
PDF
Databases By ZAK
Tabsheer Hasan
 
ODP
Performance tuning
ami111
 
PPT
15 Ways to Kill Your Mysql Application Performance
guest9912e5
 
PPTX
How Clean is your Database? Data Scrubbing for all Skill Sets
Chad Petrovay
 
ODP
Mysql For Developers
Carol McDonald
 
PPTX
Join_Queries_Presentation_By_Beate_.pptx
beatereichrath9
 
PPT
MYSQL.ppt
webhostingguy
 
PPT
SQL Server 2000 Research Series - Performance Tuning
Jerry Yang
 
A Review of Data Access Optimization Techniques in a Distributed Database Man...
Editor IJCATR
 
Database performance tuning and query optimization
Usman Tariq
 
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
Tunning sql query
vuhaininh88
 
PPT SQL CLASS.pptx
AngeOuattara
 
How to Think Like the SQL Server Engine
Brent Ozar
 
SQL Server 2008 Development for Programmers
Adam Hutson
 
Crucial Tips to Improve MySQL Database Performance.pptx
Tosska Technology
 
53 SQL Questions-Answers12121212121212.pptx
Ganesh Shirsat
 
How to design a database that include planning
Kamal Golan
 
53 SQL Questions-Answers=53 SQL Questions-Answers
marukochan23
 
Query Optimization in SQL Server
Rajesh Gunasundaram
 
Databases By ZAK
Tabsheer Hasan
 
Performance tuning
ami111
 
15 Ways to Kill Your Mysql Application Performance
guest9912e5
 
How Clean is your Database? Data Scrubbing for all Skill Sets
Chad Petrovay
 
Mysql For Developers
Carol McDonald
 
Join_Queries_Presentation_By_Beate_.pptx
beatereichrath9
 
MYSQL.ppt
webhostingguy
 
SQL Server 2000 Research Series - Performance Tuning
Jerry Yang
 
Ad

More from Simplilearn (20)

PPTX
Top 50 Scrum Master Interview Questions | Scrum Master Interview Questions & ...
Simplilearn
 
PPTX
Bagging Vs Boosting In Machine Learning | Ensemble Learning In Machine Learni...
Simplilearn
 
PPTX
Future Of Social Media | Social Media Trends and Strategies 2025 | Instagram ...
Simplilearn
 
PPTX
SQL INterview Questions .pTop 45 SQL Interview Questions And Answers In 2025 ...
Simplilearn
 
PPTX
How To Start Influencer Marketing Business | Influencer Marketing For Beginne...
Simplilearn
 
PPTX
Cyber Security Roadmap 2025 | How To Become Cyber Security Engineer In 2025 |...
Simplilearn
 
PPTX
How To Become An AI And ML Engineer In 2025 | AI Engineer Roadmap | AI ML Car...
Simplilearn
 
PPTX
What Is GitHub Copilot? | How To Use GitHub Copilot? | How does GitHub Copilo...
Simplilearn
 
PPTX
Top 10 Data Analyst Certification For 2025 | Best Data Analyst Certification ...
Simplilearn
 
PPTX
Complete Data Science Roadmap For 2025 | Data Scientist Roadmap For Beginners...
Simplilearn
 
PPTX
Top 7 High Paying AI Certifications Courses For 2025 | Best AI Certifications...
Simplilearn
 
PPTX
Data Cleaning In Data Mining | Step by Step Data Cleaning Process | Data Clea...
Simplilearn
 
PPTX
Top 10 Data Analyst Projects For 2025 | Data Analyst Projects | Data Analysis...
Simplilearn
 
PPTX
AI Engineer Roadmap 2025 | AI Engineer Roadmap For Beginners | AI Engineer Ca...
Simplilearn
 
PPTX
Machine Learning Roadmap 2025 | Machine Learning Engineer Roadmap For Beginne...
Simplilearn
 
PPTX
Kotter's 8-Step Change Model Explained | Kotter's Change Management Model | S...
Simplilearn
 
PPTX
Gen AI Engineer Roadmap For 2025 | How To Become Gen AI Engineer In 2025 | Si...
Simplilearn
 
PPTX
Top 10 Data Analyst Certification For 2025 | Best Data Analyst Certification ...
Simplilearn
 
PPTX
Complete Data Science Roadmap For 2025 | Data Scientist Roadmap For Beginners...
Simplilearn
 
PPTX
Top 7 High Paying AI Certifications Courses For 2025 | Best AI Certifications...
Simplilearn
 
Top 50 Scrum Master Interview Questions | Scrum Master Interview Questions & ...
Simplilearn
 
Bagging Vs Boosting In Machine Learning | Ensemble Learning In Machine Learni...
Simplilearn
 
Future Of Social Media | Social Media Trends and Strategies 2025 | Instagram ...
Simplilearn
 
SQL INterview Questions .pTop 45 SQL Interview Questions And Answers In 2025 ...
Simplilearn
 
How To Start Influencer Marketing Business | Influencer Marketing For Beginne...
Simplilearn
 
Cyber Security Roadmap 2025 | How To Become Cyber Security Engineer In 2025 |...
Simplilearn
 
How To Become An AI And ML Engineer In 2025 | AI Engineer Roadmap | AI ML Car...
Simplilearn
 
What Is GitHub Copilot? | How To Use GitHub Copilot? | How does GitHub Copilo...
Simplilearn
 
Top 10 Data Analyst Certification For 2025 | Best Data Analyst Certification ...
Simplilearn
 
Complete Data Science Roadmap For 2025 | Data Scientist Roadmap For Beginners...
Simplilearn
 
Top 7 High Paying AI Certifications Courses For 2025 | Best AI Certifications...
Simplilearn
 
Data Cleaning In Data Mining | Step by Step Data Cleaning Process | Data Clea...
Simplilearn
 
Top 10 Data Analyst Projects For 2025 | Data Analyst Projects | Data Analysis...
Simplilearn
 
AI Engineer Roadmap 2025 | AI Engineer Roadmap For Beginners | AI Engineer Ca...
Simplilearn
 
Machine Learning Roadmap 2025 | Machine Learning Engineer Roadmap For Beginne...
Simplilearn
 
Kotter's 8-Step Change Model Explained | Kotter's Change Management Model | S...
Simplilearn
 
Gen AI Engineer Roadmap For 2025 | How To Become Gen AI Engineer In 2025 | Si...
Simplilearn
 
Top 10 Data Analyst Certification For 2025 | Best Data Analyst Certification ...
Simplilearn
 
Complete Data Science Roadmap For 2025 | Data Scientist Roadmap For Beginners...
Simplilearn
 
Top 7 High Paying AI Certifications Courses For 2025 | Best AI Certifications...
Simplilearn
 
Ad

Recently uploaded (20)

PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 

SQL Query Optimization | SQL Query Optimization Techniques | SQL Basics | SQL Query | Simplilearn

  • 2. Indexes For SQL Query Optimization Indexing in SQL acts as a shortcut that helps the database find and retrieve data much faster.
  • 3. Types Of Indexes Clustered Indexes - Clustered indexes physically sort and store data based on actual column values. Non Clustered Index Clustered Index
  • 4. Types Of Indexes Non Clustered Index Clustered Index Non-Clustered Indexes –They create a separate lookup structure that points to the actual data.
  • 5. Types Of Indexes Full-Text Indexes –Full-text indexes help by storing word positions, making searches much faster instead of scanning the entire text.
  • 6. How Indexing Speeds Up Queries SELECT * FROM customers WHERE name = 'John Doe'; Without an index, the query scans every row: But by creating an index on the ‘name’ column, the query runs much faster. CREATE INDEX idx_customer_name ON customers(name);
  • 7. Avoid SELECT * And Use Necessary Columns When you use **SELECT *** in your queries, you’re asking the database to retrieve every single column, even if you only need a few. SELECT * FROM customers.customer_profiles; SELECT customer_name, customer_email, customer_phone FROM customers.customer_profiles;
  • 8. Optimizing JOIN Operations If you use the wrong type of join, you might end up with duplicate records, slow query performance, or unnecessary data bloating your results. Understanding INNER JOIN, OUTER JOIN, LEFT JOIN, and RIGHT JOIN is crucial for writing efficient queries. Outer Joins – Use with Caution! OUTER JOIN is like keeping everything from both, even the unrelated data. It can create duplicates and bloat your dataset unnecessarily.
  • 9. Optimizing JOIN Operations If you use the wrong type of join, you might end up with duplicate records, slow query performance, or unnecessary data bloating your results. Understanding INNER JOIN, OUTER JOIN, LEFT JOIN, and RIGHT JOIN is crucial for writing efficient queries. INNER JOIN only returns records where there’s a match between both tables. It keeps your dataset clean and ensures you only get the necessary data. Inner Joins – Your Best Friend!
  • 10. Optimizing JOIN Operations If you use the wrong type of join, you might end up with duplicate records, slow query performance, or unnecessary data bloating your results. Understanding INNER JOIN, OUTER JOIN, LEFT JOIN, and RIGHT JOIN is crucial for writing efficient queries. SELECT customer_orders.customer_id, order_details.order_id, order_details.order_date FROM customers.customer_orders customer_orders INNER JOIN orders.order_details order_details ON customer_orders.customer_id = order_details.customer_id AND customer_orders.customer_order_id = order_details.order_id;
  • 11. Optimizing JOIN Operations LEFT JOIN Vs RIGHT JOIN
  • 12. Use EXISTS Instead Of IN When checking if a value exists in a smaller dataset, EXISTS is usually much faster than IN , because EXISTS stops searching as soon as it finds a match, whereas IN scans the entire dataset before deciding—making it slower, especially with large tables. SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE active = TRUE); SELECT * FROM orders o WHERE EXISTS (SELECT 1 FROM customers c WHERE c.id = o.customer_id AND c.active = TRUE);
  • 13. Minimize Subqueries & Use CTEs Instead 1️ 1️ ⃣ Subqueries Can Get Messy – Using too many subqueries in SQL makes your code hard to read, debug, and optimize, just like untangling a messy ball of wires. 2️ ⃣ CTEs Make Queries Cleaner – Common Table Expressions (CTEs) break queries into readable sections, making them easier to understand, troubleshoot, and maintain— just like writing clear step-by-step instructions.
  • 14. Minimize Subqueries & Use CTEs Instead SELECT MAX(customer_signup) AS most_recent_signup FROM (SELECT customer_name, customer_phone, customer_signup FROM customer_details WHERE YEAR(customer_signup) = 2023); WITH 2023_signups AS ( SELECT customer_name, customer_phone, customer_signup FROM customer_details WHERE YEAR(customer_signup) = 2023 ), Most_recent_signup AS ( SELECT MAX(customer_signup) AS most_recent_signup FROM 2023_signups )
  • 15. Avoid Queries Inside A Loop When you run SQL queries inside a loop—it makes execution unnecessarily slow and inefficient. Loops like FOR, WHILE, and DO-WHILE run queries one at a time, causing repeated parsing, compiling, and execution, which hurts performance and scalability.
  • 16. FOR EACH customer IN customer_list LOOP UPDATE customers SET status = 'Active' WHERE id = customer.id; END LOOP; UPDATE customers SET status = 'Active' WHERE id IN (SELECT id FROM customer_list); Avoid Queries Inside A Loop
  • 17. Avoid Redundant Data Retrieval The larger the dataset, the slower the query, and the more resources you waste—which can increase costs, especially in cloud-based databases. Select Only the Needed Columns – We’ve already covered why **SELECT *** is inefficient, but it’s also important to limit the number of rows returned, not just columns. Use LIMIT to Control Output – Queries that return thousands or millions of rows can drag down performance, so always limit the results when needed.
  • 18. Avoid Redundant Data Retrieval SELECT customer_name FROM customer_details ORDER BY customer_signup DESC LIMIT 100; Instead of pulling all customers, retrieve only the latest 100 signups: SELECT customer_name FROM customer_details ORDER BY customer_signup DESC LIMIT 100 OFFSET 20; Want to skip the first 20 rows and get the next 100? Use OFFSET:
  • 19. How to Create A Stored Procedure? Let’s say we want to find the most recent customer signup. Instead of writing the query every time, we can save it as a stored procedure: CREATE PROCEDURE find_most_recent_customer AS BEGIN SELECT MAX(customer_signup) AS most_recent_signup FROM 2023_signups; END; EXEC find_most_recent_customer;
  • 20. How to Create A Stored Procedure? Adding Parameters for Flexibility CREATE PROCEDURE find_most_recent_customer @store_id INT AS BEGIN SELECT MAX(customer_signup) AS most_recent_signup FROM 2023_signups WHERE store_id = @store_id; END; EXEC find_most_recent_customer @store_id = 1188;
  • 21. Normalize Your Database Tables 1. First Normal Form (1NF) – No Nested Data!
  • 22. Normalize Your Database Tables 2. Second Normal Form (2NF) – Split Multi-Value Fields
  • 23. Normalize Your Database Tables 3. Third Normal Form (3NF) – Remove Column Dependencies
  • 24. Monitoring Query Performance When you run SQL queries without monitoring their performance—you have no idea which queries are slowing down your database or costing you extra resources. Identifies Slow Queries Saves Costs in Cloud Databases Prevents System Slowdowns
  • 25. Monitoring Query Performance Tools for Monitoring Query Performance Query Profiling Query Execution Plans Database Logs & Server Monitoring
  • 26. Monitoring Query Performance Let’s say you have a slow query, and you want to analyze its performance. You can use MySQL’s EXPLAIN statement: EXPLAIN SELECT customer_name FROM customers WHERE city = 'New York';
  • 27. Use UNION ALL Instead Of UNION If you use UNION, you’re double-checking every name to remove duplicates before finalizing the list. But if you use UNION ALL, you simply combine both lists as they are—faster, simpler, and without extra processing. UNION – Combines results from two tables and removes duplicates (which takes extra processing time). UNION ALL – Combines results without checking for duplicates, making it faster and more efficient.
  • 28. Use UNION ALL Instead Of UNION SELECT customer_name FROM customers_2023 UNION SELECT customer_name FROM customers_2024; SELECT customer_name FROM customers_2023 UNION ALL SELECT customer_name FROM customers_2024;
  • 29. Leverage Cloud Database-Specific Features Cloud providers like Snowflake, BigQuery, and Redshift come with built-in optimizations and custom SQL functions designed to improve performance, simplify queries, and handle data more efficiently. Built-in Functions Optimized Performance Cost Efficiency
  • 30. Leverage Cloud Database-Specific Features Example: Snowflake’s JSON Functions SELECT json_column:customer.name::STRING AS customer_name, json_column:customer.email::STRING AS customer_email FROM orders;