Skip to content
Chasale logo Chasale logo Chasale

Made for Your Everyday Style.

Chasale logo Chasale logo Chasale

Made for Your Everyday Style.

  • Home
  • Blog
  • Business
    • Finance
  • Lifestyle
    • Culture
    • Food
    • Inspiration
  • Entertainment
    • Music
  • Technology
  • Travel

Recent Posts

  • Mera Naam Kya
    Mera Naam Kya Hai? Phone Galat Naam Bole To 2026 Mein Aise Theek Karein
    by Chasale
    November 21, 2026
  • What Is the Meaning of Life
    What Is the Meaning of Life? What Science, Philosophy and the Number 42 Actually Tell Us
    by Chasale
    November 21, 2026
  • North Sentinel Island
    North Sentinel Island: Who Lives There, Why It’s Off-Limits, and What Changed in 2025-26
    by Chasale
    November 21, 2026
  • Journaling Techniques
    9 Journaling Techniques That Actually Work (With Steps, Examples and When to Skip Them)
    by Chasale
    November 21, 2026
  • Home
  • Blog
  • Business
    • Finance
  • Lifestyle
    • Culture
    • Food
    • Inspiration
  • Entertainment
    • Music
  • Technology
  • Travel
Close

Search

database optimization
Technology

Database Optimization: Find the Bottleneck Before You Fix It

By Chasale
November 21, 2026 11 Min Read
0

Quick Answer: Database optimization is the process of making queries return faster while using less CPU, memory and disk. Measure first: find the queries that use the most total time, read their execution plans, then fix the cause, usually a missing index, an N+1 query pattern or deep OFFSET pagination. In our 1-million-row PostgreSQL test, one composite index cut a query from about 30 ms to 0.15 ms.

Most slow apps don’t need a bigger server. They need someone to find the few queries doing most of the damage and fix those first. That is what database optimization looks like in practice, and it’s why this guide starts with diagnosis instead of a list of 11 tricks. Most database optimization articles hand you techniques without telling you which one your problem actually needs.

At Chasale, we ran every test in this guide on a real PostgreSQL 16 database with 1 million orders, so you’ll see measured numbers, the exact queries, and the trade-offs that usually get skipped.

Is It the Database or the App? A 10-Minute Check

Before touching a single index, confirm the database is really the slow part. Open your APM tool or request logs and compare total request time with time spent in queries. If a 2-second page spends 150 ms in the database, no index will save you; the problem is in the code, an external API, or the frontend.

If the database does own most of the time, find out which queries. In PostgreSQL, enable the pg_stat_statements extension and run:

-- PostgreSQL 13+
SELECT query, calls,
       round(total_exec_time) AS total_ms,
       round(mean_exec_time, 2) AS avg_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

In MySQL, turn on the slow query log (slow_query_log = ON, long_query_time = 1) or check performance_schema.events_statements_summary_by_digest, sorted by SUM_TIMER_WAIT.

Rank by total time, not by the slowest single run. A 5 ms lookup that runs 2 million times a day burns 10,000 seconds (about 2.8 hours) of database time. A 2-second monthly report barely registers. The quick lookup is your real target, even though it never shows up as “slow”.

Match the Symptom to the Cause

Your monitoring dashboard already tells you where to look. Use this table to go from what you see to the first fix worth trying.

What you see Likely cause Check first First fix to try
CPU pinned near 100% Unindexed filters, N+1 query loops Top queries by total time Add the missing index, batch the loop into one query
High disk I/O wait Full table scans, memory buffer too small for the hot data Seq Scan nodes in plans, cache hit ratio Index the filter columns, raise shared_buffers or innodb_buffer_pool_size
Queries fast alone, slow under load Lock waits, long transactions pg_locks or performance_schema.data_locks Shorten transactions, update rows in a consistent order
“Too many connections” errors No connection pooling, leaked connections Active vs idle connection count Add a pooler such as PgBouncer or HikariCP
Reads fast, writes slow Too many indexes, row-by-row inserts Index count per table Drop unused indexes, use multi-row inserts or COPY
Page 1 loads fast, page 500 crawls OFFSET pagination Plans for deep pages Switch to keyset pagination

How to Read an Execution Plan (Our 1-Million-Row Test)

An execution plan shows how the database actually runs your query. You don’t need to be a DBA to read one; you only need to spot a few warning signs.

Our setup: PostgreSQL 16.15 on Ubuntu 24.04, 2 vCPUs, 7 GB RAM. An orders table with 1,000,000 rows and a customers table with 50,000 rows. We ran each query several times and report warm-cache results.

The query is one every online store runs: show a customer’s 20 most recent orders.

-- PostgreSQL
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total, created_at
FROM orders
WHERE customer_id = 4217
ORDER BY created_at DESC
LIMIT 20;

Before the index, the plan showed a Parallel Seq Scan on orders feeding a Sort. PostgreSQL read all 1 million rows to find about 20. Execution time: 29 to 31 ms (71 ms on the first, cold run).

Then we added one composite index:

CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

After the index, the plan switched to Index Scan using idx_orders_customer_created, with no Sort step at all. Execution time: 0.15 to 0.17 ms, roughly 190 times faster.

When you read any plan, check these four things:

  • Scan type: Seq Scan on a large table with a selective filter is the classic red flag.
  • Estimated vs actual rows: a big gap means stale statistics. Run ANALYZE.
  • Sort and Hash nodes: an index in the right order can remove a Sort entirely, as it did here.
  • Buffers: high read counts mean the data came from disk, not memory.

Thirty milliseconds sounds harmless. On a page that loads order history for thousands of customers an hour, it adds up to real CPU and a real hosting bill.

Indexing That Helps, and Indexing That Hurts

The index from our test worked because its column order matched the query. The rule: equality filters first, then the range or sort column. (customer_id, created_at) serves WHERE customer_id = ? ORDER BY created_at. Flip the order and the same index is far less useful.

Indexes are not free, and our test showed the bill clearly:

  • Storage: the index took 30 MB on a 64 MB table, almost half the table’s size.
  • Write speed: inserting 200,000 rows took 372 ms into a table with no indexes and 2,311 ms into the same table with a primary key plus three secondary indexes. That’s about 6 times slower, because every insert updates every index.

So audit before you add. In PostgreSQL, this finds indexes nobody uses:

-- PostgreSQL: indexes never scanned since stats were reset
SELECT relname AS table_name, indexrelname AS index_name,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;

Check that stats have run through a full business cycle (month-end reports included) before dropping anything.

One production warning most guides skip: a plain CREATE INDEX blocks writes to the table while it builds. On a busy table, use CREATE INDEX CONCURRENTLY in PostgreSQL, or ALGORITHM=INPLACE, LOCK=NONE with InnoDB in MySQL. It takes longer, but your checkout page keeps working.

Application Fixes Most Guides Skip

A lot of database pain is created in application code. These three patterns showed up clearly in our tests.

The N+1 query problem

Your code loads 100 orders, then loops and runs one more query per order to fetch the customer name. That’s 101 queries for one screen. ORMs make this easy to do by accident.

In our test, the N+1 version took 9.2 ms and a single JOIN took 1.1 ms. That gap was measured on the same machine with zero network delay. In production, every query also pays a network round trip, so at around 1 ms per trip the N+1 version adds roughly 100 ms more per page load.

The fix is usually one line in your ORM: select_related() or prefetch_related() in Django, includes in Rails, with() in Laravel.

Deep OFFSET pagination

LIMIT 20 OFFSET 900000 forces the database to walk past 900,000 rows and throw them away. Keyset pagination remembers where the last page ended:

-- Slow: 71.4 ms in our test
SELECT id, total FROM orders ORDER BY id LIMIT 20 OFFSET 900000;

-- Fast: 0.4 ms in our test
SELECT id, total FROM orders WHERE id > 900000 ORDER BY id LIMIT 20;

The trade-off: keyset pagination can’t jump straight to page 4,317. For infinite scroll and “next page” buttons, that rarely matters.

Row-by-row writes and SELECT *

Inserting 10,000 rows with 10,000 separate statements means 10,000 round trips. Use multi-row INSERT ... VALUES (...), (...) or COPY in PostgreSQL. And fetch only the columns you need; SELECT * drags large text and JSON columns across the network for nothing.

Outdated Database Optimization Advice Still Ranking in 2026

Some tips in popular guides were written for database versions that are now retired. Following them today wastes time or throws errors.

Old advice What actually happens now Do this instead
“Turn on the MySQL query cache with query_cache_size“ MySQL 8.0 removed the query cache, including its system variables such as query_cache_size (MySQL 8.0.3 release notes) Cache in your app with Redis or Memcached, and fix indexes
“Use PROCEDURE ANALYSE() to size your columns” In MySQL 8.0 the clause is a syntax error (MySQL worklog WL#4745) Query information_schema or profile real data
“Use static, fixed-length tables” This came from MyISAM’s fixed row format. InnoDB, MySQL’s default engine since 5.5, stores rows differently Pick the right data types; don’t pad columns
“Use an ORM to optimize queries” ORMs improve maintainability, but they often cause N+1 loops Use an ORM, and watch its generated SQL
“Just add more RAM” Helps only if the hot data doesn’t fit in memory now Check the cache hit ratio first

The MySQL team explained why the query cache went away: it had serious scalability problems and could become a severe bottleneck. A tip that once helped became a liability as servers got more cores.

Caching, Pooling and Read Replicas: When Each Makes Sense

These three tools solve different problems. Using the wrong one adds complexity without speed.

Tool Use it when Skip it when Watch out for
App cache (Redis, Memcached) The same expensive result is read many times and can be a few seconds stale Data changes on almost every read Invalidation: stale prices or stock counts cost real money
Connection pooler (PgBouncer, HikariCP) You see connection errors or hundreds of short-lived connections A small app with a handful of steady connections Transaction-mode pooling breaks some session features, such as session-level prepared statements
Read replica Reads far outnumber writes and the primary’s CPU is the limit Writes are the bottleneck; replicas don’t help writes Replication lag: a user saves a form, then reads an old copy

A simple order of operations works for most teams: fix queries and indexes first, add pooling when connections become the problem, add caching for hot read paths, and add replicas last. Each step is harder to undo than the one before.

What Changed in 2025 and 2026

Two version changes affect how you tune a database today.

PostgreSQL 18 added asynchronous I/O. Released in September 2025, it lets PostgreSQL send several read requests at once instead of waiting on each one. The project reports up to 3 times faster reads from storage. The catch: it currently covers sequential scans, bitmap heap scans and VACUUM, while writes stay synchronous. So it speeds up big scans and maintenance, but it won’t fix a missing index or slow inserts. Our tests ran on PostgreSQL 16, so scan-heavy numbers would likely look better on 18.

MySQL 8.0 reached end of life in April 2026. Oracle’s release notes say 8.0.46 was the final release and recommend moving to MySQL 8.4 LTS. An unsupported version gets no security or bug fixes, so upgrading is now part of tuning, not a separate project. Test your queries on 8.4 first, since optimizer changes can shift plans.

PostgreSQL is also where most developers are heading. Stack Overflow’s 2025 survey ranks it the most desired and most admired database since 2023, which is why the examples here use PostgreSQL first and MySQL second.

The Business Cost of a Slow Database

When an app slows down, the easy answer is a bigger cloud instance. On AWS RDS, Azure or Google Cloud SQL, each step up in instance size typically doubles vCPUs, memory and the hourly price. If the real cause is one unindexed query, you pay double every month for a problem a single CREATE INDEX would have fixed.

For business owners: you don’t need to read SQL to ask the right questions. Ask your developer or IT partner:

  1. Which 10 queries use the most total database time?
  2. Did we check those queries before upgrading the server?
  3. When was our database version last upgraded, and is it still supported?
  4. Do we measure page speed before and after each change?

At Chasale, we like guides that show the money side of tech decisions, and this is one of the clearest cases: an hour of query work can be worth more than a year of oversized hosting.

When not to optimize

Not every slow query deserves your time.

  • Small tables: on a few thousand rows, a sequential scan is often faster than an index lookup.
  • Rare queries: a monthly report that takes 8 seconds is fine if nobody waits on it.
  • Denormalizing too early: copying data into extra columns speeds reads but creates sync bugs. Do it only when measurements prove you need it.
  • No baseline: if you can’t measure before and after, you can’t tell whether a change helped or hurt.

A Repeatable Database Optimization Checklist

Run this loop whenever performance slips, or once a quarter as routine maintenance.

  1. Record a baseline: p95 page response time, CPU, and the top 10 queries by total time.
  2. Confirm the database is the bottleneck using APM or request logs.
  3. Pick the single worst query by total time, not by single-run duration.
  4. Run EXPLAIN ANALYZE and look for sequential scans, sorts and row-estimate gaps.
  5. Make one change: an index, a query rewrite, or an ORM fix.
  6. Test on staging with production-like data volume.
  7. Deploy safely: concurrent or online index builds, outside peak hours.
  8. Re-measure against the baseline. Keep the change only if the numbers improved.
  9. Write it down: what changed, why, and the before/after numbers.
  10. Repeat with the next query on the list.

Frequently Asked Questions

How do I know if my database or my application is slow?

Compare total request time with time spent in queries using an APM tool or request logs. If queries account for a small share, the bottleneck is in your code, an external API or the frontend.

How many indexes are too many?

There’s no fixed number. If writes are slowing down or pg_stat_user_indexes shows indexes with zero scans, you have too many. In our test, four indexes made bulk inserts about 6 times slower.

How often should I tune my database?

Review the top queries once a quarter, and again after any big release or traffic jump. Data growth alone can turn a fine query into a slow one.

Does adding more RAM make a database faster?

Only when your frequently used data doesn’t fit in memory. If the cache hit ratio is already high, more RAM won’t help a query that is missing an index.

When does caching hurt performance?

When data changes often, cache invalidation adds work and risks serving stale data. Cache only results that are expensive to compute and safe to be slightly out of date.

Is optimizing a database the same as tuning it?

People use the terms loosely. Tuning usually means server settings such as memory buffers. Optimizing is broader and includes queries, indexes, schema and application code.

Next step: run the top-10 query check from this guide on your own database this week. Want more practical, tested guides like this one? Learn what Chasale is and what we cover.

Disclaimer: Test results come from our own environment and will differ on your hardware, data and settings. Always test changes on a staging copy and keep a current backup before changing production. The machines that connect to your database need protection too, so follow basic computer virus prevention habits across your team.

Author

Chasale

Aarav Kumar is an experienced content writer specializing in Business, Finance, and Lifestyle journalism.

Follow Me
Other Articles
Investment in mutual funds concept with a coin jar, a growing plant and rising coin stacks
Previous

Investment in Mutual Funds: A Beginner’s Step-by-Step Guide for India (2026)

Journaling Techniques
Next

9 Journaling Techniques That Actually Work (With Steps, Examples and When to Skip Them)

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Hey, I'm Aarav Kumar. I'm a full-time blogger.
  • X
  • Instagram
  • Facebook
  • YouTube
Work Experience

Blogsy Media

Full-Time Blogger

2022-present

Bright Pen

Content Writer

2019-2021

Blog Nest Weekly

Guest Blogger

2017-2019

Available for Hire
Get In Touch

Recent Posts

  • Mera Naam Kya
    Mera Naam Kya Hai? Phone Galat Naam Bole To 2026 Mein Aise Theek Karein
    by Chasale
    November 21, 2026
  • Mera Naam Kya
    Mera Naam Kya Hai? Phone Galat Naam Bole To 2026 Mein Aise Theek Karein
  • What Is the Meaning of Life
    What Is the Meaning of Life? What Science, Philosophy and the Number 42 Actually Tell Us
  • North Sentinel Island
    North Sentinel Island: Who Lives There, Why It’s Off-Limits, and What Changed in 2025-26
  • Journaling Techniques
    9 Journaling Techniques That Actually Work (With Steps, Examples and When to Skip Them)
  • database optimization
    Database Optimization: Find the Bottleneck Before You Fix It
  • Investment in mutual funds concept with a coin jar, a growing plant and rising coin stacks
    Investment in Mutual Funds: A Beginner’s Step-by-Step Guide for India (2026)
  • Tripura University Question Paper 2018 PDF
    Tripura University Question Paper 2018 PDF: What’s Available and How to Find Your Paper

Search...

Technologies

Figma

Collaborate and design interfaces in real-time.

Notion

Organize, track, and collaborate on projects easily.

DaVinci Resolve 20

Professional video and graphic editing tool.

Illustrator

Create precise vector graphics and illustrations.

Photoshop

Professional image and graphic editing tool.

Chasale logo

Chasale brings you clear, fact-checked updates on news, finance, tech, jobs, health, and celebrity trends, plus simple step-by-step guides for everyday needs.

  • Facebook
  • X
  • Instagram
  • LinkedIn

Latest Posts

  • Winter Break Screen Time: Do Smart Watches for Kids with Games Make It Better or Worse?
    Winter break is here, schools are closed for a couple… Read more: Winter Break Screen Time: Do Smart Watches for Kids with Games Make It Better or Worse?
  • What Is the Meaning of Life? What Science, Philosophy and the Number 42 Actually Tell Us
    Quick Answer: There is no single proven meaning of life.… Read more: What Is the Meaning of Life? What Science, Philosophy and the Number 42 Actually Tell Us
  • What Is the Indian Legend Regarding the Discovery of Tea? The Bodhidharma Story, Explained
    What Is the Indian Legend Regarding the Discovery of Tea?… Read more: What Is the Indian Legend Regarding the Discovery of Tea? The Bodhidharma Story, Explained

Pages

  • About Us
  • Contact
  • Terms and conditions

Contact

Phone

Email

Location

New York, USA

Copyright 2026 — Chasale. All rights reserved.