Composite Index คืออะไร?
- Index ที่ใช้บน multiple columns
- รู้จักว่า multiple-column index
- MySQL สร้าง composite index ได้สูงสุด 16 columns
- Query optimizer ใช้ composite indexes สำหรับ queries ที่ test all columns ใน index
- ใช้ได้กับ queries ที่ test first columns, first two columns, etc.
- ถ้า columns เรียงลำดับถูกต้องใน index definition composite index เดียวเร่งได้หลาย queries บน table เดียวกัน
สร้าง Composite Index ตอน Create Table
CREATE TABLE table_name (
c1 data_type PRIMARY KEY,
c2 data_type,
c3 data_type,
c4 data_type,
INDEX index_name (c2,c3,c4)
);
Composite index ประกอบด้วย 3 columns: c2, c3, c4
เพิ่ม Composite Index ใน Existing Table
CREATE INDEX index_name ON table_name(c2,c3,c4);
ทำให้ Slow Queries เร็วด้วย Composite Index
- Query execution speed ขึ้นกับ duration
- Index hints เพิ่ม query speed
- MySQL optimizer เลือก index ให้ถูกต้อง (static queries เท่านั้น)
- หาก WHERE clause เปลี่ยนบ่อย performance จะแย่ลง (optimizer ทำงานไม่ได้)
- 'FORCE INDEX' เหมือน 'USE INDEX' แต่ table scan ถือว่า expensive
- Table scan จำเป็นตอนไม่มี named index หา rows ได้