Welcome back, young data explorer! In Module 1, you learned what a database is. In Module 2, you learned how to install PostgreSQL, create databases, and run simple queries. In Module 3, you learned about joins, subqueries, views, functions, indexes, and normalization.
In this module, we are going to learn about performance tuning and optimization. Performance means how fast something works. Tuning means making it work better. Optimization means making something as good as it can be. We will learn how to make PostgreSQL run faster. We will learn how to make queries faster. We will learn how to keep the database healthy.
Do not worry if some words sound big. We will explain everything in simple language. We will use stories, examples from Nigeria, examples from school, and examples from home. We will use pictures made from keyboard characters (ASCII art) to help you see what we mean. By the end of this module, you will know:
This module is long because it is a complete chapter, not just short notes. Take your time. Read one lesson at a time. Do the exercises. Ask questions. Practice on your computer. Are you ready? Let us begin!
After finishing this module, you should be able to:
Emeka was a 13-year-old boy who lived in Port Harcourt, Nigeria. His mother owned a big shop. The shop had thousands of customers and thousands of sales.
Emeka had built a PostgreSQL database for the shop. It worked well at first. But as the shop grew, the database became slow. Queries that used to take one second now took ten seconds. Emeka's mother was frustrated. "I need to find customer information quickly!" she said.
Emeka remembered his PostgreSQL lessons. "I need to tune the database," he said. "I need to check how queries run. I need to add indexes. I need to vacuum the database."
Emeka used EXPLAIN ANALYZE to see how queries ran. He found that some queries were searching every row. He added indexes. The queries became fast again.
He ran VACUUM to clean up the database. The database became healthy again. His mother was very happy.
Moral of the story: Performance tuning makes databases fast and healthy. Anyone can learn to tune a database.
Performance tuning is the process of making a database run faster. It means finding slow queries and making them faster. It means keeping the database healthy.
A slow database frustrates users. They wait a long time for results. A fast database makes users happy. It helps businesses work better.
Imagine you are riding a bicycle. If the chain is rusty, you go slowly. If you oil the chain, you go faster. Performance tuning is like oiling the chain.
A bank tunes its database so customers can check their balances quickly.
A school tunes its database so teachers can find student scores quickly.
At home, you tune your recipe database so you can find recipes quickly.
In a Nigerian market, a trader tunes the sales database so customers do not wait.
PERFORMANCE TUNING:
[ SLOW DATABASE ]
|
V
[ FIND SLOW QUERIES ]
|
V
[ ADD INDEXES ]
|
V
[ VACUUM DATABASE ]
|
V
[ FAST DATABASE! ]
Performance tuning makes a database run faster. It helps users get results quickly.
You learned what performance tuning is. You saw examples from home, school, and Nigeria. Now you know that tuning makes databases fast.
EXPLAIN ANALYZE is a command that shows how PostgreSQL runs a query. It shows the steps PostgreSQL takes. It shows how long each step takes.
EXPLAIN ANALYZE helps you find slow parts of a query. You can then fix those parts and make the query faster.
Imagine you are driving to a new place. You use a map to see the route. EXPLAIN ANALYZE is like a map for your query. It shows the route PostgreSQL takes.
A bank uses EXPLAIN ANALYZE to find slow queries. The bank fixes them.
A school uses EXPLAIN ANALYZE to find slow queries. The school fixes them.
At home, you use EXPLAIN ANALYZE to find slow queries. You fix them.
In a Nigerian market, a trader uses EXPLAIN ANALYZE to find slow queries. The trader fixes them.
EXPLAIN ANALYZE SELECT * FROM sales WHERE item = 'Rice';
EXPLAIN ANALYZE:
[ TYPE: EXPLAIN ANALYZE SELECT ... ]
|
V
[ POSTGRESQL RUNS THE QUERY ]
|
V
[ SHOWS THE PLAN ]
[ SHOWS THE TIME ]
|
V
[ YOU FIND SLOW PARTS ]
EXPLAIN ANALYZE shows how PostgreSQL runs a query. It helps you find slow parts and fix them.
You learned about EXPLAIN ANALYZE. You saw examples from home, school, and Nigeria. Now you can use it to understand your queries.
A query plan is the set of steps PostgreSQL takes to run a query. EXPLAIN ANALYZE shows the query plan.
Understanding the query plan helps you find problems. You can see if PostgreSQL is searching every row or using an index.
Imagine you are giving directions to a friend. You say: "Go straight, turn left, then turn right." A query plan is like those directions. It shows the steps PostgreSQL takes.
A bank reads the query plan to see if a query uses an index.
A school reads the query plan to see if a query is slow.
At home, you read the query plan to see if a recipe search is fast.
In a Nigerian market, a trader reads the query plan to see if a sales search is fast.
| Step | What It Means |
|---|---|
| Seq Scan | Searching every row in the table |
| Index Scan | Using an index to find rows |
| Bitmap Heap Scan | Using an index to find rows, then reading the table |
| Hash Join | Joining tables using a hash table |
| Merge Join | Joining tables by sorting and merging |
| Nested Loop | Joining tables by looping through rows |
| Sort | Sorting rows |
| Aggregate | Calculating totals or averages |
QUERY PLAN:
EXPLAIN ANALYZE SELECT * FROM sales WHERE item = 'Rice';
QUERY PLAN
----------------------------------------------------------
Index Scan using idx_sales_item on sales (cost=0.00..8.27 rows=1 width=...)
Index Cond: (item = 'Rice'::text)
(2 rows)
A query plan shows the steps PostgreSQL takes to run a query. Understanding it helps you find problems.
You learned about query plans. You saw a table of common steps. Now you can read query plans and find problems.
A slow query is a query that takes a long time to run. Slow queries frustrate users. They slow down the whole database.
Finding slow queries helps you fix them. Fixing slow queries makes the whole database faster.
Imagine you have a car. One tyre is flat. The car goes slowly. The flat tyre is like a slow query. You must find it and fix it.
A bank finds a slow query. The query searches every row in the customers table. The bank adds an index. The query becomes fast.
A school finds a slow query. The query searches every row in the scores table. The school adds an index. The query becomes fast.
At home, you find a slow query. The query searches every row in the recipes table. You add an index. The query becomes fast.
In a Nigerian market, a trader finds a slow query. The query searches every row in the sales table. The trader adds an index. The query becomes fast.
FINDING SLOW QUERIES:
[ USE EXPLAIN ANALYZE ]
|
V
[ LOOK FOR "Seq Scan" ]
|
V
[ LOOK FOR HIGH COST ]
|
V
[ LOOK FOR LONG TIME ]
|
V
[ FOUND SLOW QUERY ]
Slow queries take a long time to run. You can find them using EXPLAIN ANALYZE.
You learned how to find slow queries. You saw examples from home, school, and Nigeria. Now you can find slow queries in your database.
An index is a data structure that makes queries faster. It works like the index at the back of a book.
Without an index, PostgreSQL must search every row. With an index, PostgreSQL can find data much faster.
Imagine you have a big book. You want to find a topic. Without an index, you must read every page. With an index, you find the page number quickly.
A bank creates an index on customer account numbers. The bank can find any account in seconds.
A school creates an index on student names. The school can find any student quickly.
At home, you create an index on recipe names. You can find any recipe quickly.
In a Nigerian market, a trader creates an index on item names. The trader can find any item quickly.
CREATE INDEX idx_customer_name ON customers (name); -- Now queries on customer name are faster SELECT * FROM customers WHERE name = 'Chika';
| Use an Index When | Do Not Use an Index When |
|---|---|
| You search a column often | The table is very small |
| You join tables on a column | You update the table very often |
| You sort by a column | The column has many duplicate values |
| You filter by a column | The column is not used in queries |
WITHOUT INDEX: [ SEARCH EVERY ROW ] --> [ SLOW ] WITH INDEX: [ LOOK UP IN INDEX ] --> [ FIND ROW ] --> [ FAST ]
Indexes make queries faster. They work like the index in a book. Use them on columns you search often.
You learned how to make queries faster with indexes. You saw a table of when to use them. Now you can create indexes to speed up your queries.
Vacuuming is a process that cleans up a PostgreSQL database. It removes old data that is no longer needed. It keeps the database healthy and fast.
When you update or delete data, PostgreSQL keeps the old data for a while. This old data takes up space. It slows down queries. Vacuuming removes the old data.
Imagine your room. You have old toys you do not play with anymore. They take up space. You must clean them out. Vacuuming is like cleaning your room.
A bank vacuums its database every night. The database stays fast.
A school vacuums its database every week. The database stays fast.
At home, you vacuum your recipe database every month. The database stays fast.
In a Nigerian market, a trader vacuums the sales database every week. The database stays fast.
VACUUM; VACUUM FULL; VACUUM ANALYZE;
VACUUMING:
[ DATABASE WITH OLD DATA ]
|
V
[ RUN VACUUM ]
|
V
[ OLD DATA REMOVED ]
|
V
[ DATABASE IS FAST AND HEALTHY ]
Vacuuming cleans up a PostgreSQL database. It removes old data. It keeps the database fast.
You learned about vacuuming. You saw examples from home, school, and Nigeria. Now you can vacuum your database to keep it healthy.
ANALYZE is a command that collects statistics about the data in a table. PostgreSQL uses these statistics to plan queries.
Good statistics help PostgreSQL choose the best query plan. Without statistics, PostgreSQL might choose a slow plan.
Imagine you are a teacher. You want to know how many students scored above 80. You count them. ANALYZE is like counting the data.
A bank runs ANALYZE on its tables. PostgreSQL plans queries better.
A school runs ANALYZE on its tables. PostgreSQL plans queries better.
At home, you run ANALYZE on your recipes. PostgreSQL plans queries better.
In a Nigerian market, a trader runs ANALYZE on sales. PostgreSQL plans queries better.
ANALYZE; ANALYZE sales; ANALYZE VERBOSE;
ANALYZE:
[ TABLE WITH DATA ]
|
V
[ RUN ANALYZE ]
|
V
[ STATISTICS COLLECTED ]
|
V
[ POSTGRESQL PLANS BETTER QUERIES ]
ANALYZE collects statistics about the data in a table. PostgreSQL uses these statistics to plan queries.
You learned about ANALYZE. You saw examples from home, school, and Nigeria. Now you can collect statistics to improve query planning.
Connection pooling is a way to reuse database connections. Instead of opening a new connection for every query, you reuse old connections.
Opening a connection takes time. If you have many users, opening many connections slows things down. Connection pooling saves time and resources.
Imagine you have a phone. You call your friend. You talk. You hang up. Then you call again. You talk. You hang up. This takes time. Connection pooling is like keeping the line open. You do not have to call again.
A bank uses connection pooling. Many customers can use the database at once.
A school uses connection pooling. Many students can use the database at once.
At home, you use connection pooling. Many family members can use the database at once.
In a Nigerian market, a trader uses connection pooling. Many customers can buy at once.
WITHOUT POOLING: [ USER 1 ] --> [ OPEN CONNECTION ] --> [ CLOSE ] [ USER 2 ] --> [ OPEN CONNECTION ] --> [ CLOSE ] [ USER 3 ] --> [ OPEN CONNECTION ] --> [ CLOSE ] (slow) WITH POOLING: [ USER 1 ] --+ [ USER 2 ] --+--> [ REUSE CONNECTION ] --> [ FAST ] [ USER 3 ] --+
Connection pooling reuses database connections. It saves time and resources.
You learned about connection pooling. You saw examples from home, school, and Nigeria. Now you know how to make your database handle many users.
Monitoring means watching your database to see how it is doing. It means checking for problems before they become serious.
If you do not monitor, you might not know about problems. Monitoring helps you fix problems before users complain.
Imagine you have a garden. You check the plants every day. You water them. You remove weeds. Monitoring a database is like checking a garden.
A bank monitors its database. It finds a slow query and fixes it.
A school monitors its database. It finds a disk space problem and fixes it.
At home, you monitor your recipe database. You find a slow query and fix it.
In a Nigerian market, a trader monitors the sales database. The trader finds a problem and fixes it.
| What to Monitor | Why It Is Important |
|---|---|
| Query times | Find slow queries |
| Disk space | Make sure you have enough space |
| CPU usage | Make sure the CPU is not overloaded |
| Memory usage | Make sure the database has enough memory |
| Connections | Make sure you are not running out of connections |
| Locks | Make sure queries are not blocked |
| Errors | Fix problems quickly |
MONITORING:
[ WATCH QUERY TIMES ]
|
V
[ WATCH DISK SPACE ]
|
V
[ WATCH CPU AND MEMORY ]
|
V
[ WATCH CONNECTIONS AND LOCKS ]
|
V
[ FIX PROBLEMS BEFORE THEY GET WORSE ]
Monitoring means watching your database. It helps you find and fix problems.
You learned about monitoring. You saw a table of what to monitor. Now you can watch your database and keep it healthy.
pg_stat_statements is a PostgreSQL extension. It tracks how long queries take. It helps you find slow queries.
Without pg_stat_statements, it is hard to find slow queries. With it, you can see which queries are slow and fix them.
Imagine you are a coach. You want to know which players are slow. You time them. pg_stat_statements is like a stopwatch for queries.
A bank uses pg_stat_statements to find slow queries.
A school uses pg_stat_statements to find slow queries.
At home, you use pg_stat_statements to find slow queries.
In a Nigerian market, a trader uses pg_stat_statements to find slow queries.
CREATE EXTENSION pg_stat_statements; SELECT query, calls, total_time, mean_time FROM pg_stat_statements ORDER BY mean_time DESC LIMIT 10;
pg_stat_statements:
[ INSTALL EXTENSION ]
|
V
[ TRACK QUERY TIMES ]
|
V
[ FIND SLOW QUERIES ]
|
V
[ FIX THEM ]
pg_stat_statements tracks how long queries take. It helps you find slow queries.
You learned about pg_stat_statements. You saw examples from home, school, and Nigeria. Now you can find slow queries using this tool.
Optimizing joins means making joins run faster. Joins can be slow if they are not optimized.
Joins are used often. If joins are slow, the whole database is slow.
Imagine you are putting together two puzzles. If you have a plan, it is fast. If you do not have a plan, it is slow. Optimizing joins is like making a plan.
A bank optimizes its joins. Queries run faster.
A school optimizes its joins. Queries run faster.
At home, you optimize your joins. Queries run faster.
In a Nigerian market, a trader optimizes joins. Queries run faster.
OPTIMIZING JOINS:
[ CREATE INDEX ON JOIN COLUMNS ]
|
V
[ USE INNER JOIN WHEN POSSIBLE ]
|
V
[ FILTER EARLY ]
|
V
[ CHECK WITH EXPLAIN ANALYZE ]
|
V
[ FAST JOINS! ]
Optimizing joins makes them run faster. Use indexes and choose the right join type.
You learned how to optimize joins. You saw a list of tips. Now you can make your joins faster.
Optimizing subqueries means making subqueries run faster. Subqueries can be slow if they are not optimized.
Subqueries are used often. If subqueries are slow, the whole query is slow.
Imagine you are looking for a book in a library. You ask a librarian. The librarian asks another librarian. This takes time. Optimizing subqueries is like asking one librarian who knows everything.
A bank optimizes its subqueries. Queries run faster.
A school optimizes its subqueries. Queries run faster.
At home, you optimize your subqueries. Queries run faster.
In a Nigerian market, a trader optimizes subqueries. Queries run faster.
OPTIMIZING SUBQUERIES:
[ USE JOIN INSTEAD OF SUBQUERY ]
|
V
[ USE EXISTS INSTEAD OF IN ]
|
V
[ CREATE INDEXES ]
|
V
[ CHECK WITH EXPLAIN ANALYZE ]
|
V
[ FAST SUBQUERIES! ]
Optimizing subqueries makes them run faster. Use joins and EXISTS when possible.
You learned how to optimize subqueries. You saw a list of tips. Now you can make your subqueries faster.
Partitioning means splitting a large table into smaller tables. Each smaller table is called a partition. PostgreSQL treats the partitions as one table.
Large tables are slow. Partitioning makes them faster. Queries only search the relevant partition.
Imagine you have a big book. You split it into chapters. When you want to find something, you only look in one chapter. Partitioning is like splitting a big table into chapters.
A bank partitions its transactions table by year. Queries are faster.
A school partitions its scores table by term. Queries are faster.
At home, you partition your recipes by meal type. Queries are faster.
In a Nigerian market, a trader partitions sales by month. Queries are faster.
CREATE TABLE sales (
id SERIAL,
item VARCHAR(50),
sale_date DATE
) PARTITION BY RANGE (sale_date);
CREATE TABLE sales_2025 PARTITION OF sales
FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
PARTITIONING:
[ LARGE TABLE ]
|
V
[ SPLIT INTO PARTITIONS ]
|
+---- [ PARTITION 1 ]
|
+---- [ PARTITION 2 ]
|
+---- [ PARTITION 3 ]
|
V
[ QUERIES ONLY SEARCH RELEVANT PARTITION ]
|
V
[ FASTER QUERIES! ]
Partitioning splits a large table into smaller tables. Queries only search the relevant partition.
You learned about partitioning. You saw examples from home, school, and Nigeria. Now you can partition large tables to make them faster.
Best practices are the best ways to do things. They help you keep your database fast and healthy.
Following best practices saves time. It prevents problems. It makes your database reliable.
Imagine you are washing your hands. You use soap and water. You scrub for 20 seconds. Best practices for performance tuning are like washing your hands properly.
A bank follows best practices. Its database is fast and reliable.
A school follows best practices. Its database is fast and reliable.
At home, you follow best practices. Your database is fast and reliable.
In a Nigerian market, a trader follows best practices. The database is fast and reliable.
BEST PRACTICES:
[ USE INDEXES ] --> [ VACUUM REGULARLY ]
| |
V V
[ RUN ANALYZE ] --> [ USE CONNECTION POOLING ]
| |
V V
[ MONITOR DATABASE ] --> [ USE EXPLAIN ANALYZE ]
| |
V V
[ OPTIMIZE JOINS ] --> [ PARTITION LARGE TABLES ]
| |
V V
[ FAST AND HEALTHY DATABASE! ]
Best practices help you keep your database fast and healthy. Follow them to avoid problems.
You learned best practices for performance tuning. You saw a list. Now you can keep your database in top shape.
Putting it all together means using all your performance tuning skills. It means making your database as fast and healthy as possible.
A well-tuned database makes users happy. It helps businesses work better.
Imagine you are building a car. You need an engine, wheels, and a steering wheel. Putting it all together means assembling all the parts. In the same way, you assemble all your tuning skills to make a fast database.
A bank puts it all together. Its database is fast and reliable.
A school puts it all together. Its database is fast and reliable.
At home, you put it all together. Your database is fast and reliable.
In a Nigerian market, a trader puts it all together. The database is fast and reliable.
PUTTING IT ALL TOGETHER:
[ USE EXPLAIN ANALYZE ]
|
V
[ ADD INDEXES ]
|
V
[ VACUUM AND ANALYZE ]
|
V
[ USE CONNECTION POOLING ]
|
V
[ MONITOR DATABASE ]
|
V
[ OPTIMIZE JOINS AND SUBQUERIES ]
|
V
[ PARTITION LARGE TABLES ]
|
V
[ FAST AND HEALTHY DATABASE! ๐ ]
Putting it all together means using all your performance tuning skills. It makes your database fast and healthy.
You learned how to put everything together. You saw examples from home, school, and Nigeria. Now you can tune your database like a professional.
| Word | Simple Definition |
|---|---|
| Performance tuning | Making a database run faster. |
| EXPLAIN ANALYZE | A command that shows how PostgreSQL runs a query. |
| Query plan | The set of steps PostgreSQL takes to run a query. |
| Slow query | A query that takes a long time to run. |
| Index | A data structure that makes queries faster. |
| Vacuuming | Cleaning up old data in a database. |
| ANALYZE | Collecting statistics about data in a table. |
| Connection pooling | Reusing database connections. |
| Monitoring | Watching a database to see how it is doing. |
| pg_stat_statements | A PostgreSQL extension that tracks query times. |
| Partitioning | Splitting a large table into smaller tables. |
SLOW QUERY
|
V
USE EXPLAIN ANALYZE
|
V
FIND SLOW PARTS
|
V
ADD INDEXES / REWRITE QUERY
|
V
TEST AGAIN
|
V
FAST QUERY!
Step 1: Learn what performance tuning is. Step 2: Learn EXPLAIN ANALYZE. Step 3: Learn query plans. Step 4: Learn to find slow queries. Step 5: Learn to use indexes. Step 6: Learn vacuuming. Step 7: Learn ANALYZE. Step 8: Learn connection pooling. Step 9: Learn monitoring. Step 10: Learn pg_stat_statements. Step 11: Learn to optimize joins. Step 12: Learn to optimize subqueries. Step 13: Learn partitioning. Step 14: Learn best practices. Step 15: Put it all together.
[ EXPLAIN ANALYZE ] --> [ FIND SLOW QUERIES ]
| |
V V
[ ADD INDEXES ] --> [ VACUUM AND ANALYZE ]
| |
V V
[ CONNECTION POOLING ] --> [ MONITORING ]
| |
V V
[ OPTIMIZE JOINS ] --> [ PARTITION TABLES ]
| |
V V
[ FAST AND HEALTHY DATABASE! ]
| Step | What It Means |
|---|---|
| Seq Scan | Searching every row in the table |
| Index Scan | Using an index to find rows |
| Bitmap Heap Scan | Using an index to find rows, then reading the table |
| Hash Join | Joining tables using a hash table |
| Merge Join | Joining tables by sorting and merging |
| Nested Loop | Joining tables by looping through rows |
| Sort | Sorting rows |
| Aggregate | Calculating totals or averages |
| Feature | Without Tuning | With Tuning |
|---|---|---|
| Query speed | Slow | Fast |
| Indexes | None or few | Many, well-chosen |
| Vacuuming | Rare | Regular |
| ANALYZE | Rare | Regular |
| Connection pooling | No | Yes |
| Monitoring | No | Yes |
| User experience | Frustrating | Happy |
In this module, you learned about performance tuning and optimization. You learned that performance tuning makes a database run faster. You learned about EXPLAIN ANALYZE. It shows how PostgreSQL runs a query. You learned about query plans. They show the steps PostgreSQL takes. You learned how to find slow queries.
You learned how to make queries faster with indexes. You learned about vacuuming. It cleans up old data. You learned about ANALYZE. It collects statistics. You learned about connection pooling. It reuses database connections. You learned about monitoring. It helps you find problems. You learned about pg_stat_statements. It tracks query times.
You learned how to optimize joins and subqueries. You learned about partitioning. It splits large tables into smaller ones. You learned best practices for performance tuning. You learned how to put it all together to make a fast and healthy database.
Now you are ready to move on to Module 5, where you will learn about security, backup, and replication. But before you go, make sure you understand the key takeaways below.
Match the word in Column A with the correct definition in Column B.
| Column A | Column B |
|---|---|
| 1. Performance tuning | A. A command that shows how PostgreSQL runs a query |
| 2. EXPLAIN ANALYZE | B. Cleaning up old data in a database |
| 3. Index | C. Making a database run faster |
| 4. Vacuuming | D. Reusing database connections |
| 5. ANALYZE | E. A data structure that makes queries faster |
| 6. Connection pooling | F. Collecting statistics about data in a table |
| 7. Partitioning | G. Splitting a large table into smaller tables |
Answers: 1-C, 2-A, 3-E, 4-B, 5-F, 6-D, 7-G
Title: Tune a Slow Query
Instructions: In groups of 3 or 4, create a table with many rows.
Write a slow query. Use EXPLAIN ANALYZE to find the problem.
Add an index. Test the query again. Present your results to the class.
Example:
Table: sales (id, item, price, sale_date)
Slow query: SELECT * FROM sales WHERE item = 'Rice';
EXPLAIN ANALYZE shows Seq Scan.
Add index: CREATE INDEX idx_sales_item ON sales (item);
Test again: Query uses Index Scan. Much faster!
Title: My Tuning Plan
Instructions: Write a short plan for tuning a database.
List at least 5 tuning techniques you will use. Explain why each one is important.
Example:
1. Use EXPLAIN ANALYZE to find slow queries.
2. Add indexes on columns I search often.
3. Vacuum the database regularly.
4. Run ANALYZE after big changes.
5. Use connection pooling to handle many users.
Title: Tune a Shop Database
Materials: Computer with PostgreSQL installed.
Steps:
Assignment: For one week, practice performance tuning. Keep a diary. Each day, write down:
At the end of the week, write a short report. Share it with your teacher or parent.
In Module 5, you will learn about security, backup, and replication. You will learn about:
Before you start Module 5, make sure you understand everything in this module. Practice using EXPLAIN ANALYZE. Create indexes. Vacuum and ANALYZE your database. Monitor your database. When you are ready, turn the page and continue your journey to becoming a Certified PostgreSQL Expert!
End of Module 4.