A comprehensive collection of production-grade SQL Server scripts for database administration, performance tuning, and troubleshooting.
Administrative tasks for managing SQL Server instances and databases.
user_management.sql- Create and manage SQL Server logins, database users, and permission managementdatabase_backup.sql- Full and differential database backups with integrity verificationpermission_audit.sql- Comprehensive audit of user permissions and role membership across the serverdatabase_mail_setup.sql- Configure Database Mail for alerts and notificationsmaintenance_jobs_setup.sql- Create and manage scheduled maintenance jobs (backups, index rebuilds, stats)
Query optimization and index management for maintaining database performance.
missing_indexes.sql- Identify missing indexes from query execution history; generate CREATE INDEX statementsindex_fragmentation.sql- Analyze, reorganize, and rebuild fragmented indexestable_statistics.sql- Update table statistics to maintain query optimizer effectiveness
Diagnostic scripts for investigating database issues and anomalies.
diagnose_blocking_queries.sql- Identify blocking sessions and their executing commands in real-timecheck_database_health.sql- Run DBCC integrity checks and validate database consistencytempdb_usage.sql- Monitor tempdb space consumption and identify heavy usersdisk_space_usage.sql- Track data/log file sizes and alert on capacity issues
High availability and disaster recovery configuration and monitoring.
always_on_availability_groups.sql- Configure and monitor Always On Availability Groupslog_shipping_setup.sql- Setup and monitor log shipping for disaster recoverydatabase_mirroring_setup.sql- Configure database mirroring (note: deprecated in SQL 2012+)replication_setup.sql- Setup and monitor SQL Server replicationfailover_cluster_instance.sql- Configure and monitor failover clusteringlinked_servers.sql- Create and manage linked server connections
Real-time and trend-based monitoring for performance analysis and capacity planning.
performance_counters.sql- Monitor SQL Server performance counters (CPU, memory, I/O, cache hit ratio)growth_rate_analysis.sql- Analyze database growth trends and forecast future capacity needsburn_rate_analysis.sql- Monitor resource consumption rates (memory, disk, log, CPU)
Reusable helper functions and utility scripts used by other scripts.
get_server_info.sql- Collect comprehensive SQL Server configuration and environment detailscommon_functions.sql- Reusable T-SQL functions for byte formatting, object validation, etc.generate_sql_statements.sql- Generate DDL statements for existing objects (tables, indexes, procedures)
- SQL Server 2016+ (earlier versions may work with modifications)
- Appropriate permissions (sysadmin for some operations, VIEW SERVER STATE for diagnostics)
- SSMS or other SQL query tool
- Review the script header to understand purpose, prerequisites, and safety notes
- Modify parameters (database names, paths, thresholds) as needed for your environment
- Test in development first, especially for write operations
- Execute during appropriate maintenance windows where applicable
USE [YourDatabaseName];
GO
:r "troubleshooting/check_database_health.sql"USE [YourDatabaseName];
GO
:r "performance-tuning/missing_indexes.sql"- Backup First: Always backup databases before running administrative scripts
- Test in Dev: Validate scripts in development/test environments before production use
- Review Carefully: Read the "Safety Notes" section in each script header
- Schedule Wisely: Run maintenance scripts (index rebuilds, statistics) during low-activity windows
- Monitor Impact: Watch for locking/blocking impact during execution
- Document Changes: Keep audit trail of when and why scripts were executed
performance-tuning/missing_indexes.sql- Identify optimization opportunitiesperformance-tuning/index_fragmentation.sql- Check index healthperformance-tuning/table_statistics.sql- Update query optimizer data
monitoring/growth_rate_analysis.sql- Analyze size trendsmonitoring/burn_rate_analysis.sql- Monitor resource consumptiontroubleshooting/disk_space_usage.sql- Check available space
troubleshooting/diagnose_blocking_queries.sql- Find blocking sessionstroubleshooting/tempdb_usage.sql- Check for runaway temp space usagemonitoring/performance_counters.sql- Monitor system metricstroubleshooting/disk_space_usage.sql- Verify sufficient disk capacity
troubleshooting/check_database_health.sql- DBCC integrity validationadministration/permission_audit.sql- Verify proper access controlsutilities/get_server_info.sql- Baseline server configuration
high-availability/always_on_availability_groups.sql- Always On AG configurationhigh-availability/log_shipping_setup.sql- Log shipping for DRhigh-availability/failover_cluster_instance.sql- FCI monitoringhigh-availability/linked_servers.sql- Cross-instance queries
administration/maintenance_jobs_setup.sql- Schedule backups, index rebuilds, statsadministration/database_mail_setup.sql- Configure email notificationsadministration/permission_audit.sql- Regular permission reviews
Most scripts include customizable parameters in comments:
DECLARE @DatabaseName NVARCHAR(128) = 'YourDatabaseName';
DECLARE @BackupPath NVARCHAR(500) = 'C:\Backups\';Edit these variables before running based on your environment.
All scripts target SQL Server 2016+ by default. Some scripts note specific version requirements:
--SQL 2019+indicates features only available in SQL Server 2019 or later--Azure SQL compatibleindicates scripts work with Azure SQL Database
Check individual script headers for version-specific notes.
Permission Denied Errors: Verify you have sysadmin or required VIEW SERVER STATE permission
Script Not Found: Use :r command in SSMS to reference relative paths, or use full absolute path
Unexpected Results: Review the script's WHERE clauses - they may exclude system tables or have thresholds (e.g., "only tables > 1000 pages")
This repository contains educational SQL scripts. Review and test all scripts before production use.
To add new scripts:
- Follow the directory structure (
administration/,performance-tuning/,troubleshooting/,utilities/) - Include complete header with purpose, usage, prerequisites, and safety notes
- Add inline comments explaining complex logic
- Use descriptive file names (e.g.,
diagnose_blocking_queries.sql) - Test thoroughly in non-production environments
See .github/copilot-instructions.md for detailed coding standards.