r/Database • • 10d ago

At what point does database indexing become counterproductive?

I've always thought of indexes as one of the first things to consider when improving query performance. But adding more indexes isn't always a good thing, especially when tables have frequent INSERT, UPDATE, and DELETE operations.

I'm curious how people decide which indexes are actually worth keeping.

Have you ever removed an index and noticed an improvement in overall database performance? Or found that an index was doing more harm than good?

Would be interesting to hear some real-world experiences.

95 Upvotes

40 comments sorted by

67

u/elephant_ua 10d ago

at previous workplace I saw our reports are awfully slow (which was not that big of a deal, but still - one minute, even 2 minutes) and after looking at code decided to add an index to our main table because I saw it using many joins that isn't directly referenced by indexes. After like 20 minutes of creating the index the report run for .... the same as before.

I decided to sit through with that god awful (as in complex and hard to grasp) execution plan - nothing there. Like, everywhere just small index seeks and has joins. Scrolled back and force, found a visual tool and finally i found the culprit - 99% of time was taken by the XML column operations

26

u/mattk404 10d ago

I was waiting for it... was satisfied.

2

u/briggsgate 10d ago

What do the operations do in production? I haven't dabbled in databases apart from index and and the usual stuff

2

u/brainiac256 9d ago

Extracting a single value from an XML document column and operating on it -- probably something in the XML column that should have been a column on its own so that that value could be indexed properly, maybe just checking for the existence of an XML element, maybe actually joining against the value, etc.

0

u/Fluid-Watercress1598 10d ago

What was the tool you used?

1

u/EatRunCodeSleep 6d ago

Any DB client has explain plan.

11

u/GreyHairedDWGuy 10d ago

Indexes are used to improve seek time for both reads and updates. Which ones to add are very application / access pattern specific. It’s hard to give you advice here for that reason. I use to
Work as an Oracle DBA from version 6 to version 10 then switched to SQL server and now Snowflake. In my Oracle days, you had to know the internals fairly well and how different index types helped/hurt.

I’d say using query plans along with some black arts and experience are what is needed….plus sometimes trial and error. Also note that some dbms solutions provide optimizer hints that you can use to influence access behavior.

Good luck

1

u/MusicDangerous8586 10d ago

How do you like Snowflake vs SQL Server ? What do you think are the biggest gotchas in designing DBs on Snowflake ?

1

u/GreyHairedDWGuy 9d ago

I work almost exclusively in data analytics so Snowflake aligns best with that. Performance is never an issue (ETL or end user queries). Less tweaking the database (indexing for example). However, SQL Server is a general purpose DBMS. Snowflake is not idea for building transactional solutions (although they have worked to make that possible).

There aren't many issues with designing for Snowflake. However, you have to be aware of using 'merge' statements instead of separate insert/update/delete statements and like I mentioned, it isn't good at making lots of small updates. Sorry I'm oversimplifying this a bit.

6

u/sazzer 10d ago

You measure it.

You should know what your data access patterns are - read and write. So you can take a production-sized clone, explain/execute appropriate queries and measure them. You can then adjust the indexes, explain/execute and measure again and see what the changes are.

Note though, unless you have a very high throughput then you likely won't notice any performance degradation until you've got tens or hundreds of millions of rows in your tables.

6

u/downshiftdata 10d ago

Adding an index should be a last resort.

At best, it's a trade-off: You are paying for read performance with write performance. But other factors also come into play. Could the query be rewritten to make better use of existing indexes? Could it be rewritten to address a SARGability issue? Is there an anti-semi-join with a sub-query? Could you cache the results in the application layer and just not call the SQL as often? This is just a sampling of options to consider before slapping on another index.

5

u/Jamie_1318 10d ago

Depends on the workload. I would say it's pretty common for reads to completely dwarf writes.

2

u/LaminatedMisanthropy 10d ago

Depends on the situation but indexes can be deleted before writing then recreated after the write.

1

u/EatRunCodeSleep 6d ago

If you write in batches, at regular times, maybe. If you have random writes during the entire day ... Good luck with that! 😂

1

u/YoghurtFlan 9d ago

At risk of being a dumbass web developer but echoing the 'depends' comments I think most people are going to buy that trade-off on indexes because the cost of getting into the weeds with arcane SQL is going to be far worse than the additional cost of write operations.

I think you're going to be getting into rather esoteric use-cases, or extreme scalability (that many people won't see in their usual tech job outside of FAANG and the like), for any other decision to apply and, even then, I suspect it's going to be a bad schema design that forces your hand rather than any trade-off on latency. And at that point, exactly as you say, people are going to look for solutions outside of the DB like caching, or even using other data stores (especially for stuff that is unavoidably write-heavy).

7

u/Discordbothost 10d ago

a UNIQUE index can have few query reads while still enforcing a business rule by rejecting duplicates. keep constraint enforcement separate from the performance decision. which database are you using?

2

u/TonyTheJet 10d ago

I have only had one situation in which removing an index helped the database performance, and it was for a table that kept a hash of the state of users' Cloud library, so it was getting slammed with write operations as users created folders, added files, etc., which would change their library's hash.

But the performance boost came from removing a foreign key constraint, which had a side effect of removing an index--it wasn't the index itself that was as problematic as the constraint check.

2

u/Khmerrr 10d ago

You start to do real index maintenance when you realize how much blocking, I/O, RAM, backup time, ecc your system consume maintaining indexes. The general rule is the hand rule: max five indexes with max five columns for a given table. It is intended to be a red flag rule: if your table have a lot of big indexes (more than 5) you should start thinking on how to reduce the number and/or the size. Generally speaking we do periodic performance reviews with query store and the blocked process events and the indexes DMV to find the tables where we can aggregate, add or drop indexes.

2

u/itemluminouswadison 10d ago

AI slop post ?

3

u/Frosty_Bumblebee4622 9d ago

Can't wait to see an AI slop on LinkedIn saying how "Sometimes indexing your databases more is counterproductive, here's what most companies get wrong"

1

u/Hour_Interest_5488 10d ago

Just like some answers. Not so AI though.

1

u/FishIndividual2208 9d ago

Human slop reply?

2

u/itemluminouswadison 9d ago

Looks AI to me. Perfect grammar, low hanging fruit ez to Google, question to start a conversation at the end. Like 80% of reddit posts in the last few months. Zero to minimal response from the OP

1

u/FishIndividual2208 9d ago

Oh nooo, someone is trying to start a conversation 😲

1

u/itemluminouswadison 9d ago

Honey eat your slop

1

u/mooglinux 10d ago

It becomes counterproductive when profiling shows a negative impact, or the memory/disk consumption is too much.

1

u/Any-Signature9672 10d ago

Indexes become counterproductive when they're rarely used but still have to be maintained on every write. I've seen removing unused indexes improve overall performance more than adding new ones

1

u/spez_eats_nazi_ass 10d ago

It’s always a balancing act w the write side of the house. 

1

u/Informal_Athlete1010 10d ago

Number indexes >= number columns.

1

u/alexwh68 10d ago

The basic rule where I used to work was no indexes other than primary keys on tables with less than a 1000 rows, then evaluate if an index is necessary and then what type, single column, multiple column, covering index.

But databases change, the dynamics change going from 5,000 rows to 5,000,000 rows, so period review of indexes is needed on bigger databases.

1

u/Decompiled_dev 10d ago

I try to keep indexes to a minimum, and turn on slow query log to catch queries that might need one.

Basically an index will always decrease DB performance on write, but might improve performance on reads.

1

u/rosstafarien 10d ago

Normalize until it hurts, denormalize until it performs. From there, add an index when it prevents an essential function from a table scan, but check to make sure it works.

1

u/GrayLiterature 10d ago

Heavy write workloads

1

u/mint_bolt_feel 10d ago

I dropped a covering index yesterday that was killing our write throughput. The read speedup was negligible because the optimizer kept choosing a nested loop with a table scan anyway. Stop adding indexes to fix bad SQL

1

u/cwjinc 9d ago

The objective shouldn't be deciding which indexes are worth keeping, it should be which indexes are worth creating in the first place.
OTOH, the database I work on is very heavily indexed and there is no indication that is slowing anything down.
So first investigate whether you need to change anything at all.

1

u/navicat-gu 9d ago

An index becomes counterproductive when what it costs on every write (and in memory) is more than what it saves on reads. In practice it shows up in a few ways:

  • Write-heavy tables. Every INSERT, and every UPDATE that touches an indexed column, updates every index. Ten indexes on a hot queue or event table can easily cost more than they save.
  • Redundant indexes. An index on (a) is usually redundant if you already have (a, b). These pile up over the years.
  • Unused indexes. They're pure cost. They slow writes, bloat backups and push useful pages out of the buffer cache.
  • Low-selectivity indexes. An index on a boolean or status column with three values is often ignored by the planner anyway, unless it's a partial/filtered index on the rare value.

How to decide which to keep, using real data instead of gut feel:

  • PostgreSQL: pg_stat_user_indexes (look at idx_scan = 0 since the last stats reset) together with index size.
  • SQL Server: sys.dm_db_index_usage_stats: compare seeks/scans/lookups against user_updates.
  • MySQL 8: sys.schema_unused_indexes and sys.schema_redundant_indexes.

Then drop carefully. MySQL 8 has invisible indexes and SQL Server lets you disable one, so you can "turn it off" for a week before you actually drop it. And make sure the stats cover a full business cycle (month-end reports love the index nobody uses on other days).

Disclosure: I'm RC, Director of Digital Strategy @ Navicat. For checking whether a query actually uses an index before and after a change, the visual explain in Navicat 18 (paid editions) makes plans easier to compare. Navicat Premium Lite is free to try for everyday querying, and plain EXPLAIN works too.

1

u/sallamx99 9d ago

Too many indexes on a single table means more index maintenance because of write operation. Some stats could run stale too. I ran into cases where the query planner just uses different for the same query and index hints improved performance.

I tend to keep indexes minimal and cover as much queries as possible.

1

u/4bitben 8d ago

Write overhead can be an issue. Covering indexes need more vacuuming. Other additional overhead. Just some examples 

1

u/Achsin 10d ago

Indexes are definitely one of the first things you should consider with regard to query performance, but not for the idea of adding a new one. Instead you should look at the query and see if there are any changes that can be made to it that will allow the existing indexes to be better utilized. If there just aren’t any indexes on the table (or tables) that’s another problem, but it is a lot better in the end to adjust the query to fit the indexes than to adjust the indexes to fit the query if possible.