Query Optimization มีความสำคัญมากสำหรับ Performance ของ Relational Database โดยเฉพาะสำหรับการ Execute Complex SQL Statements Query Optimizer ตัดสินใจ Best Methods สำหรับ Implement แต่ละ Query
Query Optimizer เลือก เช่น ว่าจะใช้ Indexes สำหรับ Query ที่กำหนดหรือไม่ และจะใช้ Join Methods ไหนเมื่อ Join Multiple Tables คำตัดสินใจเหล่านี้มี Effect ทREMENDOUS ต่อ SQL Performance และ Query Optimization เป็น Key Technology สำหรับทุก Application จาก Operational Systems ถึง Data Warehouse และ Analytical Systems ถึง Content Management Systems
หลักการหลักของ Query Optimization
- เข้าใจว่า Database กำลัง Execute Query อย่างไร: Phase แรกของ Query Optimization คือ เข้าใจว่า Database กำลังทำอะไร Databases ต่างๆ มี Commands ต่างๆ สำหรับนี้ ตัวอย่าง: MySQL ใช้ "EXPLAIN [SQL Query]" Keyword ดู Query Plan Oracle ใช้ "EXPLAIN PLAN FOR [SQL Query]" ดู Query Plan
- Retrieve ข้อมูลน้อยที่สุดเท่าที่จะเป็นไปได้: ยิ่งมาก Information Retrieved จาก Query ยิ่งมาก Resources ที่ Database ต้อง Expand เพื่อ Process และ Save Records ตัวอย่าง: ถ้าต้องการแค่ One Column จาก Table อย่าใช้ 'SELECT *'
- Store Intermediate Results (เก็บผลลัพธ์ระหว่างทาง): Logic สำหรับ Query บางครั้ง Complex มาก สามารถ Produce Desired Outcomes ผ่าน Subqueries, Inline Views, UNION-type Statements สำหรับ Methods นี้ Intermediate Results ไม่ Stored ใน Database แต่ Directly Used ภายใน Query นี่อาจนำไปสู่ Performance Issues โดยเฉพาะเมื่อ Intermediate Results มี Rows จำนวนมาก
Query Optimization Strategies (กลยุทธ์เพิ่มประสิทธิภาพคิวรี่)
- Use Index: ใช้ Index เป็น Strategy แรกที่ควรใช้ Speed Up Query
- Aggregate Table: ใช้ Pre-populate Tables ที่ Higher Levels ว่า Less Data ต้อง Parsed
- Vertical Partitioning: Partition Table โดย Columns Method นี้ลด Amount ของ Information ที่ SQL Query ต้อง Process
- Horizontal Partitioning: Partition Table โดย Data Value มักเป็น Time Method นี้ลด Amount ของ Information ที่ SQL Query ต้อง Process
- De-normalization: กระบวนการ De-normalization รวม Multiple Tables เป็น Single Table Speed Up Query Execution เพราะ Fewer Table Joins Required
- Server Tuning: แต่ละ Server มี Parameters ของตัวเอง และ Provides Tuning Server Parameters ให้ Take Full Advantage ของ Hardware Resources ที่สามารถ Speed Up Query Execution อย่างมีนัยสำคัญ