# How to Read SQL Server Execution Plans

Query chậm không nên được fix bằng cách đoán. Execution plan cho biết SQL Server thực sự định hoặc đã thực thi query như thế nào.

## Các operator thường gặp

### Index Seek

Tìm đúng vùng dữ liệu trong index.

### Index Scan

Đọc phần lớn hoặc toàn bộ index.

### Table Scan

Đọc toàn bộ heap hoặc table.

### Key Lookup

Sau khi tìm row qua nonclustered index, SQL Server quay lại clustered index để lấy columns còn thiếu.

### Nested Loops

Thường phù hợp khi một phía có ít rows.

### Hash Match

Thường hiệu quả với dataset lớn.

### Merge Join

Hiệu quả khi hai input đã có ordering phù hợp.

### Sort

Có thể tốn memory và CPU khi số lượng row lớn.

## Index Seek không phải lúc nào cũng tốt

Ví dụ:

“`text
Index Seek
↓
Key Lookup x 100,000
“`

Có thể tệ hơn một scan đơn giản vì lookup bị lặp quá nhiều lần.

## Estimated vs Actual Execution Plan

Estimated Plan:

“`text
Optimizer dự đoán
“`

Actual Plan:

“`text
Query thực sự đã chạy
“`

Một dấu hiệu đáng chú ý:

“`text
Estimated Rows: 100
Actual Rows: 500,000
“`

Chênh lệch lớn có thể khiến optimizer chọn join strategy hoặc memory grant không phù hợp.

## Checklist khi đọc plan

– Scan trên bảng lớn?
– Key Lookup quá nhiều?
– Sort lớn?
– Estimated Rows lệch Actual Rows?
– Join strategy phù hợp?
– Predicate có sử dụng index?
– Có implicit conversion?
– Có missing index suggestion nào thực sự hợp lý?

## Interview questions

### Is an Index Scan always bad?

> No. A scan can be optimal when a query needs a large percentage of the table. The goal is to understand why the optimizer chose it, not to eliminate scans blindly.

### What do you check first?

> I look at actual row counts, expensive operators, scans on large objects, repeated lookups, sort operations, join strategy, and estimated-versus-actual cardinality.

## Key takeaways

Execution plan là công cụ để validate hypothesis, không phải nơi chỉ nhìn “operator nào đỏ nhất”.

**Next:** Part 6 — Practical Query Optimization