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

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

PPTX
Introduction to SQL
Amin Choroomi
 
PDF
SQL Database Performance Tuning for Developers
BRIJESH KUMAR
 
PDF
SQL Joins and Query Optimization
Brian Gallagher
 
PPTX
SQLSERVERQUERIES.pptx
ssuser6bf2d1
 
PPTX
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
PPTX
More Complex SQL and Concurrency ControlModule 4.pptx
bgscseise
 
PPTX
SQL Class Note By Amit Maity PowerPoint Presentation
maitypradip938
 
PPTX
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
PPTX
Tunning sql query
vuhaininh88
 
PPTX
Structure Query Language Advance Training
parisaxena1418
 
DOCX
Sql interview prep
ssusere339c6
 
PPTX
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Abhishek590097
 
PDF
4 execution plans
Ram Kedem
 
PDF
Mysql query optimization
Baohua Cai
 
PDF
The MySQL Query Optimizer Explained Through Optimizer Trace
oysteing
 
PPTX
Practical Tutorial about the PostgreSQL Database
sistemashcp
 
PDF
Sql wksht-6
Mukesh Tekwani
 
PPTX
SQL Server Learning Drive
TechandMate
 
PDF
SQL-cheat-sheet.pdf
Alok Mohapatra
 
PDF
SQL sheet
Suman singh
 
Introduction to SQL
Amin Choroomi
 
SQL Database Performance Tuning for Developers
BRIJESH KUMAR
 
SQL Joins and Query Optimization
Brian Gallagher
 
SQLSERVERQUERIES.pptx
ssuser6bf2d1
 
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
More Complex SQL and Concurrency ControlModule 4.pptx
bgscseise
 
SQL Class Note By Amit Maity PowerPoint Presentation
maitypradip938
 
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
Tunning sql query
vuhaininh88
 
Structure Query Language Advance Training
parisaxena1418
 
Sql interview prep
ssusere339c6
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Abhishek590097
 
4 execution plans
Ram Kedem
 
Mysql query optimization
Baohua Cai
 
The MySQL Query Optimizer Explained Through Optimizer Trace
oysteing
 
Practical Tutorial about the PostgreSQL Database
sistemashcp
 
Sql wksht-6
Mukesh Tekwani
 
SQL Server Learning Drive
TechandMate
 
SQL-cheat-sheet.pdf
Alok Mohapatra
 
SQL sheet
Suman singh
 

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)

PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PDF
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
PDF
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
PPTX
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
PDF
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
PPTX
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
PPTX
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
PPTX
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
PDF
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
PDF
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
PPTX
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
PPTX
Matatag Curriculum English 8-Week 1 Day 1-5.pptx
KirbieJaneGasta1
 
PPTX
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
PDF
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
PPTX
Practice Gardens and Polytechnic Education: Utilizing Nature in 1950s’ Hu...
Lajos Somogyvári
 
PDF
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
PPTX
week 1-2.pptx yueojerjdeiwmwjsweuwikwswiewjrwiwkw
rebznelz
 
PDF
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
Matatag Curriculum English 8-Week 1 Day 1-5.pptx
KirbieJaneGasta1
 
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
Practice Gardens and Polytechnic Education: Utilizing Nature in 1950s’ Hu...
Lajos Somogyvári
 
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
week 1-2.pptx yueojerjdeiwmwjsweuwikwswiewjrwiwkw
rebznelz
 
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
Ad

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;