sql server dba best practices

49

Upload: jpaulino

Post on 10-Apr-2015

5.317 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: SQL Server DBA Best Practices
Page 2: SQL Server DBA Best Practices

Brad M. McGehee’sSQL Server DBA Best Practices

A bit about Brad..

Brad M. McGehee is a Microsoft SQL Server MVP with over 10 years’ SQL Server experience.

He founded the popular community site SQL-Server-Performance.Com where he now acts as the technical editor and forum moderator.

Brad is also a frequent speaker at SQL PASS, SQL Connections, SQL Server user groups, and other industry seminars and he is the author or co-author of more than 12 technical books and over 100 published articles. He spends what time he has left in Missouri and Hawaii with his family.

Page 3: SQL Server DBA Best Practices
Page 4: SQL Server DBA Best Practices

General DBA Best PracticesDay to Day 1. Check OS Event Logs, SQL Server

Logs, and Security Logs for unusual events.

2. Verify that all scheduled jobs have run successfully.

3. Confirmthatbackupshavebeenmadeand successfully saved to a secure location.

4. MonitordiskspacetoensureyourSQLServerswon’trunoutofdiskspace.

5. Throughouttheday,periodicallymonitorperformanceusingbothSystemMonitorandProfiler.

6. UseEnterpriseManager/ManagementStudiotomonitorandidentifyblockingissues.

7. Keepalogofanychangesyoumaketoservers,includingdocumentationofanyperformanceissuesyouidentifyandcorrect.

8. Create SQL Server alerts to notify you ofpotentialproblems,andhavethememailedtoyou.Takeactionsasneeded.

9. Run the SQL Server Best Practices Analyzer on each of your server’s instancesonaperiodicbasis.

10.TakesometimetolearnsomethingnewasaDBAtofurtheryourprofessionaldevelopment.

Page 5: SQL Server DBA Best Practices

Installation 1. Alwaysfullydocumentinstallssothat

your SQL Server instances can easily be reproducedinanemergency.

2. Ifpossible,installandconfigureallofyour SQL Server instances consistently, followinganagreed-uponorganizationstandard.

3. Don’t install SQL Server services you don’t use, such as Microsoft Full-TextSearch,NotificationServices,orAnalysis Services.

4. ForbestperformanceofSQLServerrunning under Windows, turn off any operatingsystemservicesthataren’tneeded.

5. ForoptimumSQLServerperformance,youwanttodedicateyourphysicalservers to only running a single instance ofSQLServer,nootherapplications.

6. ForbestI/Operformance,locatethedatabasefiles(.mdf)andlogfiles(.ldf) onseparatearraysonyourservertoisolatepotentiallyconflictingreadsandwrites.

7. Iftempdbwillbeusedheavily,alsoputitonitsownseparatearray.

8. DonotinstallSQLServeronadomaincontroller.

9. Be sure that SQL Server is installed on anNTFSpartition.

10.Don’tuseNTFSdatafileencryption(EFS)andcompressiononSQLServerdatabaseandlogfiles.

Page 6: SQL Server DBA Best Practices

Upgrading1. RuntheUpgradeAdvisorbefore

upgrading.Makeanynecessarychangesbeforeperformingtheupgrade.

2. PerformatestupgradeofyourtestSQLServersbeforeyouupgradeyourproductionservers.Anddon’tforgettotestyourapplicationswiththenewversion also.

3. Beforeyouupgrade,besureyouhaveaplaninplacetofallbacktoincasetheupgradeisproblematic.

4. Don’tupgradeSQLServerclustersinplace.Instead,rebuildthemonnewhardware.

5. IfyouupgradefromapreviousversionofSQLServer,youshouldupdateallofthe statistics in all your databases using eitherUPDATESTATISTICSorsp_updatestats.Thisisbecausestatisticsarenotautomaticallyupdatedduringtheupgradeprocess.

Page 7: SQL Server DBA Best Practices

Security 1. Ensurethephysicalsecurityof

eachSQLServer,preventinganyunauthorizeduserstophysicallyaccessing your servers.

2. Only install required network libraries andnetworkprotocolsonyourSQLServer instances.

3. Minimizethenumberofsysadminsallowed to access SQL Server.

4. AsaDBA,logonwithsysadminprivilegesonlywhenneeded.CreateseparateaccountsforDBAstoaccessSQLServerwhensysadminprivilegesare not needed.

5. Assign the SA account a very obscure password,andneveruseittologonto SQL Server. Use a Windows Authentication account to access SQL Serverasasysadmininstead.

6. Giveuserstheleastamountofpermissionstheyneedtoperformtheirjob.

7. Usestoredproceduresorviewstoallowusers to access data instead of letting themdirectlyaccesstables.

8. Whenpossible,useWindowsAuthentication logins instead of SQL Server logins.

9. UsestrongpasswordsforallSQLServerlogin accounts.

10.Don’tgrantpermissionstothepublicdatabase role.

11.RemoveuserloginIDswhonolongerneed access to SQL Server.

Page 8: SQL Server DBA Best Practices

12.Removetheguestuseraccountfromeach user database.

13.Disablecrossdatabaseownershipchaining if not required.

14.Nevergrantpermissiontothexp_cmdshelltonon-sysadmins.

15.RemovesampledatabasesfromallproductionSQLServerinstances.

16.UseWindowsGlobalGroups,orSQLServerRolestomanagegroupsofusersthatneedsimilarpermissions.

17. Avoid creating network shares on any SQL Server.

18. Turn on login auditing so you can see who has succeeded, and failed, to login.

19. Don’t use the SA account, or login IDs whoaremembersoftheSysadmingroup,asaccountsusedtoaccessSQLServerfromapplications.

20. Ensure that your SQL Servers are behindafirewallandarenotexposeddirectly to the Internet.

21.RemovetheBUILTIN/AdministratorsgrouptopreventlocalserveradministratorsfrombeingabletoaccessSQL Server. Before you do this on a clustered SQL Server, check Books Onlineformoreinformation.

22.RuneachseparateSQLServerserviceunderadifferentWindowsdomainaccount.

Page 9: SQL Server DBA Best Practices

23. Only give SQL Server service accounts theminimumrightsandpermissionsneededtoruntheservice.Inmostcases,localadministratorrightsarenotrequired,anddomainadministratorrights are never needed. SQL Server setupwillautomaticallyconfigureservice accounts with the necessary permissionsforthemtoruncorrectly,you don’t have to do anything.

24. When using distributed queries, use linkedserversinsteadofremoteservers.

25.DonotbrowsethewebfromaSQLServer.

26.InsteadofinstallingvirusprotectiononaSQLServer,performvirusscansfromaremoteserverduringapartofthedaywhen user activity is less.

27.AddoperatingsystemandSQLServerservicepacksandhotfixessoonafterthey are released and tested, as they oftenincludesecurityenhancements.

28.EncryptallSQLServerbackupswithathird-partybackuptool,suchasSQLBackupPro.

29.OnlyenableC2auditingorCommonCriteriacomplianceifrequired.

30. Consider running a SQL Server security scanner against your SQL servers to identify security holes.

31.ConsideraddingacertificatetoyourSQL Server instances and enable SSL or IPSEC for connections to clients.

32. If using SQL Server 2005, enable passwordpolicychecking.

Page 10: SQL Server DBA Best Practices

33.IfusingSQLServer2005,implementdatabaseencryptiontoprotectconfidentialdata.

34. If using SQL Server 2005, don’t use the SQLServerSurfaceAreaConfigurationtool to unlock features you don’t absolutely need.

35. If using SQL Server 2005 and you createendpoints,onlygrantCONNECTpermissionstotheloginsthatneedaccesstothem.ExplicitlydenyCONNECTpermissionstoendpointsthat are not needed by users.

Page 11: SQL Server DBA Best Practices

Job Maintenance 1. AvoidoverlappingjobsonthesameSQL

Server instance. Ideally, each job should runseparatelyatdifferenttimes.

2. When creating jobs, be sure to include errortrapping,logjobactivity,andsetupalerts so you know instantly when a job fails.

3. CreateaspecialSQLServerloginaccountwhosesolepurposeistorunjobs, and assign it to all jobs.

4. If your jobs include Transact-SQL code,ensurethatitisoptimizedtorunefficiently.

5. Periodically(daily,weekly,ormonthly)performadatabase reorganization on all the indexes on all the tables in all your database. This will rebuild the indexes so that the data is no longer logically fragmented.FragmenteddatacancauseSQLServertoperformunnecessarydata reads, slowing down SQL Server’s performance.Reindexingtableswillalsoupdatecolumnstatistics.

6. Don’t reindex your tables when your databaseisinactiveproduction, as it can lock resources and cause yourusersperformanceproblems.Reindexing should be scheduled during downtimes,orduringlightuseofthedatabases.

7. At least every two weeks, run DBCC CHECKDB on all your databases to verify database integrity.

Page 12: SQL Server DBA Best Practices

8. AvoidrunningmostDBCCcommandsduringbusytimesoftheday.ThesecommandsareoftenI/OintensiveandcanreduceperformanceoftheSQLServer, negatively affecting users.

9. Ifyourarelyrestartthemssqlserverservice,youmayfindthatthecurrentSQL Server log gets very large and takesalongtimetoloadandview.Youcantruncate(essentiallycreateanewlog)thecurrentserverlogbyrunningDBCCERRORLOG.Setthisupasaweekly job.

10.Scriptalljobsandstorethesescriptsina secure area so they can be used if you need to rebuild the servers.

Page 13: SQL Server DBA Best Practices

Database Settings 1. Unless you know exactly what you are

doingandhavealreadyperformedimpartialexperimentsthatprovethatmakingSQLServerconfigurationchangeshelpsyouinyourparticularenvironment,donotchangeanyoftheSQLServerconfigurationsettings.

2. Inalmostallcases,leavethe“autocreatestatistics”and“autoupdatestatistics”optionsonforalluserdatabases.

3. Inmostcases,thesettingsforthe“maximumservermemory” and the “minimumservermemory” should be left to their default values. This is because the default values allow SQL Server todynamicallyallocatememoryintheserverforthebestoveralloptimumperformance.IfyouuseAWEmemory,thenthisrecommendationistobeignored,andmaximummemoryneedstobesetmanually.

4. Many databases need to be shrunk periodicallyinordertofreeupdiskspaceasolderdataisdeletedfromthedatabase.Butdon’tbetemptedtousethe“auto shrink”databaseoption,as it can waste SQL Server resources unnecessarily. Instead, shrink databases manually.

Page 14: SQL Server DBA Best Practices

5. Don’t rely on AUTOGROWTH to automaticallymanagethesizeofyourdatabases.Instead,proactivelymonitorandalterdatabasesizeascircumstancesdictate.OnlyuseAUTOGROWTHtodealwithunexpectedgrowth.

Replication1. Replicationneedsshouldbeclearly

definedbeforecreatingareplicationtopology.Successfulreplicationcanbedifficultandrequiresmuchpre-planning.

2. Ideally,publishers,distributors,andsubscribersshouldbeonseparatephysicalhardware.

3. Create,document,andtestabackupand restore strategy. Restoring replicateddatabasescanbecomplexandrequiresmuchplanningandpractice.

4. Scriptthereplicationtopologyaspartofyourdisasterrecoveryplansoyoucaneasilyrecreateyourreplicationtopologyif needed.

5. Usedefaultreplicationsettings,unlessyou can ensure that a non-default settingwillactuallyimprovereplicationperformanceorotherissues.Besurethat you test all changes to ensure that theyareaseffectiveasyouexpect.

6. Fullyunderstandtheimplicationsofaddingordroppingarticles,changingpublicationproperties,andchangingschemaonpublisheddatabases,beforemakinganyofthesechanges.

Page 15: SQL Server DBA Best Practices

7. Periodically, validate data between publishersandsubscribers.

8. Regularlymonitorreplicationprocessesand jobs to ensure they are working.

9. Regularlymonitorreplicationperformance,andperformancetuneasnecessary.

10.Addalertstoallreplicationjobssoyouarenotifiedofanyjobfailures.

Page 16: SQL Server DBA Best Practices
Page 17: SQL Server DBA Best Practices

High Availability Best PracticesGeneral High Availability 1. PhysicallyprotectyourSQLServers

fromunauthorizedusers.2. PhysicallydocumentallofyourSQL

Serverinstances.Incorporateeffectivechangemanagement.

3. Always use a RAIDed array or SAN for storing your data.

4. Use SQL Server clustering, database mirroring,orlogshippingtoprovideextra fault tolerance.

5. Replicationisnotaneffectivemeanstoprotectyourdata.

6. Ensure that your entire IT infrastructure is redundant. It is only as strong as its weakest link.

7. Always use server-class hardware, and standardizeonthesamehardwareasmuchaspossible.

8. Usehardwareandsoftwaremonitoringtoolssoyoucanquicklybecomeawareofwhenproblemsfirstarise.

9. Aftertesting,applyallnewservicepacksandhotfixestotheOSandSQLServer.

10. Cross-train staff so that there are multiplepeoplewhoareabletodealwithvirtuallyanyproblemorissue.

Page 18: SQL Server DBA Best Practices

Disaster Recovery 1. Youmustcreateadisasterrecoveryplan

and include every detail you will need to rebuild your servers.

2. AsyourSQLServerschangeovertime,don’tforgettoupdateyourdisasterrecoveryplan.

3. Writethedisasterrecoveryplansothatanycomputerliteratepersonwillbeabletoreadandfollowit.DonotassumeaDBA will be rebuilding the servers.

4. Fullytestyourdisasterrecoveryplanatleast once a year.

5. Re-readallthebestpracticejustmentioned.I’mnotkidding.Remember,as DBAs, we are guardians of the organization’s data. This is a huge responsibility.

Page 19: SQL Server DBA Best Practices

Backup1. Allproductiondatabasesshouldbeset

tousethefullrecoverymodel.Thisway,youcancreatetransactionlogbackupsonaperiodicbasis.

2. Wheneverpossible,performadailyfullbackupofallsystemanduserdatabases.

3. Forallproductiondatabases,performregulartransactionlogbackups,atleastonce an hour.

4. Performfullbackupsduringperiodsoflowuseractivityinordertominimizetheimpactofbackupsonusers.

5. Periodicallytestbackupstoensurethatthey are good and can be restored.

6. Backupfirsttodisk,thenmovetotapeorsomeotherformofbackupmedia.

7. Storebackupsoffsite.8. IfusingSQLServer2005encryption,be

suretobackuptheservicemasterkey,databasemasterkeys,andcertificates.

9. Ifyoufindthatbackuptimestakelongerthanyourbackupwindow,orifbackupfilesizesaretakinguptoomuchspaceon your storage device, consider a third-partybackupprogram,suchasSQLBackupPro.

10.Document,step-by-step,theprocesstorestoresystemanduserdatabasesontothesame,oradifferentserver.Youdon’twanttobelookingthisinformationupduringanemergency.

Page 20: SQL Server DBA Best Practices

Clustering 1. Detailedplanningiscriticaltothe

success of every SQL Server cluster installation.Fullyplantheinstallbeforeperformingtheactualinstall.

2. Anexpensiveclusterisoflittlevalueifthesupportinginfrastructureisnotalsofaulttolerant.Forexample,don’tforgetpowerredundancy,networkredundancy,etc.

3. Run only a single instance of SQL Serverpernode.Whetheryouhavetwoor eight nodes in your cluster, leave one node as a failover node.

4. Clusternodesmustnotbedomaincontrollers,andallnodesmustbelonginthesamedomainandshouldhaveaccesstotwoormoredomaincontrollers.

5. AllclusterhardwaremustbeontheMicrosoft Windows Clustering Hardware CompatibilityList,andcertifiedtoworktogetheraspartofacluster.

6. Since clustering is not designed toprotectdata(onlySQLServerinstances),thesharedstoragedeviceusedbytheclustermustincorporatefault tolerant technology. Consider log shippingormirroringtofurtherprotectyourproductiondatabases.

7. When initially installing Windows and SQL Server Clustering, be sure that all driversandsoftwareareup-to-date,includingthelatestservicepacksorhotfixes.

Page 21: SQL Server DBA Best Practices

8. Each node of a cluster should have identical hardware, drivers, software, andconfigurationsettings.

9. Fiber channel shared arrays are preferredoverSCSI,andFiberchannelhastobeusedifyouincludemorethantwo nodes in your cluster.

10.TheQuorumdrivemustbeonitsownfault-tolerant, dedicated, logical drive.

11. Once the cluster has been installed, test itthoroughlyforeverypossiblefailurescenario.

12.DonotrunantivirusorantispywareonaSQL Server cluster.

13.IfyouneedtoreconfigureanyWindowsorSQLServerclusteringconfigurationoptions,suchasIPaddressesorvirtualnames,youwillneedtouninstallclustering and then reinstall it.

14.Monitoractiveproductionclustersonadailybasis,lookingforanypotentialproblems.Periodicallytestfailoveronproductionserverstoensureallisworking well.

15. Once you have a stable SQL Server Cluster running, be very leery about makinganychangestoit,whatsoever.

Page 22: SQL Server DBA Best Practices

SQL Server 2005 Mirroring 1. Theprincipaldatabaseandthemirror

databaseshouldbeonseparatephysicalhardware,andideally,indifferentphysicallocations.

2. The witness server should be on separatephysicalhardware,andbeonaseparatenetwork(bestifatathirdlocation).

3. Initialdatabasemirroringsetupshouldbedoneduringlessbusytimes,asthesetupprocesscannegativelyaffectperformanceoftheproductiondatabasebeingmirrored.

4. Usehighavailabilitymodewheneverpossible,andhighperformancemodeonly when required.

5. The hardware, along with the OS and SQLServerconfiguration,shouldbeidentical(atleastverysimilar)betweenthe two servers.

6. While a fast connection is not required betweenmirroredservers,thefastertheconnection, and the better quality the connection, the better.

7. Youwillwanttooptimizetheperformanceofthemirroreddatabaseasmuchaspossibletoreducetheoverheadcausedbythemirroringprocessitself.

8. Thoroughlytestdatabasemirroringbeforeputtingitintoproduction.

9. Monitordatabasemirroringdailytoensurethatitisworkingproperly,andismeetingperformancegoals.

Page 23: SQL Server DBA Best Practices

10.Developaformaloperationalandrecoveryprocedure(anddocument)tosupportmirroring.Periodicallytestthefailoverprocesstoensurethatitworks.

LogShipping1. Ifyoudon’tcurrentlyemployclustering

ordatabasemirroringforyourSQLServers because of cost, consider employinglogshippingtohelpboostyourhighavailability.Itprovidesreasonably high availability at low cost.

2. If you take advantage of SQL Server 2000or2005logshippingcapability,youwillwanttokeepthelogshippingmonitoringserviceonaSQLServerofits own, not on the source or destination serversparticipatinginlogshipping.Notonlyisthisimportantforfaulttolerance,butbecausethelogshippingmonitoringservice incurs overhead that can affect theperformanceofthesourceanddestination servers.

3. Monitorlogshippingdailytoensurethatit is working successfully.

4. Learnwhatyouneedtoknowtofixshippingifsynchronizationislostbetweentheproductionandbackupdatabases.

5. Document,andtestyourserverrecoveryplan,soyouwillbereadyincaseofaserver failure.

Page 24: SQL Server DBA Best Practices
Page 25: SQL Server DBA Best Practices

Performance Tuning BestPracticesPerformanceMonitoring1. RegularlymonitoryourSQLServersfor

blocked transactions.2. Regularlymonitorsystemperformance

usingSystemMonitor.UseSystemMonitorforbothreal-timeanalysisandforhistorical/baselineanalysis.

3. If running SQL Server 2005, SP2 or later, install the free SQL Server PerformanceDashboard.Itcanbeusedforreal-timemonitoringandperformancetroubleshooting.

4. RegularlymonitoractivityusingProfiler.Be sure that traces are taken during thebusiesttimesofthedaysoyougetamorerepresentativetraceofwhatisgoing on in each server. When running theProfiler,donotcollectmoredatathan you need to collect.

5. PerformperformancemonitoringfromacomputerthatisnottheSQLServeryouaremonitoring.Runmonitoringtoolsonaseparatedesktoporserver.

Page 26: SQL Server DBA Best Practices

HardwarePerformanceTuning1. Althoughheavy-dutyhardwarecanhelp

SQLServer’sperformance,applicationanddatabasedesigncanplayagreaterpartinoverallperformancethanhardware.Keepthisinmind,asthrowinggoodmoneyafterbadonserverhardwaredoesnotalwaysfixSQLServerperformanceproblems.Beforegetting faster hardware, be sure you havethoroughlytunedyourapplications,Transact-SQL, and database indexing.

2. Inmanycases,addingRAMtoaserveristhecheapestandfastestwaytoboosthardwareperformanceofaSQLServer.ButbeforeaddingmoreRAMtoaSQLServer,ensurefirstthatitwillbeusedbySQLServer.AddingmoreRAMdoesn’tmeanthatSQLServerwillalwaysuseit. If the current Buffer Hit Cache Ratio is consistently above 99% and you have wellmorethan10MBofAvailableRAM,yourserverwon’tbenefitfromaddingadditional RAM.

3. If your SQL Server’s total CPU utilization isconsistentlyabove80%ormore,youneedmoreCPUs,fasterCPUs,oryouneedtofindawaytoreducetheloadonthe current server.

4. If the Physical Disk Object: % Disk Timecounterexceeds55%,andthePhysical Disk Object: Avg. Disk Queue Length exceeds a count of 2 for each individual disk drive in your disk storage subsystem,thenyoumostlikelyexperiencingadiskI/Operformance

Page 27: SQL Server DBA Best Practices

issue and need to start looking for solutions.

5. Don’trunanyapplicationsonyourserver other than SQL Server, with the exceptionofnecessaryutilities.

6. NTFS-formattedpartitions should not exceed80%oftheircapacity.Forexample,ifyouhavea100GBlogicaldrive, it should never be fuller than 80GB.Why?NTFSneedsroomtowork,andwhenyouexceed80%capacity,NTFSbecomelessefficientandI/Ocansuffer for it.

7. IfyourSQLServerdatabaseismostlyreads, then a RAID 5 array offers good protectionandadequateperformance.IfyourSQLServerdatabaseismostlywrites, then use a RAID 10 array for best protectionandperformance.

8. If your SQL Server’s tempdbdatabase isheavilyusedbyyourapplication(s),consider locating it on an array of its own(suchasRAID1orRAID10).ThiswillallowdiskI/Otobemoreevenlydistributed,reducingdiskI/Ocontentionissues,andspeedingupSQLServer’soverallperformance.

9. Themorespindlesyouhaveinanarray,thefasterdiskI/Owillbe.

10. Ensure that all hardware is running the latest,approveddrivers.

Page 28: SQL Server DBA Best Practices

Indexing 1. Periodically, run the Index Wizard

or Database Engine Tuning Advisor againstcurrentProfilertracestoidentifypotentiallymissingindexes.

2. Removeindexesthatareneverused.3. Don’t accidentally create redundant

indexes.4. Asaruleofthumb,everytableshould

have at least a clustered index. Generally, but not always, the clustered indexshouldbeonacolumnthatmonotonicallyincreases—suchasanidentitycolumn,orsomeothercolumnwherethevalueisincreasing—andisunique.Inmanycases,theprimarykeyistheidealcolumnforaclusteredindex.

5. Since you can only create one clustered indexpertable,takeextratimetocarefully consider how it will be used. Considerthetypeofqueriesthatwillbeusedagainstthetable,andmakeaneducatedguessastowhichquery(themostcommononerunagainstthetable,perhaps)isthemostcritical,andifthisquerywillbenefitfromhavingaclusteredindex.

6. Ifacolumninatableisnotatleast95%unique,thenmostlikelythequeryoptimizerwillnotuseanon-clusteredindexbasedonthatcolumn.Becauseof this, you generally don’t want to add non-clusteredindexestocolumnsthataren’t at least 95% unique.

Page 29: SQL Server DBA Best Practices

7. Keepthe“width”ofyourindexesasnarrowaspossible. This reduces the size of the index and reduces the numberofdiskI/Oreadsrequiredtoreadtheindex,boostingperformance.

8. Ifpossible,avoidaddingaclusteredindextoaGUIDcolumn(uniqueidentifierdatatype).GUIDstakeup16-bytesofstorage,morethananIdentifycolumn,whichmakestheindexlarger,whichincreasesI/Oreads,whichcanhurtperformance.

9. Indexes should be considered on all columnsthatarefrequentlyaccessedbytheJOIN,WHERE,ORDERBY,GROUPBY,TOP,andDISTINCTclauses.

10.Don’tautomaticallyaddindexes on a tablebecauseitseemsliketherightthing to do. Only add indexes if you know that they will be used by the queries run against the table.

11.Whencreatingindexes,trytomakethemuniqueindexesifatallpossible.SQL Server can often search through a unique index faster than a non-unique index because in a unique index, each row is unique, and once the needed record is found, SQL Server doesn’t have to look any further.

12.Ifyouperformregularjoins between twoormoretables in your queries, performancewillbeoptimizedifeachofthejoinedcolumnshaveappropriateindexes.

Page 30: SQL Server DBA Best Practices

13.Don’tautomaticallyacceptthedefaultvalueof100forthefillfactorforyourindexes.Itmayormaynotbestmeetyourneeds.Ahighfillfactorisgoodforseldomchangeddata,buthighlymodifieddataneedsalowerfillfactortoreducepagesplitting.

14. Don’t over index your OLTP tables, as everyindexyouaddincreasesthetimeittakestoperformINSERTS,UPDATES,andDELETES.Thereisafinelinebetweenhavingtheidealnumberofindexes(forSELECTs)andtheidealnumbertominimizetheoverheadthat occurs with indexes during data modifications.

15.Ifyouknowthatyourapplicationwillbeperformingthesamequeryoverandoveronthesametable,considercreating a non-clustered covering index on the table. A covering index, which is aformofacompositeindex,includesallofthecolumnsreferencedinSELECT,JOIN, and WHERE clauses of a query. Because of this, the index contains the data you are looking for and SQL Server doesn’thavetolookuptheactualdatainthetable,reducinglogicaland/orphysicalI/O,andboostingperformance.

Page 31: SQL Server DBA Best Practices
Page 32: SQL Server DBA Best Practices

Application Design andCoding Best PracticesDatabase Design 1. Bad logical database design results

inbadphysicaldatabasedesign,andgenerallyresultsinpoordatabaseperformance. So, if it is your responsibilitytodesignadatabasefromscratch, be sure you take the necessary timeandefforttogetthelogicaldatabase design right. Once the logical design is right, then you also need to takethetimetogetthephysicaldesignright.

2. Normalizeyourdatatoensurebestperformance.

3. Take advantage of SQL Server’s built-in referentialintegrity.Youdon’tneedtowrite your own.

4. Alwaysspecifythenarrowestcolumnsyou can. In addition, always choose the smallestdatatypeyouneedtoholdthedatayouneedtostoreinacolumn.Thenarrowerthecolumn,thelessamountofdata SQL Server has to store, and the faster SQL Server is able to read and write data.

5. TrytoavoidperformingbothOLTPandOLAPtransactionswithinthesamedatabase.

Page 33: SQL Server DBA Best Practices

Queries and Stored Procedures 1. Maintain all code in a source control

system.2. Keeptransactionsasshortaspossible.

This reduces locking and increases applicationconcurrency,whichhelpstoboostperformance.

3. Avoid using query hints unless you know exactly what you are doing, and you haveverifiedthatthehintactuallyboostsperformance.

4. Encapsulatealltransactionswithinstoredprocedures, including both the BEGIN TRANSACTION and COMMIT TRANSACTIONstatementsintheprocedure.

5. Use the least restrictive transaction isolationlevelpossible for your user connection, instead of always using the default READ COMMITTED.

6. Wheneveraclientapplicationneedsto send Transact-SQL to SQL Server, senditintheformofastoredprocedureinsteadofascriptorembeddedTransact-SQL.Storedproceduresoffermanybenefits,including:

a. Reducednetworktrafficandlatency,boostingapplicationperformance.

b. Storedprocedureexecutionplanscanbe reused, staying cached in SQL Server’smemory,reducingserveroverhead.

Page 34: SQL Server DBA Best Practices

c. Clientexecutionrequestsaremoreefficient.Forexample,ifanapplicationneeds to INSERT a large binary value intoanimagedatacolumnnotusingastoredprocedure,itmustconvertthebinaryvaluetoacharacterstring(whichdoublesitssize),andsendittoSQLServer. When SQL Server receives it, it thenmustconvertthecharactervaluebacktothebinaryformat.Thisisalotofwastedoverhead.AstoredprocedureeliminatesthisissueasparametervaluesstayinthebinaryformatallthewayfromtheapplicationtoSQLServer, reducing overhead and boosting performance.

d. Storedprocedureshelppromotecodereuse. While this does not directly boost anapplication’sperformance,itcanboosttheproductivityofdevelopersbyreducingtheamountofcoderequired,alongwithreducingdebuggingtime.

e. Storedprocedurescanencapsulatelogic.Youcanchangestoredprocedurecodewithoutaffectingclients(assumingyoukeeptheparametersthesameanddon’tremoveanyresultsetscolumns).Thissavesdevelopertime.

f. Storedproceduresprovidebettersecurity to your data

7. SET NOCOUNT ON at the beginning of eachstoredprocedureyouwrite.Thisstatementshouldbeincludedineverystoredprocedureyouwrite.

Page 35: SQL Server DBA Best Practices

8. Before you are done with your stored procedurecode,reviewitforanyunusedcode,parameters,orvariables that you mayhaveforgottentoremovewhileyouweremakingchanges,andremovethem.

9. Forbestperformance,all objects that arecalledwithinthesamestoredprocedureshouldallbeownedbythesameobjectownerorschema,preferablydbo,andshouldalsobereferredtointheformatofobject_owner.object_nameorschema_owner.object_name.

10.Onewaytohelpensurethatstoredproceduresqueryplans are reused fromexecutiontoexecutionofthesamestoredprocedureistoensurethatanyuserconnectionsinformation,SEToptions,databaseoptions,orSQLServerconfigurationoptionsdon’tchangefromexecutiontoexecutionofthesamestoredprocedure.Iftheydochange,thenSQLServermayconsiderthesesamestoredprocedurestobedifferent, and not be able to reuse the currentqueryplanstoredincache.

Page 36: SQL Server DBA Best Practices

Transact-SQL 1. Don’tbeafraidtomakeliberaluseof

in-lineandblockcomments in your Transact-SQL code, they will not affect theperformanceofyourapplicationandtheywillenhanceyourproductivitywhenyouorotherscomebacktothecodeandtrytomodifyit.

2. Ifpossible,avoid using SQL Server cursors. They generally use a lot of SQL Server resources and reduce the performanceandscalabilityofyourapplications.Ifyouneedtoperformrow-by-rowoperations,trytofindanothermethodtoperformthetask.

3. WhenusingtheUNIONstatement,keepinmindthat,bydefault,itperformstheequivalent of a SELECT DISTINCT onthefinalresultset.Inotherwords,UNION takes the results of two like recordsets,combinesthem,andthenperformsaSELECTDISTINCTinordertoeliminateanyduplicaterows.Thisprocessoccurseveniftherearenoduplicaterecordsinthefinalrecordset.Ifyouknowthatthereareduplicaterecords,andthispresentsaproblemforyourapplication,thenbyallmeansusetheUNIONstatementtoeliminatetheduplicaterows.Butifnot,useUNIONALL, which is less resource intensive.

Page 37: SQL Server DBA Best Practices

4. Carefully evaluate whether your SELECT query needs the DISTINCT clause or not.SomedevelopersautomaticallyaddthisclausetoeveryoneoftheirSELECTstatements,evenwhen it is not necessary.

5. In your queries, don’treturncolumndata you don’t need.Forexample,youshould not use SELECT * to return all thecolumnsfromatableifyoudon’tneedallthedatafromeachcolumn.Inaddition,usingSELECT*maypreventthe use of covered indexes, further potentiallyhurtingqueryperformance.

6. Always include a WHERE clause in yourSELECTstatement to narrow the numberofrowsreturned.Onlyreturnthose rows you need.

7. When you have a choice of using the IN or the BETWEEN clauses in your Transact-SQL, you will generally want to usetheBETWEENclause,asitismoreefficient.

8. IfyouneedtowriteaSELECTstatementtoretrievedatafromasingletable,don’tSELECTthedatafromaviewthatpointstomultipletables.Instead,SELECTthedatafromthetabledirectly,orfromaview that only contains the table you are interested in. If you SELECT the data fromthemulti-tableview,thequerywillexperienceunnecessaryoverhead,andperformancewillbehindered.

Page 38: SQL Server DBA Best Practices

9. Ifyourapplicationallowsuserstorunqueries, but you are unable in your applicationtoeasilypreventusersfromreturning hundreds, even thousands of unnecessary rows of data, consider usingtheTOPoperatorwithintheSELECTstatement.Thisway,youcanlimithowmanyrowsarereturned,evenif the user doesn’t enter any criteria to helpreducethenumberorrowsreturnedto the client.

10. Try to avoid WHERE clauses that are non-sargable. If a WHERE clause is sargable,thismeansthatitcantakeadvantageofanindex(assumingoneisavailable)tospeedcompletionofthe query. If a WHERE clause is non-sargable,thismeansthattheWHEREclause(oratleastpartofit)cannottake advantage of an index, instead performingatable/indexscan,whichmaycausethequery’sperformancetosuffer.Non-sargablesearchargumentsintheWHEREclause,suchas“ISNULL”,“<>”,“!=”,“!>”,“!<”,“NOT”,“NOTEXISTS”,“NOTIN”,“NOTLIKE”,and“LIKE‘%500’”generallyprevent(butnotalways)thequeryoptimizerfromusinganindextoperformasearch.Inaddition,expressionsthatincludeafunctiononacolumn,expressionsthathavethesamecolumnonbothsidesoftheoperator,orcomparisonsagainstacolumn(notaconstant),arenotsargable.

Page 39: SQL Server DBA Best Practices

SQL Server 2005 CLR 1. Don’t turn on the CLR unless you will be

using it.2. UsetheCLRtocomplementTransact-

SQLcode,nottoreplaceit.3. Standard data access, such as SELECT,

INSERTs, UPDATEs, and DELETEs are best done via Transact-SQL code, not the CLR.

4. Computationallyorprocedurallyintensive business logic can often be encapsulatedasfunctionsrunningintheCLR.

5. Ifaprocedureincludesbothsignificantdataaccessandcomputationandlogic,considerseparatingtheprocedurecodein the CLR that calls the Transact-SQL storedprocedurethatdoesmostofthedata access.

6. Use the CLR for error handling, as it is morerobustthanwhatTransact-SQLoffers.

7. UsetheCLRforstringmanipulation,asit is generally faster than using Transact-SQL.

8. Use the CLR when you need to take advantage of the large base class library.

9. Use the CLR when you want to access externalresources,suchasthefilesystem,EventLog,awebservice,ortheregistry.

10. Set CLR code access security to the mostrestrictivepermissionsaspossible.

Page 40: SQL Server DBA Best Practices

XML 1. XMLisbestusedformodelingdatawith

aflexibleorrichstructure.2. Don’t use XML for conventional,

structured data.3. StoreobjectpropertiesasXMLdatain

XMLdatatypes.4. Whenpossible,usetypedXMLdata

typesoveruntypedXMLdatatoboostperformance.

5. AddprimaryandsecondaryindexestoXMLcolumnstospeedretrieval.

Page 41: SQL Server DBA Best Practices
Page 42: SQL Server DBA Best Practices

SQL Server ComponentBest PracticesSSIS 1. Schedulelargedataimports,exports,

ortransformationonyourproductionserversduringlessbusyperiodsofthedaytoreducetheimpactonyourusers.

2. Consider running large, resource-intensiveSSISpackagesonadedicatedphysicalserver.

3. Renamealldefaultnameanddescriptionpropertiesusingstandardnamingconventions.Thiswillmakeiteasier for you and others to debug or modifyyourpackages.

4. Includeannotationsinyourpackagestomakeiteasierforyou,andothers,tounderstand what is going on.

5. Use Sequence Containers to organize packagestructuresintologicalworkunits.

6. UseNamespacesforyourpackages.7. Onlyscopevariablesforthecontainers

for which they are needed.8. Ifyouknowthatdataisalreadypre-

sorted,setIsSorted=TRUE.Doingsocanhelppreventunnecessarysorts,whichuseupresourcesunnecessarily.

Page 43: SQL Server DBA Best Practices

9. Whenselectingcolumnsfromatableto return, return only what is needed. In additionuseaTransact-SQLstatementinanOLEDBSourcecomponent,ortheLookupComponent,insteadofselectinganentiretable.Thisway,youpreventunnecessarydatafrombeingprocessed.

10. When INSERTing data, use the SQL Server Destination instead of the OLE DBDestinationtoboostperformance.

ReportingServices1. Ideally,dedicateoneormorephysical

serversforReportingServices.2. The SQL Server databases used to

producetherawdataforreportsshouldbeontheirowndedicatedphysicalservers.

3. Only return the actual data you need in thereport,nomoreornoless.

4. OptimizetheperformanceoftheTransact-SQL code you are using to returndataforyourreportbeforeyouactuallydesignthephysicalappearanceofthereport.

5. Manageallreportcodeand.rdlfilesusingaSourceControlsystem.

Page 44: SQL Server DBA Best Practices

NotificationServices1. ImplementingNotificationsServices

requirescarefulplanninganddesign.2. SQLServer2000and2005Notification

Services can be a heavy burden on aSQLServer,dependingonhowitisused.Forbestoverallperformance,itisrecommendedtorunNotificationServices to a dedicated SQL Server.

3. NotificationServicesmakesheavyuseofthetempdbdatabase.Becauseofthis,you should consider two things: First, considerallocatingaminimumsizeforthetempdbdatabase,sothatwhenSQLServer is restarted, it will create a new tempdbdatabaseofanappropriatesize.ThispreventsSQLServerfromhavingtoexpandthetempdbdatabasesizeautomatically,whichcanleadtoshortburstsofpoorI/Operformanceasthedatabaseisexpanded.Second,considerinstallingthetempdbdatabaseonitsowndedicatedphysicaldiskdriveorarrayinordertoreduceI/Ocontention.

4. NotificationServicesalsomakesheavyuse of the transaction log. To reduce I/Ocontention,considerlocatingthetransactionlogfileonitsowndedicatedphysicaldiskdrive.Inaddition,theFullBackupRecoverymodelshouldbeusedtoensureaminimumoflostdata,shouldtherebeanyproblem.Also,becausethe log is heavily used, be sure that it is backedup(logtruncated)oftensothatitdoesnotfillupyourdiskspaceandstopyour server.

Page 45: SQL Server DBA Best Practices

5. WhilemanyindexesarecreatedautomaticallybyNotificationServiceswhentheNotificationServicesdatabaseiscreated,noteverypotentiallyusefulindexiscreated.Onceyoursystemisinproduction,considertakingaProfilerTraceduringaverybusytimeoftheserver and use the Index Wizard or the Database Engine Tuning Advisor to identifypotentialnewindexes.

Page 46: SQL Server DBA Best Practices

Analysis Services 1. AlwaysrunOLAPapplicationsontheir

own dedicated servers, never sharing a serverrunningOLTPapplications.Thetwotypesofapplicationsaremutuallyexclusivewhenitcomestoperformancetuning.

2. When designing OLAP cubes, don’t includemeasuresordimensionsthatyour users won’t use. The way to preventthisisgoodsystemsanalysisand design. Unused data will increase the size of your cubes and slow performance.

3. Whenusingthestarschemadesign, at a minimum,youwillcreateanon-clusteredindexontheprimarykeyofeachdimensiontableandanon-clusteredindex on each of the related foreign-keys.Fromthere,youcancreatenon-clusteredindexesonadditionalcolumnsthatwillbequeriedonfrequently.Youdon’tneedtocreatecompositeindexesto create covering indexes because SQL Server will use index intersection to do thisforyouautomatically.

4. When you create indexes on your data warehousesanddatamarts,useaFILLFACTOR of 100 to ensure that the indexpagesareasfullaspossible.ThisreducesunnecessaryI/O,speedingupperformance.

5. Schedulecubeupdatesonyourproductionserversduringlessbusyperiodsofthedaytoreducetheimpacton your users.

Page 47: SQL Server DBA Best Practices

Service Broker 1. Planning for a Service Broker

implementationrequiresthatyouanswerthese questions:

a. Decide the role that Service Broker will playintheapplication.

b. Identifytherequiredinformationforeachstepofaconversationinordertocompleteeachtask.

c. Selectwherethemessageprocessinglogic will run.

d. Decide on the technology to be used to implementyourapplication

e. Identifywhichservercomponentswillyourapplicationusethemost.

2. Before rolling out a Service Broker application,testitthoroughlyinatestenvironmentthatcloselyrepresentsyouractualproductionenvironment.

3. AfteraServiceBrokerapplicationhasbeendesignedandwritten,itmustberolled out. This is generally done with a setofinstallationscriptsthatareruntocreatethenecessarymessagetypes,contracts, queues, services, and stored procedures.Ideally,theDBAwillreviewthesescriptsbeforerunningthem.

4. Oncetheinstallationscriptsarerun,itisthejoboftheDBAtoconfigurethenecessarysecurityprinciples,certificates,remoteservicebindings,and required routes.

5. Because a Service Broker installation canbecomplex,itmustbefullydocumentedsothatitcanbeeasilyreplicatedanduninstalledifnecessary.

Page 48: SQL Server DBA Best Practices

Full-Text Search 1. If using SQL Server 2005, full-text

catalogs can be attached and detached along with their database. This is the bestwaytomoveadatabaseandcatalog together.

2. If using SQL Server 2005, use BACKUP andRESTOREtobackupandrestoreyour full-text catalogs. Catalogs should bebackedupwhenthedatabaseisbackedup.

3. Generallyspeaking,limitedhardwareresourcescontributemosttopoorFull-TextSearchperformance.CheckforCPU,diskI/O,andmemorybottlenecks,andiftheyareidentified,theyoftenmustbecorrectedwiththepurchaseoflargerhardware.

4. Regularlydefragmenttheindexonthe base tables that feed the Full-Text Search engine. In addition, regularly reorganize the full-text catalog.

5. Keepfull-textkeycolumnsasnarrowaspossibletospeedperformance.

Page 49: SQL Server DBA Best Practices

Notes