I.
Naming Conventions
The m ain goal of adopt ing a nam ing convent ion for dat abase obj ect s is so t hat you and ot her s can easily ident ify t he t ype and pur pose of all obj ect s cont ained in t he dat abase. The infor m at ion pr esent ed her e ser ves as a guide for you t o follow w hen nam ing your dat abase obj ect s. When r eading t hese r ules and guidelines, r em em ber t hat consist ent nam ing can be t he m ost im por t ant r ule t o follow . Please also keep in m ind t hat follow ing t he guidelines as out lined in t his docum ent can st ill pr oduce long and cr ypt ic nam es, but w ill lim it t heir num ber s and im pact . How ever , ult im at ely your unique sit uat ion w ill dict at e t he r easonabilit y of your nam ing convent ion. The goal of t his par t icular nam ing convent ion is t o pr oduce pr act ical, legible, concise, unam biguous and consist ent nam es for your dat abase obj ect s.
This sect ion is a gener ic DBMS- neut r al guide for nam ing com m on obj ect s. While m ost dat abases cont ain m or e t ypes of obj ect s t han t hose discussed her e ( User Defined Types, Funct ions, Quer ies, et c.) , t he 7 t ypes of obj ect s m ent ioned her e ar e com m on am ong all m aj or dat abase syst em s.
The follow ing t ypes of dat abase obj ect s ar e discussed her e:
1. Tables
2. Colum ns ( incl. Pr im ar y, For eign and Com posit e Keys) 3. I ndexes
4. Const r aint s 5. View s
6. St or ed Pr ocedur es 7. Tr igger s
• Tr y t o lim it t he nam e t o 50 char act er s ( shor t er is bet t er )
ALL D ATABASE OBJECTS
• Avoid using under scor es even if t he syst em allow s it , except w her e not ed in t his docum ent . PascalCase not at ion achieves t he sam e w or d separ at ion w it hout t hem and in few er char act ers.
• Use only let t er s or under scor es ( t r y t o avoid num ber s – and lim it t he use of under scor es t o m eet st andar ds for Const r aint s,
• Use a let t er as t he fir st char act er of t he nam e. ( don't st ar t nam es w it h under scor es or num ber s)
• Lim it t he use of abbr eviat ions ( can lead t o m isint er pr et at ion of nam es)
• Lim it t he use of acr onym s ( som e acr onym s have m or e t han one m eaning e.g. " ASP" )
• Make t he nam e r eadable ( t hey shouldn't sound funny w hen r ead aloud) .
• Avoid using spaces in nam es even if t he syst em allow s it .
1 . TABLES
When nam ing your dat abase t ables, giv e consider at ion t o ot her st eps in t he developm ent pr ocess. Keep in m ind you w ill m ost lik ely have t o ut ilize t he nam es you give your t ables sever al t im es as par t of ot her obj ect s, for exam ple, pr ocedur es, t r igger s or view s m ay all cont ain r eferences t o t he t able nam e. You w ant t o keep t he nam e as sim ple and shor t as possible. Som e syst em s enfor ce char act er lim it s on obj ect nam es also.
Ru le 1 a (Singular Nam es) - Table nam es should be singular , for exam ple, " Cust om er " inst ead of " Cust om er s" . This r ule is
applicable because t ables ar e pat t er ns for st or ing an ent it y as a r ecor d – t hey ar e analogous t o Classes ser ving up class inst ances. And if for no ot her r eason t han r eadabilit y , you avoid er r or s due t o t he
plur alizat ion of English nouns in t he pr ocess of dat abase developm ent . For inst ance, act ivit y becom es act iv it ies, ox becom es oxen, per son becom es people or per sons, alum nus becom es alum ni, w hile dat a r em ains dat a.
Ru le 1 b (Pr efixes
Do not give your t able nam es pr efixes like " t b" or " TBL_" as t hese ar e r edundant and w or dy. I t w ill be obvious w hich nam es ar e t he t able nam es in SQL st at em ent s because t hey w ill alw ays be pr eceded by t he FROM clause of t he SELECT st at em ent . I n addit ion, m any RDBMS adm inist r at ive and/ or quer y t ools ( such as SQL Ser ver Managem ent St udio) v isually separ at e com m on dat abase obj ect s in t he
developm ent envir onm ent . Also not e t hat Rule 5a pr ovides a m eans t o dist inguish view s fr om t ables.
I n som e cases, your t ables m ight be shar ing a schem a/ dat abase w it h ot her t ables t hat ar e not r elat ed in any w ay. I n t his case, it is
som et im es a good idea t o pr efix your t able nam es w it h som e char act er s t hat gr oup your t ables t oget her . For exam ple, for a healt hcar e applicat ion you m ight give y our t ables an " Hc" pr efix so t hat all of t he t ables for t hat applicat ion w ould appear in alphabet ized list s t oget her . Not e t hat even for t he pr efix, use PascalCase. This is discussed in Rule 1c. Do not use under scor es in your pr efix es, w hich is discussed in m or e dept h in Rule 1d. The last kind of pr efix t hat is
accept able is one t hat allow s you t o gr oup logical unit s of t ables. A plausible exam ple could ent ail a lar ge applicat ion ( 30 t o 40+ t ables) t hat handled bot h Payr oll and Benefit s dat a. You could pr efix t he t ables dealing w it h payr oll w it h a " Pay" or " Pr l" pr efix and give t he t ables dealing w it h benefit s dat a a " Ben" or " Bft s" pr efix. The goal of bot h t his pr efix and t he afor em ent ioned shar ed schem a/ dat abase pr efix is t o allow you t o gr oup specific t ables t oget her alphabet ically in list s and dist inguish t hem fr om unr elat ed t ables. Last ly, if a pr efix is used for t his pur pose, t he shar ed schem a/ dat abase pr efix is a higher gr ouping level and com es fir st in t he nam e, for exam ple,
" HcPayClient s" not " PayHcClient s" .
Ru le 1 c (Not at ion) - For all par t s of t he t able nam e, including pr efixes, use Pascal Case. Using t his not at ion w ill dist inguish your t able nam es fr om SQL keyw or ds ( cam elCase) . For exam ple, " select Cust om er I d, Cust om er Nam e fr om MyAppGr oupTable w her e
Cust om er Nam e = '% S'" show s t he not at ion for t he t able nam e
dist inguishing it fr om t he SQL keyw or ds used in t he quer y. PascalCase also r educes t he need for under scor es t o visually separ at e w or ds in nam es.
Ru le 1 e (Abbr eviat ions) - Avoid using abbr eviat ions if possible. Use " Account s" inst ead of " Acct s" and " Hour s" inst ead of " Hr s" . Not
ever yone w ill alw ay s agr ee w it h you on w hat your abbr eviat ions st and for - and - t his m ak es it sim ple t o r ead and under st and for bot h
developer s and non- developer s. This r ule can be r elaxed in t he sake of space const r aint s for j unct ion t able nam es ( See Rule 1f) . Avoid using acr onym s as w ell. I f except ions t o t his r ule ar e deem ed necessar y, ensur e t hat t he sam e convent ion is follow ed by all pr oj ect m em ber s.
Ru le 1 f (Junct ion a.k.a I nt er sect ion Tables) - Junct ion t ables, w hich handle m any t o m any r elat ionships, should be nam ed by
concat enat ing t he nam es of t he t ables t hat have a one t o m any r elat ionship w it h t he j unct ion t able. For exam ple, you m ight have " Doct or s" and " Pat ient s" t ables. Since doct or s can have m any pat ient s and pat ient s can have m any doct or s ( specialist s) you need a t able t o hold t he dat a for t hose r elat ionships in a j unct ion t able. This t able should be nam ed Doct or Pat ient " . Since t his convent ion can r esult in lengt hy t able nam es, abbr eviat ions som et im es m ay be used at your discr et ion.
2 . COLUM N S
- (incl. PRI MARY, FOREI GN, AND COMPOSI TE KEYS) When nam ing your colum ns, keep in m ind t hat t hey ar e m em ber s of t he t able, so t hey do not need t he any m ent ion of t he t able nam e in t he nam e. When w r it ing a quer y against t he t able, you should be pr efixing t he field nam e w it h t he t able nam e or an alias anyw ay. Just like w it h nam ing t ables, avoid using abbr eviat ions, acr ony m s or special char act er s. All colum n nam es should use PascalCase t o dist inguish t hem fr om SQL key w or ds ( cam elCase) .Ru le 2 a (I dent it y Pr im ar y Key Fields) - For fields t hat ar e t he pr im ar y key for a t able and uniquely ident ify each r ecor d in t he t able, t he nam e should sim ply be [ t ableNam e] + “ I d“ ( e.g.in a Cust om er t able, t he pr im ar y key field w ould be “ Cust om er I d” . A pr efix is added
m ainly because “ I d” is a keyw or d in SQL Ser ver and w e w ould have t o w r ap it in br acket s w hen r eferencing it in quer ies ot her w ise. Though Cust om er I d conveys no m or e infor m at ion about t he field t han
Cust om er .I d and is a far w or dier im plem ent at ion, it is st ill pr efer able t o having t o t ype br acket s ar ound “ I d” .
kept , it w ould also be " Cust om er I d" . Ther e is one except ion t o t his r ule, w hich is w hen you have m or e t han one for eign key field per t able r eferencing t he sam e pr im ar y key field in anot her t able. I n t his
sit uat ion, it m ight be helpful t o add a descr ipt or befor e t he field nam e. An exam ple of t his is if you had an Addr ess t able. You m ight
have anot her t able w it h for eign key fields like Hom eAddr essI d, Wor kAddr essI d, MailingAddr essI d, or ShippingAddr essI d.
This r ule com bined w it h r ule 2a m akes for m uch m or e r eadable SQL:
... File inner j oin Dir ect or y on File.FileI D = Dir ect or y.FileI D ...
w her eas t his has a lot of r epeat ing and confusing infor m at ion:
... File inner j oin Dir ect or y on File.FileI d_Pk = Dir ect or y.FileI d_Fk ...
Ru le 2 c (Com posit e Keys) - I f you hav e t ables w it h com posit e keys ( m or e t han one field m akes up t he unique value) , it ’s r ecom m ended t hat a seeded ident it y colum n is cr eat ed t o use as t he pr im ar y key for t he t able.
Ru le 2 d (Pr efixes) - Do not pr efix your fields w it h " fld_" or " Col_" as it should be obvious in SQL st at em ent s w hich it em s ar e colum ns ( befor e or aft er t he FROM clause) . Do not use a dat a t ype pr efix for t he field eit her , for exam ple, " I nt Cust om er I d" for a num er ic t y pe or " VcNam e" for a var char t ype. These “ clog up” our nam ing and add lit t le value; m ost int eger fields can be easily ident ified as such and char act er fields w ould have t o be checked for lengt h in t he Obj ect Br ow ser anyw ay.
Ru le 2 e (Dat a Type- Specific Nam ing) - Bit fields should be given affir m at ive boolean nam es like " I sDelet ed" , " HasPer m ission" , or
" I sValid" so t hat t he m eaning of t he dat a in t he field is not am biguous; negat ive boolean nam es ar e har der t o read w hen checking values in T-SQL because of double- negat ives ( e.g. “ Not I sNot Delet ed” ) . I f t he field holds dat e and/ or t im e infor m at ion, t he w or d " Dat e" or " Tim e" should appear som ew her e in t he field nam e. I t is som et im es
appr opr iat e t o add t he unit of t im e t o t he field nam e also, especially if t he field holds dat a like w hole num ber s ( " 3" or " 20" ) . Those fields should be nam ed lik e " Runt im eHour s" or " ScheduledMinut es" .
Ru le 2 g (Special Char act er s) – Field nam es should cont ain only let t er s and num ber s. No special char act er s, under scor es or spaces should be used.
3 . I N D EXES
I ndexes w ill r em ain nam ed as t he SQL Ser ver default , unless t he index cr eat ed is for a special pur pose. All pr im ar y key fields and for eign key fields w ill be indexed and nam ed in t he SQL Ser ver default . Any ot her index w ill be given a nam e indicat ing it ’s pur pose.
Ru le 3 a (Nam ing Convent ion
w her e " U/ N" is for unique or non- unique and " I X_" m at ches t he default pr efix t hat SQL Ser ver assigns indexes.
) – I ndexes w ill r em ain nam ed as t he SQL Ser ver default , unless t he index cr eat ed is for a special pur pose, in w hich case t he nam ing convent ion for special- pur pose indexes follow s t his st r uct ur e:
{ U/ N} I X_{ TableNam e} { SpecialPur pose}
Ru le 3 b (Pr efixes and Suffixes) - Avoid put t ing any pr efix ot her t han t hat specified in Rule 3a befor e your special- pur pose index es..
4 . CON STRAI N TS
Const r aint s ar e at t he field/ colum n level so t he nam e of t he field t he const r aint is on should be used in t he nam e. The t ype of const r aint ( Check, Refer ent ial I nt egr it y a.k .a For eign Key, Pr im ar y Key, or Unique) should be not ed also. Const r aint s ar e also unique t o a
par t icular t able and field com binat ion, so you should include t he t able nam e also t o ensur e unique const r aint nam es acr oss your set of dat abase t ables.
Ru le 4 a (Nam ing Convent ion) - The nam ing convent ion sy nt ax for const r aint s looks lik e t his:
{ const r aint t ype} { t able nam e} _{ field nam e}
Exam ples:
1. PkPr oduct s_I d - pr im ar y key const r aint on t he I d field of t he Pr oduct s t able
2. FkOr der s_Pr oduct I d - for eign key const r aint on t he Pr oduct I d field in t he Or der s t able
field in t he Cust om er s t able
The r eason under scor es ar e used here w it h Pascal Case not at ion is so t hat t he t able nam e and field nam e ar e clear ly separ at ed. Wit hout t he under scor e, it w ould becom e easy t o get confused about w her e t he t able nam e st ops and t he field nam e st ar t s.
Ru le 4 b (Pr efixes) A t w o let t er pr efix get s applied t o t he const r aint nam e depending on t he t ype
Pr im ar y Key: Pk For eign Key: Fk Check: Ck
Unique: Un
5 . VI EW S
View s follow m any of t he sam e r ules t hat apply t o nam ing t ables. Ther e are only t w o differ ences ( Rules 5a and 5b) . I f your v iew com bines ent it ies w it h a j oin condit ion or w her e clause, be sur e t o com bine t he nam es of t he ent it ies t hat ar e j oined in t he nam e of your view . This is discussed in m or e dept h in Rule 5b.
Ru le 5 a (Pr efixes) - While it is point less t o pr efix t ables, it can be helpful for view s. Pr efixing your view s w it h " vw " is a helpful r em inder t hat you'r e dealing w it h a view , and not a t able. What ever t ype of pr efix you choose t o apply , use at least 2 let t er s and not j ust " v" because a pr efix should use m or e t han one let t er or it s m eaning can be am biguous.
Ru le 5 b (View Types) - Som e view s ar e sim ply t abular
r epr esent at ions of one or m or e t ables w it h a filt er applied or because of secur it y pr ocedur es ( user s given per m issions on view s inst ead of t he under ly ing t able( s) in som e cases) . Som e view s ar e used t o gener at e r epor t dat a w it h m or e specific values in t he WHERE clause. Nam ing your view s should be differ ent depending on t he t y pe or
6 . STORED PROCED URES
Unlike a lot of t he ot her dat abase obj ect s discussed her e, st or ed pr ocedur es ar e not logically t ied t o any t able or colum n. Ty pically t hough, st or ed pr ocedur es per for m one or m or e com m on dat abase act iv it ies ( Read, I nser t , Updat e, and/ or Delet e) on a t able, or anot her act ion of som e k ind. Since st or ed pr ocedur es alw ays per for m som e t ype of oper at ion, it m akes sense t o use a nam e t hat descr ibes t he oper at ion t hey per for m . Use a ver b t o descr ibe t he t y pe of oper at ion, follow ed by t he t able( s) t he oper at ions occur on.
Ru le 6 a (Pr efixes or Suffixes
I f your pr ocedur e r et ur ns a scalar value, or per for m s an oper at ion like validat ion, you should use t he ver b and noun com binat ion. For
exam ple, " Validat eLogin" .
) - The w ay you nam e your st or ed
pr ocedur es depends on how you w ant t o gr oup t hem w it hin a list ing. I t is r ecom m ended t hat you have your pr ocedur es or der ed by t he
t able/ business ent it y t hey per for m a dat abase oper at ion on, and adding t he dat abase act ivit y " Get , Sav e, or Delet e" as a suffix , e.g., ( " Pr oduct I nfoGet " or " Or der sSave" ) or ( " spPr oduct I nfoGet " or
" spOr der sSave" ) .
The use of t he “ sp” pr efix is accept able and encour aged. This w ill help developer s ident ify st or ed pr ocedur es and differ ent iat e t hem fr om ot her non pr efixed obj ect s such as t ables w hen view ing a list ing of dat abase obj ect s.
Ru le 6 b (Gr ouping Pr efixes) - I f you have m any st or ed pr ocedur es, you m ight w ant t o consider using a gr ouping pr efix t hat can be used t o ident ify w hich par t s of an applicat ion t he st or ed pr ocedur e is used by . For exam ple, a " Pr l" pr efix for Payr oll r elat ed pr ocedur es or a " Hr " pr efix for Hum an Resour ces r elat ed pr ocedur es can be helpful. This pr efix w ould com e befor e t he t able/ business ent it y pr efix ( See Rule 6a) . Please not e t hat t his should be av oided unless absolut ely necessar y.
Ru le 6 c (Bad Pr efix es) - Do not pr efix your st or ed pr ocedur es w it h som et hing t hat w ill cause t he syst em t o t hink it is a syst em pr ocedur e. For exam ple, in SQL Ser ver , if you st ar t a pr ocedur e w it h " sp_" , " xp_" or " dt _" it w ill cause SQL Ser ver t o check t he m ast er dat abase for t his pr ocedur e fir st , causing a per for m ance hit . Spend a lit t le t im e
7 . FUN CTI ON S
Funct ions follow m any of t he sam e r ules t hat apply t o nam ing st or ed pr ocedur es. Ther e ar e only t w o differ ences ( Rules 5a and 5b) t hat exist so t he user of t he funct ion k now s t hey ar e dealing w it h a funct ion and not a st or ed pr ocedur e and all of t he det ails t hat involves ( value r et ur ned, can be used in a select st at em ent , et c.) .
Ru le 7 a (Pr efixes) - While it is m akes lit t le sense t o pr efix st or ed pr ocedur es, it is necessar y t o dist inguish funct ions fr om st or ed
pr ocedur es. To t hat end, you should pr efix your funct ions w it h " fn" as a helpful r em inder t hat you'r e dealing w it h a funct ion, and not a st or ed pr ocedur e.
Ru le 7 b (Funct ion Pur pose
Rule 7c ( Funct ion Suffix ) – Scalar funct ions do not need a suffix , but t able- valued funct ions should indicat e t hat t hey r et ur n a t able by using a “ Table” suffix.
) – Funct ions should be nam ed as a ver b, because t hey w ill alw ays r et ur n a value ( e.g. “ fnGet OpenDat e” , “ fnPar seTableToSt r ing” , “ fnFor m at Zip” , et c.) .
8 . TRI GGERS
Tr igger s have m any t hings in com m on w it h st or ed pr ocedur es. How ever , t r igger s ar e differ ent t han st or ed pr ocedur es in t w o im por t ant w ays. Fir st , t r igger s don't ex ist on t heir ow n. They ar e dependent upon a t able. So it is w ise t o include t he nam e of t his t able in t he t r igger nam e. Second, t r igger s can only execut e w hen an I nser t , Updat e, or Delet e happens on one or m or e of t he r ecor ds in t he t able. So it also m akes sense t o include t he t ype of act ion t hat w ill cause t he t r igger t o execut e.
Ru le 8 a (Pr efixes) - To dist inguish t r igger s fr om ot her dat abase obj ect s, it is helpful t o add " t r " as a pr efix, e.g. “ t r _Pr oduct sI ns” . As long as you include t he t able nam e, t he oper at ion t hat execut es t he t r igger ( I ns, Upd, or Del) and t he " t r " pr efix, it should be obvious t o som eone w or king w it h t he dat abase w hat kind of obj ect it is. As w it h all convent ions you use, pick one and r em ain consist ent .
Ru le 8 b (Mult iple Oper at ions) - I f a t r igger handles m or e t han one oper at ion ( bot h I NSERT and UPDATE for exam ple) t hen include bot h oper at ion abbr eviat ions in your nam e. For exam ple,
Ru le 8 c (Mult iple Tr igger s) - Som e syst em s allow m ult iple t r igger s per oper at ion per t able. I n t his case, you should m ake sur e t he nam es of t hese t r igger s ar e easy t o dist inguish bet w een, e.g.
" t r User s_Validat eEm ailAddr ess_I ns" and " t r User s_MakeAct ionEnt r ies_I ns" .
9 . Use r - D e fin e d D a t a Type s
User - defined dat a t ypes should be avoided w henever possible. They ar e an added pr ocessing over head w hose funct ionalit y could t ypically be accom plished m or e efficient ly w it h sim ple dat a t ype var iables, t able var iables, or t em por ar y t ables.
Ru le 9 a (Pr efixes and Suffixes) - To dist inguish a user - defined dat a t ype fr om ot her dat abase obj ect s, it is helpful t o add " ud" as a pr efix.
Ru le 9 b (Special Char act er s) – User - defined dat a t ype nam es should cont ain only let t er s, num ber s and under scor es. No special char act er s or spaces should be used.
1 0 . Va r ia ble s
I n addit ion t o t he gener al nam ing st andar ds r egar ding no special char act er s, no spaces, and lim it ed use of abbr eviat ions and acr onym s, com m on sense should pr evail in nam ing var iables; var iable nam es should be m eaningful and nat ur al.
Ru le 1 0 a (Nam e lengt h lim it) – Var iable nam es should descr ibe it s pur pose and not ex ceed 50 char act er s in lengt h.
Ru le 1 0 b (Pr efix) – All var iables m ust begin w it h t he “ @” sym bol. Do NOT user “ @@” t o pr efix a var iable as t his signifies a SQL Ser ver syst em global var iable and w ill affect per for m ance.
Ru le 1 0 c (Case) – All var iables should be w r it t en in cam elCase, e.g. “ @fir st Nam e” or “ @cit y” or “ @sit eI d” .
Ru le 1 0 d (Special Char act er s
1 1 . Usin g M odu la r Pr e fix e s
) – Var iable nam es should cont ain only let t er s and num ber s. No special char act er s or spaces should be used.
and view s. This m et hodology involves ident ify ing pr im ar y m odules of t he syst em and assigning each of t hose m odules a pr efix. When t hese pr efixes ar e applied t o t he nam es of dat abase obj ect s t his allow s us t o easily locat e m odule specific pr ocedur es and dat abase obj ect s for easier m odificat ion and debugging.
Ex a m ple 1 :
We have a m odular syst em t hat deals w it h st udent s and t eacher dat a separ at ely. We hav e defined t hese m odules as such:
M odu le N a m e Pr e fix
St udent STU
Teacher TEA
As w e im plem ent nam ing convent ions for our new obj ect s pr ocessing specific t o each m odule w e cr eat e an easier w ay t o find and view m odule specific funct ionalit y .
spSTU_At t endance_I nser Updat e spTEA_Cr edent ials_Delet e
spSTU_Validat eSt udent I D spTEA_Addr ess_I nser t Updat e spSTU_Addr ess_I nser t Updat e vw STU_AllSt udent s
Ex a m ple 2 :
Should you find t he need for even m or e gr anular it y w hen
im plem ent ing your nam ing convent ions, consider using sub- m odules as w ell.
M odu le N a m e Pr e fix
Repor t ing RPT
Dat a Collect ion DTA
Su b M odu le N a m e Pr e fix
St udent STU
Teacher TEA
spDTA_STU_At t endance_I nser Updat e spDTA_TEA_Cr edent ials_Delet e
spDTA_STU_Addr ess_I nser t Updat e vw DTA_STU_Validat eSt udent
II. Coding Conventions
1 . SQL St a t e m e n t s ( Se le ct s)
The fir st of t he follow ing t w o quer ies show s t he old st yle j oin, w hile t he second one show s t he new ANSI j oin sy nt ax:
Use t he m or e r eadable ANSI - St andar d Join clauses ( SQL- 92 synt ax ) inst ead of t he old st yle j oins ( SQL- 89 sy nt ax) . The older synt ax ( in w hich t he WHERE clause handles bot h t he j oin condit ion and filt er ing dat a) is being phased out SQL Ser ver 2005 and higher ver sions. Th is “old st yle ” w a y of j oin in g t a ble s w ill N OT be su ppor t e d in
fu t u r e ve r sion s of SQL Se r ve r .
SELECT a.AuthorId, t.Title
FROM Titles t, Authors a, TitleAuthor ta
WHERE
a.AuthorId = ta.AuthorId AND ta.TitleId = t. TitleId AND t.Title LIKE '%Computer%'
SELECT
a.AuthorId, t.Title
FROM dbo.Authors a
INNER JOIN dbo.TitleAuthor ta ON a.AuthorId = ta.AuthorId
INNER JOIN dbo.Titles t ON
ta.TitleId = t.TitleId
WHERE
t.Title LIKE '%Computer%'
Do not use t he “ Select * ” convent ion w hen gat her ing r esult s fr om a per m anent t able, inst ead specify t he field nam es and br ing back only t hose fields you need; t his opt im izes quer y per for m ance and
elim inat es t he possibilit y of unexpect ed r esult s w hen fields ar e added t o a t able.
Pr efix all t able nam e w it h t he t able ow ner ( in m ost cases “ dbo.” ) . This r esult s in a per for m ance gain as t he opt im izer does not have t o
Use aliases for your t able nam es in m ost T- SQL st at em ent s; a useful convent ion is t o m ake t he alias out of t he fir st or fir st t w o let t er s of each capit alized t able nam e, e.g. “ Sit e” becom es “ s” and “ Sit eType” becom es “ st ” .
2 . SQL St a t e m e n t s ( I n se r t s)
Consider t he follow ing t able:
Alw ays use a colum n list in your I NSERT st at em ent s. This helps in avoiding pr oblem s w hen t he t able st r uct ur e changes ( like adding or dr opping a colum n) . Her e's an exam ple t hat show s t he pr oblem .
CREATE TABLE EuropeanCountries (
CountryID int PRIMARY KEY, CountryName varchar(25) )
Her e's an I NSERT st at em ent w it hout a colum n list , t hat w or ks per fect ly:
INSERT INTO EuropeanCountries
SELECT 1, 'Ireland'
Now , let 's add a new colum n t o t his t able:
ALTER TABLE EuropeanCountries
ADD EuroSupport bit
Now if you r un t he above I NSERT st at em ent . You get t he follow ing er r or fr om SQL Ser ver :
Server: Msg 213, Level 16, State 4, Line 1
Insert Error: Column name or number of supplied values does not match table definition.
This pr oblem can be avoided by w r it ing an I NSERT st at em ent w it h a colum n list as show n below :
INSERT INTO EuropeanCountries (CountryID, CountryName)
SELECT 1, 'England'
3 . SQL St a t e m e n t s ( For m a t t in g)
easy-t o- r ead chunk s, m or e com plicaeasy-t ed seasy-t aeasy-t em eneasy-t s ar e ver y har d easy-t o decipher . By doing t his and aliasing t able nam es w hen possible, you w ill m ake colum n addit ions and m aint enance of quer ies m uch easier . Refer t o t he exam ples below .
Confusing SQL:
SELECT dbo.DealUnitInvoice.DealUnitInvoiceID,
dbo.DealUnitInvoice.UnitInventoryID, dbo.UnitInventory.UnitID,
dbo.UnitInventory.StockNumber AS [Stock Number], dbo.UnitType.UnitType
AS [Unit Type], ISNULL(dbo.Make.Description, '') AS Make,
ISNULL(dbo.Model.Description, '') AS Model, DATEPART(YEAR, dbo.Unit.ProductionYear) AS [Year], dbo.UnitType.UnitTypeID,
dbo.MeterType.Description AS MeterType, dbo.UnitInventory.MeterReading, dbo.UnitInventory.ECMReading, '$' + LTRIM(CONVERT(nvarchar(18),
CAST(dbo.DealUnitInvoice.Price AS decimal(18, 2)))) AS Price, '$' +
LTRIM(CONVERT(nvarchar(18), CAST(dbo.DealUnitInvoice.Cost AS decimal(18, 2))))
AS Cost, dbo.DealUnitInvoice.IsTradeIn, ISNULL(dbo.Unit.Vin, '') AS
Vin, ISNULL(dbo.Unit.SerialNumber, '') AS SerialNumber, dbo.UnitInventory.AvailabilityStatusID,
dbo.Unit ON dbo.UnitInventory.UnitID = dbo.Unit.UnitID LEFT OUTER JOIN dbo.MeterType ON dbo.Unit.MeterTypeID = dbo.MeterType.MeterTypeID LEFT OUTER JOIN
dbo.UnitType ON dbo.UnitInventory.UnitTypeID = dbo.UnitType.UnitTypeID AND dbo.UnitType.InActive = 0 LEFT OUTER JOIN
DELETE FROM MyTable
GO
5 . Code Com m e n t in g
St or ed pr ocedur es and funct ions should include at a m inim um a header com m ent w it h a br ief over view of t he bat ches funct ionalit y. I m por t ant code blocks w it hin st or ed pr ocedur es and user defined funct ions should be com m ent ed. Br ief funct ionalit y descr ipt ions should be included w her e im por t ant or com plicat ed pr ocessing is t aking place.
Com m ent synt ax:
-- single line comment use 2 dashes (--)
/*
block comments use ( /* ) to begin and ( */ ) to close
*/
Block com m ent s ar e pr efer red t o single line com m ent s ( even for com m ent ing a single line) as cut and past e oper at ions m ay dislocat e t he double- dash single line com m ent , w her eas t he block com m ent s can never be dislocat ed.
6 . Usin g Code H e a de r s
St or ed pr ocedur es, t r igger s and user - defined funct ions should have a code header . The header can be cr eat ed using t he com m ent synt ax above. This header should give a br ief descr ipt ion of t he funct ionalit y of t he pr ocedur e as w ell as any special execut ion inst r uct ions. Also cont ained in t his header t her e should be a br ief definit ion of any
par am et er s used. Refer t o t he exam ple below . You m ay also include an execut ion exam ple of t he funct ion or pr ocedur e in t he header as w ell.
CREATE PROCEDURE [dbo].[spGBL_ValidateConcurrency] @TableName varchar(255),
@ID int,
@LastUpdate datetime, @IsValid bit OUTPUT AS
/*********************************************************
This procedure validates the concurrency of a record update by taking the LastUpdate date passed in and checking it against the current LastUpdate date of the record. If they do NOT match the record is not updated because someone has updated the record out from under
--- Parameter Definition:
--- @TableName = Table to be validated.
@ID = Record ID of the current record to be validated.
@LastUpdate = The Last Update Date passed by app to compare with current date value for the record.
@IsValid = Returns the following back to the calling app. 1 = Record is valid. No concurrancy issues.
0 = Record is NOT concurrent.
*********************************************************/
7 . Un icode vs. N on - Un icode D a t a Type s
Use Unicode dat a t y pes, like NCHAR, NVARCHAR, or NTEXT, ONLY if your dat abase is going t o st or e not j ust plain English char act er s, but a var iet y of char act er s used all over t he w or ld. Use t hese dat a t y pes only w hen t hey ar e absolut ely needed as t hey use t w ice as m uch space as non- Unicode dat a t ypes.
8 . CH AR vs. VARCH AR D a t a Type s
Use t he CHAR dat a t ype for a colum n only w hen t he colum n is non-nullable. I f a CHAR colum n is nullable, it is t r eat ed as a fixed lengt h colum n in SQL Ser ver 7.0+ . So, a CHAR( 100) , w hen NULL, w ill eat up 100 byt es, r esult ing in space w ast age. So, use VARCHAR( 100) in t his sit uat ion. Of cour se, var iable lengt h colum ns do have a ver y lit t le pr ocessing over head over fixed lengt h colum ns. Car efully choose bet w een CHAR and VARCHAR depending up on t he lengt h of t he dat a you ar e going t o st or e.
9 . Ve r y La r ge St r in gs
I f you don't have t o st or e m or e t han 8KB of t ext , use CHAR( 8000) or VARCHAR( 8000) dat a t y pes. I f, how ever , ( and only if) you find t hat you need t o cr eat e a field t o be sized t o accom m odat e st r ing or binar y dat a > 8KB, t hen use t he VARCHAR( MAX) or VARBI NARY( MAX) dat a t ypes r espect ively . They ar e fully int egr at ed w it h nat ive T- SQL funct ions and do not r equir e special funct ions like t he old TEXT dat a t ypes did.
1 0 . D a t a Acce ss a n d Tr a n sa ct ion s
Never , ever w ait for user input in t he m iddle of a t r ansact ion. Do not use higher level locking hint s or r est r ict ive isolat ion levels unless t hey ar e absolut ely needed. Make your fr ont - end applicat ions deadlock-int elligent , t hat is, t hese applicat ions should be able t o r esubm it t he t r ansact ion in case t he pr evious t r ansact ion fails w it h er r or 1205. I n your applicat ions, pr ocess all t he r esult s r et ur ned by SQL Ser ver im m ediat ely so t hat t he locks on t he pr ocessed r ow s are r eleased, hence no blocking.
Alw ays check t he global var iable @@ERROR im m ediat ely aft er execut ing a dat a m anipulat ion st at em ent ( like
I NSERT/ UPDATE/ DELETE) , so t hat you can r ollback t he t r ansact ion in case of an er r or ( @@ERROR w ill be gr eat er t han 0 in case of an er r or ) . This is im por t ant , because, by default , SQL Ser ver w ill not r ollback all t he pr evious changes w it hin a t r ansact ion if a par t icular st at em ent fails. Execut ing SET XACT_ABORT ON can change t his behavior . The @@ROWCOUNT variable also play s an im por t ant r ole in det er m ining how m any r ow s w er e affect ed by a pr ev ious dat a m anipulat ion ( also, r et r ieval) st at em ent , and based on t hat you could choose t o com m it or r ollback a par t icular t r ansact ion.
Sam ple t r ansact ion:
declare @sql_error int set @sql_error = 0
begin transaction
update dbo.tbCacLic
set
sintLicCapacity = source.sintNewLicCapacity, chrLastUpdtId = 'myLogin',
dtmLastUpdt = getDate()
from
dbo.tbCacLic as target
inner join #dcfsOldLic as source
on target.intAplySiteId = source.intAplySiteId
select @sql_error = @@error
if @sql_error = 0
begin
commit transaction drop table #dcfsOldLic
end else begin
1 2 . Er r or H a n dlin g
- Tally er r or s. Rollback if failur e occur s anyw her e in pr oc.
CREATE PROCEDURE dbo.spDoStuff
Alt hough som e pr ocedur al pr ocesses m ay not r equir e addit ional er r or handling, as show n above in t he Dat a Access and Tr ansact ions sect ion t her e m ay be inst ances w it hin your st or ed pr ocedur es you w ish t o handle er r or s m or e gr acefully . You can use er r or handling t o r ollback ent ir e t r ansact ions if one piece fails, r epor t a single failed pr ocess w it hin a pr ocedur e back t o t he calling applicat ion…et c. Ther e ar e som e exam ples below of pr oper im plem ent at ion of er r or handling w it hin a SQL Ser ver st or ed pr ocedur e.
SQL Ser ver 7.0 – 9.0( 2005) – Use t his m et hodology t o handle er r or s in ver sions pr evious t o SQL 2008 ( 10.0) .
@var1 int
AS
SET NOCOUNT ON
--declare/initialize error counter
DECLARE @err int SELECT @err = 0
BEGIN TRAN
DELETE FROM MyTable
WHERE Col1 = @var1
SET @err = @err + @@ERROR
INSERT INTO MyOtherTable(Col1)
SELECT @var1
SET @err = @err + @@ERROR
IF @err = 0
BEGIN
COMMIT TRAN RETURN 0
END ELSE BEGIN
ROLLBACK TRAN RETURN @err
END
- End pr ocessing w hen er r or is r eached and r et ur n er r or t o applicat ion.
CREATE PROCEDURE dbo.spDoStuff @var1 int
AS
SET NOCOUNT ON
DECLARE @err int
BEGIN TRAN
DELETE FROM MyTable
WHERE Col1 = @var1
SET @err = @err + @@ERROR IF @err > 0 GOTO ERROR_HDLR
INSERT INTO MyOtherTable(Col1)
SELECT @var1
SET @err = @err + @@ERROR IF @err > 0 GOTO ERROR_HDLR
GOTO END_PROC
-- Handle Errors
ERROR_HDLR:
ROLLBACK TRANSACTION RETURN @err
-- Return & Exit
END_PROC:
COMMIT TRANSACTION RETURN 0
SQL Ser ver 10.0( 2008) and gr eat er – SQL ver sion 10.0 has added Tr y/ Cat ch funct ionalit y and new funct ions t o r epor t er r or st at us t o enhance er r or handling. You m ay im plem ent t his m et hodology w hen developing in SQL 10.0 or higher . Exam ple( s) below .
CREATE PROCEDURE dbo.spDoStuff @var1 int
AS
SET NOCOUNT ON BEGIN TRY
BEGIN TRAN
DELETE FROM MyTable
WHERE Col1 = @var1
INSERT INTO MyOtherTable(Col1)
SELECT @var1
COMMIT TRANSACTION END TRY
GO
BEGIN CATCH
SELECT
ERROR_NUMBER() as ErrorNumber, ERROR_MESSAGE() as ErrorMessage -- Test XACT_STATE for 1 or -1.
-- XACT_STATE = 0 means there is no transaction and
-- Test whether the transaction is uncommittable. IF (XACT_STATE()) = -1
BEGIN
N'The transaction is in an uncommittable state. ' + 'Rolling back transaction.'
ROLLBACK TRAN
END
-- Test whether the transaction is active and valid. IF (XACT_STATE()) = 1
BEGIN
N'The transaction is committable. ' + 'Committing transaction.'
COMMIT TRAN
END END CATCH
1 3 . For e ign Ke y a n d Ch e ck Con st r a in t s
Per for m all your r efer ent ial int egr it y checks and dat a validat ions using const r aint s ( for eign key and check const r aint s) inst ead of t r igger s, as t hey ar e fast er . Lim it t he use t r igger s only for audit ing, cust om t asks and validat ions t hat cannot be per for m ed using const r aint s.
Const r aint s save you t im e as w ell, as y ou don't have t o w r it e code for t hese validat ions, allow ing t he RDBMS t o do all t he w or k for you. Unique for eign key const r aint s should ALWAYS be enfor ced acr oss alt er nat e keys w henever possible. Not enfor cing t hese const r aint s w ill com pr om ise dat a int egr it y.
1 4 . Cu r sor Usa ge
Should t he need ar ise w her e cur sor s are t he only opt ion, avoid using dynam ic and updat e cur sor s. Make sur e you define your cur sor s as local, for w ar d only t o incr ease per for m ance and decr ease over head. Tr y t o avoid ser ver side cur sor s as m uch as possible. Alw ay s st ick t o a 'set - based appr oach' inst ead of a 'pr ocedur al appr oach' for accessing and m anipulat ing dat a. Cur sor s can oft en be avoided by using SELECT st at em ent s inst ead or at w or st , t em por ar y t ables and/ or t able
var iables.
Sam ple Cur sor :
DECLARE @var1 int
SELECT Col2
FROM MyTable1
WHERE Col1 = 5
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @var1
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN
DELETE FROM MyTable2
WHERE Col1 = @var1
END
FETCH NEXT FROM MyCursor INTO @var1
END
CLOSE MyCursor
DEALLOCATE MyCursor
1 5 . Te m por a r y Ta ble s a n d Ta ble Va r ia ble s
Use t em por ar y t ables ( e.g. # NslClaim s) only w hen absolut ely necessar y. When t em por ar y st or age is needed w it hin a T- SQL st at em ent or pr ocedur e, it ’s r ecom m ended t hat you use local t able var iables ( e.g. @NslClaim s) inst ead if t he am ount of dat a st or ed is r elat ively sm all. This elim inat es unnecessar y locks on sy st em t ables and r educes t he num ber of r ecom piles on st or ed pr ocedur es. This also incr eases per for m ance as t able var iables ar e cr eat ed in RAM, w hich is significant ly fast er t han physical disk. You can incr ease per for m ance on t em por ar y t ables and t able var iables in som e inst ances by applying indexes. How ever , SQL 2005 and gr eat er handles indexes on t em p t ables and var iables m uch bet t er t han SQL 2000. Also keep in m ind t hat w hen using indexes it can decr ease per for m ance on inser t s and updat es so use caut ion w hen choosing indexed colum ns.
1 6 . Pa r a m e t e r Sn iffin g – Be W a r n e d
suggest only using t his w her e you find pr oblem s w it h par am et er sniffing.
CREATE PROCEDURE dbo.spDoStuff @var1 int,
@var2 varchar(20)
AS
SET NOCOUNT ON
---Bypass parameter sniffing--
DECLARE @var1a int, @var2a varchar(20)
SELECT @var1a = @var1, @var2a = @var2
---end bypass---
SELECT *
FROM MyTable
WHERE col1 = @var1a and col2 = @var2a
1 7 . D a t a ba se D e sign – Be st Pr a ct ice s
• Ut ilize enfor ced r elat ionships bet w een t ables t o pr ot ect dat a int egr it y w hen possible. Alw ays r em em ber ...gar bage
in....gar bage out . The dat a w ill only ev er be as good as t he int egr it y used t o st or e it .
Using SQL Ser ver s RDBMS plat for m t o it s fullest pot ent ial is
encour aged. Below ar e a few t ips t o aide in m ax im izing t he built in feat ur es of r elat ional dat abase st r uct ur es.
• Take car e t o nor m alize dat a as m uch as possible w hile st ill achieving peak per for m ance and m aint ainabilit y. Over
-nor m alizat ion can also be an issue as it can have a sever e effect on per for m ance and dat a m aint enance and cause un- needed over head. Ent it ies and t heir pr oposed uses should be st udied t o for m ulat e a dat a m odel t hat can balance int egr it y , scalabilit y and per for m ance.
• Make use of aut o- num ber ed sur r ogat e keys on all t ables. This can r educe dat a st or age w her e com pound pr im ar y and for eign keys ar e pr evalent and sim plify r elat ionships bet w een dat a w hen nor m alizing dat a st r uct ur es and w r it ing quer ies.
index) alw ays put a pr im ar y key on a t able. Tables w it h no pr im ar y key ar e a pr oblem w ait ing t o happen.
• Ut ilize indexes and fill fact or s cor r ect ly. Not hing can speed up dat a t hr oughput m or e t han cor r ect ut ilizat ion of clust er ed indexes, r egular indexes and fill fact or s. This can be t r icky business but SQL Ser ver has a sm all host of t ools t hat can assist . Not hing bet t er t han exper ience w hen it com es t o opt im izing quer ies and inser t / updat e per for m ance. I f you ar e unsur e how t o pr oceed w it h opt im izat ions consult t he DBA.
• Dat abase secur it y is alw ays a concer n. I SBE has im plem ent ed funct ionalit y t o incr ease secur it y by obscur ing ser ver and
dat abase connect iv it y infor m at ion using CI AM and I WAS as w ell as disabling SQL Ser ver funct ionalit y t hat can be used