SQL Server Optimization Guide
SQL Server Optimization Guide
1. TEMPORARY TABLES
------------------
WHEN TO USE:
- Large result sets that will be referenced multiple times
- Complex calculations that need staging
- Breaking down complex queries into manageable steps
- When you need to reference intermediate results multiple times
- Data that needs multiple transformations
BENEFITS:
- Reduces repeated calculations
- Improves query readability
- Better performance than table variables for larger datasets (>1000 rows)
- Statistics are available for query optimizer
- Can be indexed for better performance
BEST PRACTICES:
- Create indexes AFTER data load
- Only create necessary indexes
- Drop temp tables when no longer needed
- Use proper data types and sizes
- Consider using table variables for very small datasets (<1000 rows)
2. INDEXING STRATEGY
-------------------
TYPES OF INDEXES:
a) Clustered Index
• One per table
• Defines physical order of data
• Best for columns that:
- Are unique or have high selectivity
- Are accessed sequentially
- Are used in range queries
- Are used frequently in ORDER BY or GROUP BY
b) Non-Clustered Index
• Multiple per table
• Creates separate structure with pointers
• Best for columns that:
- Are frequently used in WHERE clauses
- Are used in JOIN conditions
- Have good selectivity
- Are used in foreign key relationships
EXAMPLE PATTERN:
CREATE TABLE #TempTable (Col1 INT, Col2 VARCHAR(50))
INSERT INTO #TempTable
SELECT Col1, Col2 FROM SourceTable
-- Create index after data load
CREATE INDEX IX_TempTable_Col1 ON #TempTable(Col1)
4. PERFORMANCE CONSIDERATIONS
---------------------------
MONITORING:
- Use sys.dm_db_index_usage_stats to track index usage
- Monitor index fragmentation
- Watch for unused indexes
- Check execution plans for index usage
MAINTENANCE:
- Regularly rebuild/reorganize fragmented indexes
- Remove unused indexes
- Update statistics when necessary
- Monitor index size and impact on storage
5. COMMON PITFALLS
-----------------
- Creating too many indexes
- Not considering the maintenance overhead
- Creating redundant indexes
- Not accounting for update/insert performance impact
- Over-indexing small tables
- Under-indexing large tables
- Not considering the proper column order in composite indexes
6. OPTIMIZATION TIPS
------------------
- Always check execution plans
- Consider filtered indexes for specific queries
- Use included columns instead of covering indexes when possible
- Monitor missing index suggestions
- Consider columnstore indexes for data warehouse scenarios
- Use proper statistics maintenance
- Consider partitioning for very large tables