What are some DOs and DONTs for improving database performance using index?
A DO would be a case in which an index should be created, or another indexes related tip that will improve performance.
A DONT will be a case when an index shouldn't be created, or another index related action that can hurt the performance.
Indexes should not be used on small tables. Indexes should not be used on columns that return a high percentage of data rows when used as a filter condition in a query's WHERE clause. For instance, you would not have an entry for the word "the" or "and" in the index of a book.
The downside to adding indexes to a table is that they affect the performance of writes. Moreover, improperly created indexes can even adversely affect SELECT queries! Any table configuration where performance suffers due to excessive, improper, or missing indexes is considered to be poor indexing.
Yes, it does. However, if you have foreign key constraints such as RESTRICT that ensure referential integrity with other tables, you'll want to drop those keys prior to dropping or truncating a table.
Generally speaking:
Each index makes writes slower...
-- index on foo (bar)
select bar from foo where bar = :bar;
By the same token it'll be used in foreign key references (on both tables).
-- index on foo (bar) if baz (bar) is frequently updated/deleted.
create table foo (bar references baz (bar));
-- index on foo (bar)
select bar from foo order by bar limit 10;
In this case put the where conditions first, and the sort key last:
-- index on foo (baz, bar)
select bar from foo where baz between :baz1 and :baz2 group by bar;
If the table stats are garbage, there is little chances that the optimizer will use your indexes. Manually vacuum/analyze your database if needed.
Past a certain threshold of rows retrieved, it'll be faster to do a full table scan. If your index is on a boolean field that more or less splits your table in two, it'll never be used.
Likewise, if your data is stored in such a way that the index scan will likely end up randomly accessing nearly ever applicable disk page for that table, the planner will prefer a full table scan.
If you've a field that has the same value except for 10% of your rows, consider a partial index on it (i.e. where not that value). This results in a much smaller index without hindering its actual usefulness.
If you're constantly querying against an expression applied to your column and you platform offers expression indexes, consider adding an index on it. When used, the expression won't get evaluated for each row.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With