Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

indexing - What are the biggest benefits of using INDEXES in mysql?

I know I need to have a primary key set, and to set anything that should be unique as a unique key, but what is an INDEX and how do I use them?

What are the benefits? Pros & Cons? I notice I can either use them or not, when should I?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short answer:
Indexes speed up SELECT's and slow down INSERT's.

Usually it's better to have indexes, because they speed up select more than they slow down insert.

On an UPDATE the index can speed things way up if an indexed field is used in the WHERE clause and slow things down if you update one of the indexed fields.

How do you know when to use an index

Add EXPLAIN in front of your SELECT statement.
Like so:

EXPLAIN SELECT * FROM table1 
WHERE unindexfield1 > unindexedfield2 
ORDER BY unindexedfield3

Will show you how much work MySQL will have to do on each of the unindexed fields.
Using that info you can decide if it is worthwhile to add indexes or not.

Explain can also tell you if it is better to drop and index

EXPLAIN SELECT * FROM table1 
WHERE indexedfield1 > indexedfield2 
ORDER BY indexedfield3

If very little rows are selected, or MySQL decided to ignore the index (it does that from time to time) then you might as well drop the index, because it is slowing down your inserts but not speeding up your select's.

Then again it might also be that your select statement is not clever enough.
(Sorry for the complexity in the answer, I was trying to keep it simple, but failed).

Link:
MySQL indexes - what are the best practices?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...