SQLAuthority.com SQL Server Important Guidelines SQLServer Guide Lines
User Manual:
Open the PDF directly: View PDF .
Page Count: 9
![](asset-1.png)
1© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
INDEX
GuidelinesforSQLSERVER
1ImportantGuidelinesforSQLServer…………………………..2
Notice:
Allrightsreservedworldwide.Nopartofthisbookmaybereproducedorcopiedor
translatedinanyformbyanyelectronicormechanicalmeans(includingphotocopying,
recording,orinformationstorageandretrieval)withoutpermissioninwritingfromthe
publisher,exceptforreadingandbrowsingviatheWorldWideWeb.Usersarenotpermitted
tomountthisfileonanynetworkservers.
Formoreinformationsendemailto:pinal@sqlauthority.com
![](asset-2.png)
2© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
ImportantGuidelinesforSQLSERVER
• Use"Pascal"notationforSQLserverObjectsLikeTables,Views,StoredProcedures.
Alsotablesandviewsshouldhaveending"s".
Example:
UserDetails
Emails
• Ifyouhavebigsubsetoftablegroupthanitmakessensetogiveprefixforthistable
group.Prefixshouldbeseparatedby_.
Example:
Page_UserDetails
Page_Emails
• UsefollowingnamingconventionforStoredProcedure.sp<Application
Name>_[<groupname>_]<actiontype><tablenameorlogicalinstance>Whereaction
is:Get,Delete,Update,Write,Archive,Insert...i.e.verb
Example:
spApplicationName_GetUserDetails
spApplicationName_UpdateEmails
• UsefollowingNamingpatternfortriggers:TR_<TableName>_<action><description>
Example:
TR_Emails_LogEmailChanges
TR_UserDetails_UpdateUserName
• Indexes:IX_<tablename>_<columnsseparatedby_>
Example:
IX_UserDetails_UserID
• PrimaryKey:PK_<tablename>
Example:
PK_UserDetails
PK_Emails
![](asset-3.png)
3© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
• ForeignKey:FK_<tablename_1>_<tablename_2>
Example:
FK_UserDetails_Emails
• Default:DF_<tablename>_<columnname>
Example:
DF_UserDetails_UserName
• NormalizeDatabasestructurebasedon3rdNormalizationForm.Normalizationisthe
processofdesigningadatamodeltoefficientlystoredatainadatabase.(ReadMore
Here)
• AvoiduseofSELECT*inSQLqueries.Insteadpracticewritingrequiredcolumnnames
afterSELECTstatement.
Example:
SELECT Username,Password
FROM UserDetails
• AvoidusingtemporarytablesandderivedtablesasitusesmoredisksI/O.Insteaduse
CTE(CommonTableExpression);itsscopeislimitedtothenextstatementinSQLquery.
(ReadMoreHere)
• UseSETNOCOUNTONatthebeginningofSQLBatches,StoredProceduresandTriggers.
ThisimprovestheperformanceofStoredProcedure.(ReadMoreHere)
• ProperlyformatSQLqueriesusingindents.
Example:WrongFormat
SELECTUsername,PasswordFROMUserDetailsudINNERJOIN EmployeeeON
e.EmpID=ud.UserID
Example:CorrectFormat
SELECT Username,Password
FROM UserDetailsud
INNERJOINEmployeeeONe.EmpID=ud.UserID
![](asset-4.png)
4© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
• PracticewritingUpperCaseforallSQLkeywords.
Example:
SELECT,UPDATE,INSERT,WHERE,INNERJOIN,AND,OR,LIKE.
• TheremustbePRIMARYKEYinallthetablesofdatabasewithcolumnnameID.Itis
commonpracticetousePrimaryKeyasIDENTITYcolumn.
• If“OneTable”references“AnotherTable”thanthecolumnnameusedinreference
shouldusethefollowingrule:
ColumnofAnotherTable:<OneTableName>ID
Example:
IfUsertablereferencesEmployeetablethanthecolumnnameusedinreferenceshould
beUserIDwhereUseristablenameandIDprimarycolumnofUsertableandUserIDis
referencecolumnofEmployeetable.
• ColumnswithDefaultvalueconstraintshouldnotallowNULLs.
• PracticeusingPRIMARYkeyinWHEREconditionofUPDATEorDELETEstatementsas
thiswillavoiderrorpossibilities.
• Alwayscreatestoredprocedureinsamedatabasewhereitsrelevanttableexists
otherwiseitwillreducenetworkperformance.
• Avoidserver‐sideCursorsasmuchaspossible,insteaduseSELECTstatement.Ifyou
needtousecursorthenreplaceitwithWHILEloop(orreadnextsuggestion).
• InsteadofusingLOOPtoinsertdatafromTableBtoTableA,trytouseSELECT
statementwithINSERTstatement.(ReadMoreHere)
INSERTINTOTableA(column1,column2)
SELECTcolumn1,column2
FROMTableB
WHERE….
![](asset-5.png)
5© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
• Avoidusingspaceswithinthenameofdatabaseobjects;thismaycreateissueswith
front‐enddataaccesstoolsandapplications.Ifyouneedspacesinyourdatabaseobject
namethenwillaccessingitsurroundthedatabaseobjectnamewithsquarebrackets.
Example:
[OrderDetails]
• Donotusereservedwordsfornamingdatabaseobjects,asthatcanleadtosome
unpredictablesituations.(ReadMoreHere)
• Practicewritingcommentsinstoredprocedures,triggersandSQLbatches,whenever
somethingisnotveryobvious,asitwon’timpacttheperformance.
• DonotusewildcardcharactersatthebeginningofwordwhilesearchusingLIKE
keywordasitresultsinIndexscan.
• Indentcodeforbetterreadability.(Example)
• WhileusingJOINsinyourSQLqueryalwaysprefixcolumnnamewiththetablename.
(Example).IfadditionallyrequirethenprefixTablenamewithServerName,
DatabaseName,DatabaseOwner.(Example)
• Defaultconstraintmustbedefinedatthecolumnlevel.Allotherconstraintsmustbe
definedatthetablelevel.(ReadMoreHere)
• Avoidusingrulesofdatabaseobjectsinsteaduseconstraints.
• DonotusetheRECOMPILEoptionforStoredProcedureasitreducestheperformance.
• AlwaysputtheDECLAREstatementsatthestartingofthecodeinthestoredprocedure.
Thiswillmakethequeryoptimizertoreusequeryplans.(Example)
• PuttheSETstatementsinbeginning(afterDECLARE)beforeexecutingcodeinthe
storedprocedure.(Example)
• UseBEGIN…ENDblocksonlywhenmultiplestatementsarepresentwithinaconditional
codesegment.(ReadMoreHere)
![](asset-6.png)
6© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
• Toexpressapostrophewithinastring,nestsinglequotes(twosinglequotes).
Example:
SET@sExample='SQL''sAuthority'
• Whenworkingwithbranchconditionsorcomplicatedexpressions,useparenthesisto
increasereadability.
Example:
IF((SELECT1
FROMTableName
WHERE1=2)ISNULL)
• Tomarksinglelineascommentuse(‐‐)beforestatement.Tomarksectionofcodeas
commentuse(/*...*/).
• Avoidtheuseofcrossjoinsifpossible.(ReadMoreHere)
• Ifthereisnoneedofresultsetthenusesyntaxthatdoesn’treturnaresultset.
IFEXISTS(SELECT1
FROMUserDetails
WHEREUserID=50)
Ratherthan,
IFEXISTS(SELECTCOUNT(UserID)
FROMUserDetails
WHEREUserID=50)
• UsegraphicalexecutionplaninQueryAnalyzerorSHOWPLAN_TEXTor
SHOWPLAN_ALLcommandstoanalyzeSQLqueries.Yourqueriesshoulddoan“Index
Seek”insteadofan“IndexScan”ora“TableScan”.(ReadMoreHere)
• Donotprefixstoredprocedurenameswith“SP_”,as“SP_”isreservedforsystem
storedprocedures.
Example:
SP<AppName>_[<GroupName>_]<Action><table/logicalinstance>
![](asset-7.png)
7© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
• Incorporateyourfrequentlyrequired,complicatedjoinsandcalculationsintoaviewso
thatyoudon’thavetorepeatthosejoins/calculationsinallyourqueries.Instead,just
selectfromtheview.(ReadMoreHere)
• Donotquery/manipulatethedatadirectlyinyourfrontendapplication,insteadcreate
storedprocedures,andletyourapplicationstoaccessstoredprocedure.
• Avoidusingntext,text,andimagedatatypesinnewdevelopmentwork.Usenvarchar
(max),varchar(max),andvarbinary(max)instead.
• Donotstorebinaryorimagefiles(BinaryLargeObjectsorBLOBs)insidethedatabase.
Instead,storethepathtothebinaryorimagefileinthedatabaseandusethatasa
pointertotheactualfilestoredonaserver.
• UsetheCHARdatatypeforanon‐nullablecolumn,asitwillbethefixedlengthcolumn,
NULLvaluewillalsoblockthedefinedbytes.
• AvoidusingdynamicSQLstatements.DynamicSQLtendstobeslowerthanstaticSQL,
asSQLServergenerateexecutionplaneverytimeatruntime.
• MinimizetheuseofNulls.Becausetheyincurmorecomplexityinqueriesandupdates.
ISNULLandCOALESCEfunctionsarehelpfulindealingwithNULLvalues
• UseUnicodedatatypes,likeNCHAR,NVARCHARorNTEXTifitneeded,astheyuse
twiceasmuchspaceasnon‐Unicodedatatypes.
• AlwaysusecolumnlistinINSERTstatementsofSQLqueries.Thiswillavoidproblem
whentablestructurechanges.
• Performallreferentialintegritychecksanddatavalidationsusingconstraintsinsteadof
triggers,astheyarefaster.Limittheuseoftriggersonlyforauditing,customtasks,and
validationsthatcannotbeperformedusingconstraints.
• Alwaysaccesstablesinthesameorderinallstoredprocedureandtriggersconsistently.
Thiswillavoiddeadlocks.(ReadMoreHere)
![](asset-8.png)
8© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
• Donotcallfunctionsrepeatedlyinstoredprocedures,triggers,functionsandbatches,
insteadcallthefunctiononceandstoretheresultinavariable,forlateruse.
• WithBeginandEndTransactionalwaysuseglobalvariable@@ERROR,immediately
afterdatamanipulationstatements(INSERT/UPDATE/DELETE),sothatifthereisan
Errorthetransactioncanberollback.
• ExcessiveusageofGOTOcanleadtohard‐to‐readandunderstandcode.
• DonotusecolumnnumbersintheORDERBYclause;itwillreducethereadabilityofSQL
query.
Example:WrongStatement
SELECT UserID,UserName,Password
FROM UserDetails
ORDERBY2
Example:CorrectStatement
SELECT UserID,UserName,Password
FROM UserDetails
ORDERBYUserName
• ToavoidtripsfromapplicationtoSQLServer,weshouldretrivemultipleresultsetfrom
singleStoredProcedureinsteadofusingoutputparam.
• TheRETURNstatementismeantforreturningtheexecutionstatusonly,butnotdata.If
youneedtoreturndata,useOUTPUTparameters.
• Ifstoredprocedurealwaysreturnssinglerowresultset,thenconsiderreturningthe
resultsetusingOUTPUTparametersinsteadofSELECTstatement,asADOhandles
OUTPUTparametersfasterthanresultsetsreturnedbySELECTstatements.
• Effectiveindexesareoneofthebestwaystoimproveperformanceinadatabase
application.
• BULKINSERTcommandhelpstoimportadatafileintoadatabasetableorviewin
auser‐specifiedformat.
![](asset-9.png)
9© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
• UsePolicyManagementtomakeordefineandenforceyourownpoliciesfro
configuringandmanagingSQLServeracrosstheenterprise,eg.PolicythatPrefixesfor
storedproceduresshouldbesp.
• Usesparsecolumnstoreducethespacerequirementsfornullvalues.(ReadMoreHere)
• UseMERGEStatementtoimplementmultipleDMLoperationsinsteadofwriting
separateINSERT,UPDATE,DELETEstatements.
• Whensomeparticularrecordsareretrievedfrequently,applyFilteredIndextoimprove
queryperformace,fasterretrievalandreduceindexmaintenancecosts.
• UsingtheNOLOCKqueryoptimizerhintisconsideredgoodpracticeinordertoimprove
concurrencyonabusysystem.
• EXCEPTorNOTEXISTclausecanbeusedinplaceofLEFTJOINorNOTINforbetter
peformance.
Example:
SELECT EmpNo,EmpName
FROM EmployeeRecord
WHERE Salary>1000ANDSalary
NOTIN(SELECT Salary
FROM EmployeeRecord
WHERE Salary>2000);
(Recomended)
SELECT EmpNo,EmpName
FROM EmployeeRecord
WHERE Salery>1000
EXCEPT
SELECT EmpNo,EmpName
FROM EmployeeRecord
WHERE Salery>2000
ORDERBY EmpName;