Vous êtes sur la page 1sur 31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

SQLServerFrequentlyAskedQuestions(FAQs)

SQLServerFrequentlyAskedQuestions(FAQs)
TransactSQLOptimizationTips
Useviewsandstoredproceduresinsteadofheavydutyqueries.
Thiscanreducenetworktraffic,becauseyourclientwillsendtoserveronlystoredprocedureorviewname
(perhapswithsomeparameters)insteadoflargeheavydutyqueriestext.Thiscanbeusedtofacilitate
permissionmanagementalso,becauseyoucanrestrictuseraccesstotablecolumnstheyshouldnotsee.
Trytouseconstraintsinsteadoftriggers,wheneverpossible.
Constraintsaremuchmoreefficientthantriggersandcanboostperformance.So,youshoulduse
constraintsinsteadoftriggers,wheneverpossible.
Usetablevariablesinsteadoftemporarytables.
Tablevariablesrequirelesslockingandloggingresourcesthantemporarytables,sotablevariablesshould
beusedwheneverpossible.ThetablevariablesareavailableinSQLServer2000only.
TrytouseUNIONALLstatementinsteadofUNION,wheneverpossible.
TheUNIONALLstatementismuchfasterthanUNION,becauseUNIONALLstatementdoesnotlookfor
duplicaterows,andUNIONstatementdoeslookforduplicaterows,whetherornottheyexist.
TrytoavoidusingtheDISTINCTclause,wheneverpossible.
BecauseusingtheDISTINCTclausewillresultinsomeperformancedegradation,youshouldusethis
clauseonlywhenitisnecessary.
TrytoavoidusingSQLServercursors,wheneverpossible.
SQLServercursorscanresultinsomeperformancedegradationincomparisonwithselectstatements.Try
tousecorrelatedsubqueryorderivedtables,ifyouneedtoperformrowbyrowoperations.
TrytoavoidtheHAVINGclause,wheneverpossible.
TheHAVINGclauseisusedtorestricttheresultsetreturnedbytheGROUPBYclause.Whenyouuse
GROUPBYwiththeHAVINGclause,theGROUPBYclausedividestherowsintosetsofgroupedrows
andaggregatestheirvalues,andthentheHAVINGclauseeliminatesundesiredaggregatedgroups.Inmany
cases,youcanwriteyourselectstatementso,thatitwillcontainonlyWHEREandGROUPBYclauses
withoutHAVINGclause.Thiscanimprovetheperformanceofyourquery.
Ifyouneedtoreturnthetotaltable'srowcount,youcanusealternativewayinsteadofSELECT
COUNT(*)statement.
BecauseSELECTCOUNT(*)statementmakeafulltablescantoreturnthetotaltable'srowcount,itcan
takeverymanytimeforthelargetable.Thereisanotherwaytodeterminethetotalrowcountinatable.
Youcanusesysindexessystemtable,inthiscase.ThereisROWScolumninthesysindexestable.This
columncontainsthetotalrowcountforeachtableinyourdatabase.So,youcanusethefollowingselect
statementinsteadofSELECTCOUNT(*):SELECTrowsFROMsysindexesWHEREid=
OBJECT_ID('table_name')ANDindid<2So,youcanimprovethespeedofsuchqueriesin
severaltimes.
IncludeSETNOCOUNTONstatementintoyourstoredprocedurestostopthemessageindicating
thenumberofrowsaffectedbyaTSQLstatement.
Thiscanreducenetworktraffic,becauseyourclientwillnotreceivethemessageindicatingthenumberof
rowsaffectedbyaTSQLstatement.
TrytorestrictthequeriesresultsetbyusingtheWHEREclause.
Thiscanresultsingoodperformancebenefits,becauseSQLServerwillreturntoclientonlyparticularrows,
notallrowsfromthetable(s).Thiscanreducenetworktrafficandboosttheoverallperformanceofthe
query.
UsetheselectstatementswithTOPkeywordortheSETROWCOUNTstatement,ifyouneedtoreturn
onlythefirstnrows.
Thiscanimproveperformanceofyourqueries,becausethesmallerresultsetwillbereturned.Thiscanalso
reducethetrafficbetweentheserverandtheclients.
Trytorestrictthequeriesresultsetbyreturningonlytheparticularcolumnsfromthetable,notall
table'scolumns.
Thiscanresultsingoodperformancebenefits,becauseSQLServerwillreturntoclientonlyparticular
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

1/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

columns,notalltable'scolumns.Thiscanreducenetworktrafficandboosttheoverallperformanceofthe
query.
1.Indexes
2.avoidmorenumberoftriggersonthetable
3.unnecessarycomplicatedjoins
4.correctuseofGroupbyclausewiththeselectlist
5.inworstcasesDenormalization
IndexOptimizationtips
EveryindexincreasesthetimeintakestoperformINSERTS,UPDATESandDELETES,sothenumberof
indexesshouldnotbeverymuch.Trytousemaximum45indexesononetable,notmore.Ifyouhave
readonlytable,thenthenumberofindexesmaybeincreased.
Keepyourindexesasnarrowaspossible.Thisreducesthesizeoftheindexandreducesthenumberof
readsrequiredtoreadtheindex.
Trytocreateindexesoncolumnsthathaveintegervaluesratherthancharactervalues.
Ifyoucreateacomposite(multicolumn)index,theorderofthecolumnsinthekeyareveryimportant.Try
toorderthecolumnsinthekeyastoenhanceselectivity,withthemostselectivecolumnstotheleftmostof
thekey.
Ifyouwanttojoinseveraltables,trytocreatesurrogateintegerkeysforthispurposeandcreateindexeson
theircolumns.
Createsurrogateintegerprimarykey(identityforexample)ifyourtablewillnothavemanyinsertoperations.
Clusteredindexesaremorepreferablethannonclustered,ifyouneedtoselectbyarangeofvaluesoryou
needtosortresultssetwithGROUPBYorORDERBY.
Ifyourapplicationwillbeperformingthesamequeryoverandoveronthesametable,considercreatinga
coveringindexonthetable.
YoucanusetheSQLServerProfilerCreateTraceWizardwith"IdentifyScansofLargeTables"traceto
determinewhichtablesinyourdatabasemayneedindexes.Thistracewillshowwhichtablesarebeing
scannedbyqueriesinsteadofusinganindex.
Youcanusesp_MSforeachtableundocumentedstoredproceduretorebuildallindexesinyour
database.TrytoscheduleittoexecuteduringCPUidletimeandslowproductionperiods.
sp_MSforeachtable@command1="print'?'DBCCDBREINDEX('?')"
TSQLQueries

1.2tables
Employee Phone
empid
empname empid
salary
phnumber
mgrid

2.Selectallemployeeswhodoesn'thavephone?
SELECTempname
FROMEmployee
WHERE(empidNOTIN
(SELECTDISTINCTempid
FROMphone))
3.Selecttheemployeenameswhoishavingmorethanonephonenumbers.
SELECTempname
FROMemployee
WHERE(empidIN
(SELECTempid
FROMphone
GROUPBYempid
HAVINGCOUNT(empid)>1))
4.Selectthedetailsof3maxsalariedemployeesfromemployeetable.
SELECTTOP3empid,salary
FROMemployee
ORDERBYsalaryDESC
5.Displayallmanagersfromthetable.(manageridissameasempid)
SELECTempname
FROMemployee
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

2/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

WHERE(empidIN
(SELECTDISTINCTmgrid
FROMemployee))
6.WriteaSelectstatementtolisttheEmployeeName,ManagerNameunderaparticularmanager?
SELECTe1.empnameASEmpName,e2.empnameASManagerName
FROMEmployeee1INNERJOIN
Employeee2ONe1.mgrid=e2.empid
ORDERBYe2.mgrid
7.2tablesempandphone.
empfieldsareempid,name
Phfieldsareempid,ph(office,mobile,home).Selectallemployeeswhodoesn'thaveanyphnos.
SELECT*
FROMemployeeLEFTOUTERJOIN
phoneONemployee.empid=phone.empid
WHERE(phone.officeISNULLORphone.office='')
AND(phone.mobileISNULLORphone.mobile='')
AND(phone.homeISNULLORphone.home='')
8.Findemployeewhoislivinginmorethanonecity.
TwoTables:
Emp

City

Empid
empName
Salary

Empid
City

9.SELECTempname,fname,lname
FROMemployee
WHERE(empidIN
(SELECTempid
FROMcity
GROUPBYempid
HAVINGCOUNT(empid)>1))
10.Findallemployeeswhoislivinginthesamecity.(tableissameasabove)
SELECTfname
FROMemployee
WHERE(empidIN
(SELECTempid
FROMcitya
WHEREcityIN
(SELECTcity
FROMcityb
GROUPBYcity
HAVINGCOUNT(city)>1)))
11. ThereisatablenamedMovieTablewiththreecolumnsmoviename,personandrole.Writeaquerywhich
getsthemoviedetailswhereMr.AmitabhandMr.Vinodactedandtheirroleisactor.
SELECTDISTINCTm1.moviename
FROMMovieTablem1INNERJOIN
MovieTablem2ONm1.moviename=m2.moviename
WHERE(m1.person='amitabh'ANDm2.person='vinod'OR
m2.person='amitabh'ANDm1.person='vinod')AND(m1.role='actor')AND
(m2.role='actor')
ORDERBYm1.moviename
12.Therearetwoemployeetablesnamedemp1andemp2.Bothcontainssamestructure(salarydetails).But
Emp2salarydetailsareincorrectandemp1salarydetailsarecorrect.So,writeaquerywhichcorrects
salarydetailsofthetableemp2
updateaseta.sal=b.salfromemp1a,emp2bwherea.empid=b.empid
13.GivenaTablenamedStudentswhichcontainsstudentid,subjectidandmarks.Wherethereare10
subjectsand50students.WriteaQuerytofindouttheMaximummarksobtainedineachsubject.
14.InthissametablesnowwriteaSQLQuerytogetthestudentidalsotocombinewithpreviousresults.
15.Threetablesstudent,course,markshowdogoatfindingnameofthestudentswhogotmaxmarksin
thediffcourses.
SELECTstudent.name,course.nameAScoursename,marks.sid,marks.mark
FROMmarksINNERJOIN
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

3/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

studentONmarks.sid=student.sidINNERJOIN
courseONmarks.cid=course.cid
WHERE(marks.mark=
(SELECTMAX(Mark)
FROMMarksMaxMark
WHEREMaxMark.cID=Marks.cID))
16.Thereisatableday_tempwhichhasthreecolumnsdayid,dayandtemperature.HowdoIwriteaqueryto
getthedifferenceoftemperatureamongeachotherforsevendaysofaweek?
SELECTa.dayid,a.dday,a.tempe,a.tempeb.tempeASDifference
FROMday_tempaINNERJOIN
day_tempbONa.dayid=b.dayid+1
OR
Selecta.day,a.degreeb.degreefromtemperaturea,temperaturebwhere
a.id=b.id+1
17.Thereisatablewhichcontainsthenameslikethis.a1,a2,a3,a3,a4,a1,a1,a2andtheirsalaries.Writea
querytogetgrandtotalsalary,andtotalsalariesofindividualemployeesinonequery.
SELECTempid,SUM(salary)ASsalary
FROMemployee
GROUPBYempidWITHROLLUP
ORDERBYempid
18.Howtoknowhowmanytablescontainsempnoasacolumninadatabase?
SELECTCOUNT(*)ASCounter
FROMsyscolumns
WHERE(name='empno')
19.Findduplicaterowsinatable?ORIhaveatablewithonecolumnwhichhasmanyrecordswhich
arenotdistinct.Ineedtofindthedistinctvaluesfromthatcolumnandnumberoftimesitsrepeated.
SELECTsid,mark,COUNT(*)ASCounter
FROMmarks
GROUPBYsid,mark
HAVING(COUNT(*)>1)
20.Howtodeletetherowswhichareduplicate(dontdeletebothduplicaterecords).
SETROWCOUNT1
DELETEyourtable
FROMyourtablea
WHERE(SELECTCOUNT(*)FROMyourtablebWHEREb.name1=a.name1ANDb.age1=
a.age1)>1
WHILE@@rowcount>0
DELETEyourtable
FROMyourtablea
WHERE(SELECTCOUNT(*)FROMyourtablebWHEREb.name1=a.name1ANDb.age1=
a.age1)>1
SETROWCOUNT0
21.Howtofind6thhighestsalary
SELECTTOP1salary
FROM(SELECTDISTINCTTOP6salary
FROMemployee
ORDERBYsalaryDESC)a
ORDERBYsalary
22.Findtopsalaryamongtwotables
SELECTTOP1sal
FROM(SELECTMAX(sal)ASsal
FROMsal1
UNION
SELECTMAX(sal)ASsal
FROMsal2)a
ORDERBYsalDESC
23.Writeaquerytoconvertallthelettersinawordtouppercase
SELECTUPPER('test')
24.Writeaquerytoroundupthevaluesofanumber.Forexampleeveniftheuserenters7.1itshould
beroundedupto8.
SELECTCEILING(7.1)
25.WriteaSQLQuerytofindfirstdayofmonth?
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

4/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

SELECTDATENAME(dw,DATEADD(dd,DATEPART(dd,GETDATE())+1,GETDATE()))AS
FirstDay
Datepart

Abbreviations

year

yy,yyyy

quarter

qq,q

month

mm,m

dayofyear

dy,y

day

dd,d

week

wk,ww

weekday

dw

hour

hh

minute

mi,n

second

ss,s

millisecond

ms

26.TableAcontainscolumn1whichisprimarykeyandhas2values(1,2)andTableBcontainscolumn1which
isprimarykeyandhas2values(2,3).Writeaquerywhichreturnsthevaluesthatarenotcommonforthe
tablesandthequeryshouldreturnonecolumnwith2records.
SELECTtbla.a
FROMtbla,tblb
WHEREtbla.a<>
(SELECTtblb.a
FROMtbla,tblb
WHEREtbla.a=tblb.a)
UNION
SELECTtblb.a
FROMtbla,tblb
WHEREtblb.a<>
(SELECTtbla.a
FROMtbla,tblb
WHEREtbla.a=tblb.a)
OR(betterapproach)
SELECTa
FROMtbla
WHEREaNOTIN
(SELECTa
FROMtblb)
UNIONALL
SELECTa
FROMtblb
WHEREaNOTIN
(SELECTa
FROMtbla)
27.Thereare3tablesTitles,AuthorsandTitleAuthors(checkPUBSdb).Writethequerytogettheauthor
nameandthenumberofbookswrittenbythatauthor,theresultshouldstartfromtheauthorwhohas
writtenthemaximumnumberofbooksandendwiththeauthorwhohaswrittentheminimumnumberof
books.
SELECTauthors.au_lname,COUNT(*)ASBooksCount
FROMauthorsINNERJOIN
titleauthorONauthors.au_id=titleauthor.au_idINNERJOIN
titlesONtitles.title_id=titleauthor.title_id
GROUPBYauthors.au_lname
ORDERBYBooksCountDESC

28.
UPDATEemp_master
SETemp_sal=
CASE
WHENemp_sal>0ANDemp_sal<=20000THEN(emp_sal*1.01)
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

5/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

WHENemp_sal>20000THEN(emp_sal*1.02)
END
29.Listallproductswithtotalquantityordered,ifquantityorderedisnullshowitas0.
SELECTname,CASEWHENSUM(qty)ISNULLTHEN0WHENSUM(qty)>0THENSUM(qty)
ENDAStot
FROM[order]RIGHTOUTERJOIN
productON[order].prodid=product.prodid
GROUPBYname
Result:
coke60
mirinda0
pepsi10
30.ANY,SOME,orALL?
ALLmeansgreaterthaneveryvalueinotherwords,greaterthanthemaximumvalue.Forexample,>ALL
(1,2,3)meansgreaterthan3.
ANYmeansgreaterthanatleastonevalue,thatis,greaterthantheminimum.So>ANY(1,2,3)means
greaterthan1.SOMEisanSQL92standardequivalentforANY.
31.IN&=(differenceincorrelatedsubquery)
INDEX
32.WhatisIndex?Itspurpose?
Indexesindatabasesaresimilartoindexesinbooks.Inadatabase,anindexallowsthedatabaseprogram
tofinddatainatablewithoutscanningtheentiretable.Anindexinadatabaseisalistofvaluesinatable
withthestoragelocationsofrowsinthetablethatcontaineachvalue.Indexescanbecreatedoneithera
singlecolumnoracombinationofcolumnsinatableandareimplementedintheformofBtrees.Anindex
containsanentrywithoneormorecolumns(thesearchkey)fromeachrowinatable.ABtreeissortedon
thesearchkey,andcanbesearchedefficientlyonanyleadingsubsetofthesearchkey.Forexample,an
indexoncolumnsA,B,CcanbesearchedefficientlyonA,onA,B,andA,B,C.
33.ExplainaboutClusteredandnonclusteredindex?HowtochoosebetweenaClusteredIndexanda
NonClusteredIndex?
Thereareclusteredandnonclusteredindexes.Aclusteredindexisaspecialtypeofindexthatreordersthe
wayrecordsinthetablearephysicallystored.Thereforetablecanhaveonlyoneclusteredindex.Theleaf
nodesofaclusteredindexcontainthedatapages.
Anonclusteredindexisaspecialtypeofindexinwhichthelogicalorderoftheindexdoesnotmatchthe
physicalstoredorderoftherowsondisk.Theleafnodesofanonclusteredindexdoesnotconsistofthe
datapages.Instead,theleafnodescontainindexrows.
Considerusingaclusteredindexfor:
Columnsthatcontainalargenumberofdistinctvalues.
QueriesthatreturnarangeofvaluesusingoperatorssuchasBETWEEN,>,>=,<,and<=.
Columnsthatareaccessedsequentially.
Queriesthatreturnlargeresultsets.
NonclusteredindexeshavethesameBtreestructureasclusteredindexes,withtwosignificant
differences:
Thedatarowsarenotsortedandstoredinorderbasedontheirnonclusteredkeys.
Theleaflayerofanonclusteredindexdoesnotconsistofthedatapages.Instead,theleafnodes
containindexrows.Eachindexrowcontainsthenonclusteredkeyvalueandoneormorerowlocators
thatpointtothedatarow(orrowsiftheindexisnotunique)havingthekeyvalue.
Pertableonly249nonclusteredindexes.

34.Disadvantageofindex?
EveryindexincreasesthetimeintakestoperformINSERTS,UPDATESandDELETES,sothenumberof
indexesshouldnotbeverymuch.
35.GivenascenariothatIhavea10ClusteredIndexinaTabletoalltheir10Columns.Whatarethe
advantagesanddisadvantages?
A:Only1clusteredindexispossible.
36.HowcanIenforcetouseparticularindex?
Youcanuseindexhint(index=<index_name>)afterthetablename.
SELECTau_lnameFROMauthors(index=aunmind)
37.WhatisIndexTuning?
Oneofthehardesttasksfacingdatabaseadministratorsistheselectionofappropriatecolumnsfornon
clusteredindexes.Youshouldconsidercreatingnonclusteredindexesonanycolumnsthatarefrequently
referencedintheWHEREclausesofSQLstatements.Othergoodcandidatesarecolumnsreferencedby
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

6/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

JOINandGROUPBYoperations.
Youmaywishtoalsoconsidercreatingnonclusteredindexesthatcoverallofthecolumnsusedbycertain
frequentlyissuedqueries.Thesequeriesarereferredtoascoveredqueriesandexperienceexcellent
performancegains.
IndexTuningistheprocessoffindingappropriatecolumnfornonclusteredindexes.
SQLServerprovidesawonderfulfacilityknownastheIndexTuningWizardwhichgreatlyenhancesthe
indexselectionprocess.
38.DifferencebetweenIndexdefragandIndexrebuild?
Whenyoucreateanindexinthedatabase,theindexinformationusedbyqueriesisstoredinindexpages.
Thesequentialindexpagesarechainedtogetherbypointersfromonepagetothenext.Whenchangesare
madetothedatathataffecttheindex,theinformationintheindexcanbecomescatteredinthedatabase.
Rebuildinganindexreorganizesthestorageoftheindexdata(andtabledatainthecaseofaclustered
index)toremovefragmentation.Thiscanimprovediskperformancebyreducingthenumberofpagereads
requiredtoobtaintherequesteddata
DBCCINDEXDEFRAGDefragmentsclusteredandsecondaryindexesofthespecifiedtableorview.
39.Whatissortingandwhatisthedifferencebetweensorting&clusteredindexes?
TheORDERBYclausesortsqueryresultsbyoneormorecolumnsupto8,060bytes.Thiswillhappenby
thetimewhenweretrievedatafromdatabase.Clusteredindexesphysicallysortingdata,while
inserting/updatingthetable.
40.Whatarestatistics,underwhatcircumstancestheygooutofdate,howdoyouupdatethem?
Statisticsdeterminetheselectivityoftheindexes.Ifanindexedcolumnhasuniquevaluesthenthe
selectivityofthatindexismore,asopposedtoanindexwithnonuniquevalues.Queryoptimizeruses
theseindexesindeterminingwhethertochooseanindexornotwhileexecutingaquery.
Somesituationsunderwhichyoushouldupdatestatistics:
1)Ifthereissignificantchangeinthekeyvaluesintheindex
2)Ifalargeamountofdatainanindexedcolumnhasbeenadded,changed,orremoved(thatis,ifthe
distributionofkeyvalueshaschanged),orthetablehasbeentruncatedusingtheTRUNCATETABLE
statementandthenrepopulated
3)Databaseisupgradedfromapreviousversion
41.Whatisfillfactor?Whatistheuseofit?Whathappenswhenweignoreit?Whenyoushoulduse
lowfillfactor?
Whenyoucreateaclusteredindex,thedatainthetableisstoredinthedatapagesofthedatabase
accordingtotheorderofthevaluesintheindexedcolumns.Whennewrowsofdataareinsertedintothe
tableorthevaluesintheindexedcolumnsarechanged,MicrosoftSQLServer2000mayhaveto
reorganizethestorageofthedatainthetabletomakeroomforthenewrowandmaintaintheordered
storageofthedata.Thisalsoappliestononclusteredindexes.Whendataisaddedorchanged,SQLServer
mayhavetoreorganizethestorageofthedatainthenonclusteredindexpages.Whenanewrowisadded
toafullindexpage,SQLServermovesapproximatelyhalftherowstoanewpagetomakeroomforthe
newrow.Thisreorganizationisknownasapagesplit.Pagesplittingcanimpairperformanceandfragment
thestorageofthedatainatable.
Whencreatinganindex,youcanspecifyafillfactortoleaveextragapsandreserveapercentageoffree
spaceoneachleaflevelpageoftheindextoaccommodatefutureexpansioninthestorageofthetable's
dataandreducethepotentialforpagesplits.Thefillfactorvalueisapercentagefrom0to100that
specifieshowmuchtofillthedatapagesaftertheindexiscreated.Avalueof100meansthepageswillbe
fullandwilltaketheleastamountofstoragespace.Thissettingshouldbeusedonlywhentherewillbeno
changestothedata,forexample,onareadonlytable.Alowervalueleavesmoreemptyspaceonthedata
pages,whichreducestheneedtosplitdatapagesasindexesgrowbutrequiresmorestoragespace.This
settingismoreappropriatewhentherewillbechangestothedatainthetable.
DATATYPES
42.WhatarethedatatypesinSQL
bigint

Binary

bit

char

cursor

datetime

Decimal

float

image

int

money

Nchar

ntext

nvarchar

real

smalldatetime

Smallint

smallmoney

text

timestamp

tinyint

Varbinary

Varchar

uniqueidentifier

43.Differencebetweencharandnvarchar/charandvarchardatatype?
char[(n)]FixedlengthnonUnicodecharacterdatawithlengthofnbytes.nmustbeavaluefrom1through
8,000.Storagesizeisnbytes.TheSQL92synonymforcharischaracter.
nvarchar(n)VariablelengthUnicodecharacterdataofncharacters.nmustbeavaluefrom1through
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

7/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

4,000.Storagesize,inbytes,istwotimesthenumberofcharactersentered.Thedataenteredcanbe0
charactersinlength.TheSQL92synonymsfornvarchararenationalcharvaryingandnationalcharacter
varying.
varchar[(n)]VariablelengthnonUnicodecharacterdatawithlengthofnbytes.nmustbeavaluefrom1
through8,000.Storagesizeistheactuallengthinbytesofthedataentered,notnbytes.Thedataentered
canbe0charactersinlength.TheSQL92synonymsforvarchararecharvaryingorcharactervarying.
44.GUIDdatasize?
128bit
45.HowGUIDbecominguniqueacrossmachines?
Toensureuniquenessacrossmachines,theIDofthenetworkcardisused(amongothers)tocomputethe
number.
46.Whatisthedifferencebetweentextandimagedatatype?
Textandimage.Usetextforcharacterdataifyouneedtostoremorethan255charactersinSQLServer
6.5,ormorethan8000inSQLServer7.0.Useimageforbinarylargeobjects(BLOBs)suchasdigital
images.Withtextandimagedatatypes,thedataisnotstoredintherow,sothelimitofthepagesizedoes
notapply.Allthatisstoredintherowisapointertothedatabasepagesthatcontainthedata.Individualtext,
ntext,andimagevaluescanbeamaximumof2GB,whichistoolongtostoreinasingledatarow.
JOINS
47.Whatarejoins?
Sometimeswehavetoselectdatafromtwoormoretablestomakeourresultcomplete.Wehaveto
performajoin.
48.HowmanytypesofJoins?
Joinscanbecategorizedas:
Innerjoins(thetypicaljoinoperation,whichusessomecomparisonoperatorlike=or<>).These
includeequijoinsandnaturaljoins.
Innerjoinsuseacomparisonoperatortomatchrowsfromtwotablesbasedonthevaluesincommon
columnsfromeachtable.Forexample,retrievingallrowswherethestudentidentificationnumberis
thesameinboththestudentsandcoursestables.
Outerjoins.Outerjoinscanbealeft,aright,orfullouterjoin.
Outerjoinsarespecifiedwithoneofthefollowingsetsofkeywordswhentheyarespecifiedinthe
FROMclause:
LEFTJOINorLEFTOUTERJOINTheresultsetofaleftouterjoinincludesalltherowsfromthe
lefttablespecifiedintheLEFTOUTERclause,notjusttheonesinwhichthejoinedcolumns
match.Whenarowinthelefttablehasnomatchingrowsintherighttable,theassociatedresult
setrowcontainsnullvaluesforallselectlistcolumnscomingfromtherighttable.
RIGHTJOINorRIGHTOUTERJOINArightouterjoinisthereverseofaleftouterjoin.All
rowsfromtherighttablearereturned.Nullvaluesarereturnedforthelefttableanytimearight
tablerowhasnomatchingrowinthelefttable.
FULLJOINorFULLOUTERJOINAfullouterjoinreturnsallrowsinboththeleftandright
tables.Anytimearowhasnomatchintheothertable,theselectlistcolumnsfromtheothertable
containnullvalues.Whenthereisamatchbetweenthetables,theentireresultsetrowcontains
datavaluesfromthebasetables.
CrossjoinsCrossjoinsreturnallrowsfromthelefttable,eachrowfromthelefttableiscombined
withallrowsfromtherighttable.CrossjoinsarealsocalledCartesianproducts.(ACartesianjoinwill
getyouaCartesianproduct.ACartesianjoiniswhenyoujoineveryrowofonetabletoeveryrowof
anothertable.Youcanalsogetonebyjoiningeveryrowofatabletoeveryrowofitself.)

48.Whatisselfjoin?
Atablecanbejoinedtoitselfinaselfjoin.
49.WhatarethedifferencesbetweenUNIONandJOINS?
Ajoinselectscolumnsfrom2ormoretables.Aunionselectsrows.
50.CanIimproveperformancebyusingtheANSIstylejoinsinsteadoftheoldstylejoins?
CodeExample1:
selecto.name,i.name
fromsysobjectso,sysindexesi
whereo.id=i.id
CodeExample2:
selecto.name,i.name
fromsysobjectsoinnerjoinsysindexesi
ono.id=i.id
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

8/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

YouwillnotgetanyperformancegainbyswitchingtotheANSIstyleJOINsyntax.
UsingtheANSIJOINsyntaxgivesyouanimportantadvantage:Becausethejoinlogiciscleanlyseparated
fromthefilteringcriteria,youcanunderstandthequerylogicmorequickly.
TheSQLServeroldstyleJOINexecutesthefilteringconditionsbeforeexecutingthejoins,whereasthe
ANSIstyleJOINreversesthisprocedure(joinlogicprecedesfiltering).
PerhapsthemostcompellingargumentforswitchingtotheANSIstyleJOINisthatMicrosofthasexplicitly
statedthatSQLServerwillnotsupporttheoldstyleOUTERJOINsyntaxindefinitely.Anotherimportant
considerationisthattheANSIstyleJOINsupportsqueryconstructionsthattheoldstyleJOINsyntaxdoes
notsupport.
51.Whatisderivedtable?
DerivedtablesareSELECTstatementsintheFROMclausereferredtobyanaliasorauserspecified
name.TheresultsetoftheSELECTintheFROMclauseformsatableusedbytheouterSELECT
statement.Forexample,thisSELECTusesaderivedtabletofindifanystorecarriesallbooktitlesinthe
pubsdatabase:
SELECTST.stor_id,ST.stor_name
FROMstoresASST,
(SELECTstor_id,COUNT(DISTINCTtitle_id)AStitle_count
FROMsales
GROUPBYstor_id
)ASSA
WHEREST.stor_id=SA.stor_id
ANDSA.title_count=(SELECTCOUNT(*)FROMtitles)
STOREDPROCEDURE

53.WhatisStoredprocedure?
AstoredprocedureisasetofStructuredQueryLanguage(SQL)statementsthatyouassignanametoand
storeinadatabaseincompiledformsothatyoucanshareitbetweenanumberofprograms.
Theyallowmodularprogramming.
Theyallowfasterexecution.
Theycanreducenetworktraffic.
Theycanbeusedasasecuritymechanism.

54.WhatarethedifferenttypesofStorageProcedure?
1.TemporaryStoredProceduresSQLServersupportstwotypesoftemporaryprocedures:localand
global.Alocaltemporaryprocedureisvisibleonlytotheconnectionthatcreatedit.Aglobaltemporary
procedureisavailabletoallconnections.Localtemporaryproceduresareautomaticallydroppedatthe
endofthecurrentsession.Globaltemporaryproceduresaredroppedattheendofthelastsession
usingtheprocedure.Usually,thisiswhenthesessionthatcreatedtheprocedureends.Temporary
proceduresnamedwith#and##canbecreatedbyanyuser.
2.Systemstoredproceduresarecreatedandstoredinthemasterdatabaseandhavethesp_prefix.(or
xp_)Systemstoredprocedurescanbeexecutedfromanydatabasewithouthavingtoqualifythe
storedprocedurenamefullyusingthedatabasenamemaster.(Ifanyusercreatedstoredprocedure
hasthesamenameasasystemstoredprocedure,theusercreatedstoredprocedurewillneverbe
executed.)
3.AutomaticallyExecutingStoredProceduresOneormorestoredprocedurescanexecute
automaticallywhenSQLServerstarts.Thestoredproceduresmustbecreatedbythesystem
administratorandexecutedunderthesysadminfixedserverroleasabackgroundprocess.The
procedure(s)cannothaveanyinputparameters.
4.Userstoredprocedure
55.HowdoImarkthestoredproceduretoautomaticexecution?
Youcanusethesp_procoptionsystemstoredproceduretomarkthestoredproceduretoautomatic
executionwhentheSQLServerwillstart.Onlyobjectsinthemasterdatabaseownedbydbocanhavethe
startupsettingchangedandthisoptionisrestrictedtoobjectsthathavenoparameters.
USEmaster
EXECsp_procoption'indRebuild','startup','true')
56.HowwillknowwhethertheSQLstatementsareexecuted?
Whenusedinastoredprocedure,theRETURNstatementcanspecifyanintegervaluetoreturntothe
callingapplication,batch,orprocedure.IfnovalueisspecifiedonRETURN,astoredprocedurereturnsthe
value0.Thestoredproceduresreturnavalueof0whennoerrorswereencountered.Anynonzerovalue
indicatesanerroroccurred.
57.Whyoneshouldnotprefixuserstoredprocedureswithsp_?
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

9/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

Itisstronglyrecommendedthatyoudonotcreateanystoredproceduresusingsp_asaprefix.SQLServer
alwayslooksforastoredprocedurebeginningwithsp_inthisorder:

5.Thestoredprocedureinthemasterdatabase.
6.Thestoredprocedurebasedonanyqualifiersprovided(databasenameorowner).
7.Thestoredprocedureusingdboastheowner,ifoneisnotspecified.
Therefore,althoughtheusercreatedstoredprocedureprefixedwithsp_mayexistinthecurrent
database,themasterdatabaseisalwayscheckedfirst,evenifthestoredprocedureisqualifiedwiththe
databasename.

58.WhatcancauseaStoredprocedureexecutionplantobecomeinvalidatedand/orfalloutofcache?
Serverrestart
Planisagedoutduetolowuse
DBCCFREEPROCCACHE(sometimedesiredtoforceit)

59.Whendooneneedtorecompilestoredprocedure?
ifanewindexisaddedfromwhichthestoredproceduremightbenefit,optimizationdoesnotautomatically
happen(untilthenexttimethestoredprocedureisrunafterSQLServerisrestarted).
60.SQLServerprovidesthreewaystorecompileastoredprocedure:
Thesp_recompilesystemstoredprocedureforcesarecompileofastoredprocedurethenexttimeit
isrun.
CreatingastoredprocedurethatspecifiestheWITHRECOMPILEoptioninitsdefinitionindicatesthat
SQLServerdoesnotcacheaplanforthisstoredprocedurethestoredprocedureisrecompiledeach
timeitisexecuted.UsetheWITHRECOMPILEoptionwhenstoredprocedurestakeparameters
whosevaluesdifferwidelybetweenexecutionsofthestoredprocedure,resultingindifferentexecution
planstobecreatedeachtime.Useofthisoptionisuncommon,andcausesthestoredprocedureto
executemoreslowlybecausethestoredproceduremustberecompiledeachtimeitisexecuted.
YoucanforcethestoredproceduretoberecompiledbyspecifyingtheWITHRECOMPILEoption
whenyouexecutethestoredprocedure.Usethisoptiononlyiftheparameteryouaresupplyingis
atypicalorifthedatahassignificantlychangedsincethestoredprocedurewascreated.

61.Howtofindoutwhichstoredprocedureisrecompiling?Howtostopstoredproceduresfrom
recompiling?
62.IhaveTwoStoredProceduresSP1andSP2asgivenbelow.HowtheTransactionworks,whether
SP2Transactionsucceedsorfails?
CREATEPROCEDURESP1AS
BEGINTRAN
INSERTINTOMARKS(SID,MARK,CID)VALUES(5,6,3)
EXECSP2
ROLLBACK
GO
CREATEPROCEDURESP2AS
BEGINTRAN
INSERTINTOMARKS(SID,MARK,CID)VALUES(100,100,103)
committran
GO
Bothwillgetrollbacked.
63.CREATEPROCEDURESP1AS
BEGINTRAN
INSERTINTOMARKS(SID,MARK,CID)VALUES(5,6,3)
BEGINTRAN
INSERTINTOSTUDENT(SID,NAME1)VALUES(1,'SA')
committran
ROLLBACKTRAN
GO
Bothwillgetrollbacked.
64.HowwillyouhandleErrorsinSqlStoredProcedure?
INSERTNonFatalVALUES(@Column2)
IF@@ERROR<>0
BEGIN
PRINT'ErrorOccured'
END
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

10/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

http://www.sqlteam.com/item.asp?ItemID=2463[http://www.sqlteam.com/item.asp?ItemID=2463]
65.Howwillyouraiseanerrorinsql?
RAISERRORReturnsauserdefinederrormessageandsetsasystemflagtorecordthatanerrorhas
occurred.UsingRAISERROR,theclientcaneitherretrieveanentryfromthesysmessagestableorbuilda
messagedynamicallywithuserspecifiedseverityandstateinformation.Afterthemessageisdefineditis
sentbacktotheclientasaservererrormessage.
66.Ihaveastoredprocedurelike
committran
createtablea()
insertintotableb

rollbacktran
whatwillbetheresult?Istablecreated?datawillbeinsertedintableb?
67.HowyouwillreturnXMLfromStoredProcedure?
YouusetheFORXMLclauseoftheSELECTstatement,andwithintheFORXMLclauseyouspecifyan
XMLmode:RAW,AUTO,orEXPLICIT.
68.CanaStoredProcedurecallitself(recursive).Ifsothenuptowhatlevelandcanitbecontrol?
Storedproceduresarenestedwhenonestoredprocedurecallsanother.Youcanneststoredproceduresup
to32levels.Thenestinglevelincreasesbyonewhenthecalledstoredprocedurebeginsexecutionand
decreasesbyonewhenthecalledstoredprocedurecompletesexecution.Attemptingtoexceedthe
maximumof32levelsofnestingcausesthewholecallingstoredprocedurechaintofail.Thecurrentnesting
levelforthestoredproceduresinexecutionisstoredinthe@@NESTLEVELfunction.
eg:
SETNOCOUNTON
USEmaster
IFOBJECT_ID('dbo.sp_calcfactorial')ISNOTNULL
DROPPROCdbo.sp_calcfactorial
GO
CREATEPROCdbo.sp_calcfactorial
@base_numberint,@factorialintOUT
AS
DECLARE@previous_numberint
IF(@base_number<2)SET@factorial=1Factorialof0or1=1
ELSEBEGIN
SET@previous_number=@base_number1
EXECdbo.sp_calcfactorial@previous_number,@factorialOUTRecursivecall
IF(@factorial=1)RETURN(1)Gotanerror,return
SET@factorial=@factorial*@base_number
END
RETURN(0)
GO
callingproc.
DECLARE@factorialint
EXECdbo.sp_calcfactorial4,@factorialOUT
SELECT@factorial
69.NestedTriggers
Triggersarenestedwhenatriggerperformsanactionthatinitiatesanothertrigger,whichcaninitiateanother
trigger,andsoon.Triggerscanbenestedupto32levels,andyoucancontrolwhethertriggerscanbe
nestedthroughthenestedtriggersserverconfigurationoption.
70.Whatisanextendedstoredprocedure?CanyouinstantiateaCOMobjectbyusingTSQL?
AnextendedstoredprocedureisafunctionwithinaDLL(writteninaprogramminglanguagelikeC,C++
usingOpenDataServices(ODS)API)thatcanbecalledfromTSQL,justthewaywecallnormalstored
proceduresusingtheEXECstatement.
71.Differencebetweenviewandstoredprocedure?
Viewscanhaveonlyselectstatements(create,update,truncate,deletestatementsarenotallowed)Views
cannothaveselectinto,GroupbyHaving,Orderby
72.WhatisaFunction&whatarethedifferentuserdefinedfunctions?
FunctionisasavedTransactSQLroutinethatreturnsavalue.Userdefinedfunctionscannotbeusedto
performasetofactionsthatmodifytheglobaldatabasestate.Userdefinedfunctions,likesystem
functions,canbeinvokedfromaquery.TheyalsocanbeexecutedthroughanEXECUTEstatementlike
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

11/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

storedprocedures.

11. ScalarFunctions
FunctionsarescalarvaluediftheRETURNSclausespecifiedoneofthescalardatatypes
12.InlineTablevaluedFunctions
IftheRETURNSclausespecifiesTABLEwithnoaccompanyingcolumnlist,thefunctionisaninline
function.
13.MultistatementTablevaluedFunctions
IftheRETURNSclausespecifiesaTABLEtypewithcolumnsandtheirdatatypes,thefunctionisa
multistatementtablevaluedfunction.
73.Whatarethedifferencebetweenafunctionandastoredprocedure?
Functionscanbeusedinaselectstatementwhereasprocedurescannot
ProceduretakesbothinputandoutputparametersbutFunctionstakesonlyinputparameters
Functionscannotreturnvaluesoftypetext,ntext,image&timestampswhereasprocedurescan
Functionscanbeusedasuserdefineddatatypesincreatetablebutprocedurescannot
***Eg:createtable<tablename>(namevarchar(10),salarygetsal(name))
Heregetsalisauserdefinedfunctionwhichreturnsasalarytype,whentableiscreatednostorageis
allottedforsalarytype,andgetsalfunctionisalsonotexecuted,Butwhenwearefetchingsome
valuesfromthistable,getsalfunctiongetsexecutedandthereturn
Typeisreturnedastheresultset.

74.Howtodebugastoredprocedure?
TRIGGER
75.WhatisTrigger?Whatisitsuse?WhatarethetypesofTriggers?Whatarethenewkindsoftriggers
insql2000?
TriggersareaspecialclassofstoredproceduredefinedtoexecuteautomaticallywhenanUPDATE,
INSERT,orDELETEstatementisissuedagainstatableorview.Triggersarepowerfultoolsthatsitescan
usetoenforcetheirbusinessrulesautomaticallywhendataismodified.
TheCREATETRIGGERstatementcanbedefinedwiththeFORUPDATE,FORINSERT,orFOR
DELETEclausestotargetatriggertoaspecificclassofdatamodificationactions.WhenFORUPDATEis
specified,theIFUPDATE(column_name)clausecanbeusedtotargetatriggertoupdatesaffectinga
particularcolumn.
YoucanusetheFORclausetospecifywhenatriggerisexecuted:
AFTER(default)Thetriggerexecutesafterthestatementthattriggereditcompletes.Ifthestatement
failswithanerror,suchasaconstraintviolationorsyntaxerror,thetriggerisnotexecuted.AFTER
triggerscannotbespecifiedforviews.
INSTEADOFThetriggerexecutesinplaceofthetriggeringaction.INSTEADOFtriggerscanbe
specifiedonbothtablesandviews.YoucandefineonlyoneINSTEADOFtriggerforeachtriggering
action(INSERT,UPDATE,andDELETE).INSTEADOFtriggerscanbeusedtoperformenhance
integritychecksonthedatavaluessuppliedinINSERTandUPDATEstatements.INSTEADOF
triggersalsoletyouspecifyactionsthatallowviews,whichwouldnormallynotsupportupdates,tobe
updatable.
AnINSTEADOFtriggercantakeactionssuchas:
Ignoringpartsofabatch.
Notprocessingapartofabatchandloggingtheproblemrows.
Takinganalternativeactionifanerrorconditionisencountered.
InSQLServer6.5youcoulddefineonly3triggerspertable,oneforINSERT,oneforUPDATEandone
forDELETE.FromSQLServer7.0onwards,thisrestrictionisgone,andyoucouldcreatemultiple
triggerspereachaction.Butin7.0there'snowaytocontroltheorderinwhichthetriggersfire.InSQL
Server2000youcouldspecifywhichtriggerfiresfirstorfireslastusingsp_settriggerorder.
TillSQLServer7.0,triggersfireonlyafterthedatamodificationoperationhappens.Soinaway,theyare
calledposttriggers.ButinSQLServer2000youcouldcreatepretriggersalso.

76.Whenshouldoneuse"insteadofTrigger"?Example
CREATETABLEBaseTable
(
PrimaryKeyintIDENTITY(1,1),
Colornvarchar(10)NOTNULL,
Materialnvarchar(10)NOTNULL,
ComputedColAS(Color+Material)
)
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

12/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

GO
Createaviewthatcontainsallcolumnsfromthebasetable.
CREATEVIEWInsteadView
ASSELECTPrimaryKey,Color,Material,ComputedCol
FROMBaseTable
GO
CreateanINSTEADOFINSERTtriggeronttheview.
CREATETRIGGERInsteadTriggeronInsteadView
INSTEADOFINSERT
AS
BEGIN
BuildanINSERTstatementignoringinserrted.PrimaryKeyand
inserted.ComputedCol.
INSERTINTOBaseTable
SELECTColor,Material
FROMinserted
END
GO
caninsertvaluetobasetablebythisinsertintobasetable(color,material)
values('red','abc')
insertintoInsteadView(color,material))values('red','abc')can'tdo
this.
Itwillgiveerror"'PrimaryKey'iintable'InsteadView'cannotbenull."
caninsertvaluethroughtablebythis<
insertintoInsteadViewvalues(1,'red','abc',1)PrimaryKey,ComputedCol
wonttakevaluesfromhere
77.Differencebetweentriggerandstoredprocedure?
TriggerwillgetexecuteautomaticallywhenanUPDATE,INSERT,orDELETEstatementisissuedagainst
atableorview.
Wehavetocallstoredproceduremanually,oritcanexecuteautomaticwhentheSQLServerstarts(You
canusethesp_procoptionsystemstoredproceduretomarkthestoredproceduretoautomatic
executionwhentheSQLServerwillstart.
78.Thefollowingtriggergeneratesanemailwheneveranewtitleisadded.
CREATETRIGGERreminder
ONtitles
FORINSERT
AS
EXECmaster..xp_sendmail'MaryM','Newtitle,mentioninthenextreportto
distributors.'
79.Drawbackoftrigger?Itsalternativesolution?
Triggersaregenerallyusedtoimplementbusinessrules,auditing.Triggerscanalsobeusedtoextendthe
referentialintegritychecks,butwhereverpossible,useconstraintsforthispurpose,insteadoftriggers,as
constraintsaremuchfaster.
LOCK
80.Whatarelocks?
MicrosoftSQLServer2000useslockingtoensuretransactionalintegrityanddatabaseconsistency.
Lockingpreventsusersfromreadingdatabeingchangedbyotherusers,andpreventsmultipleusersfrom
changingthesamedataatthesametime.Iflockingisnotused,datawithinthedatabasemaybecome
logicallyincorrect,andqueriesexecutedagainstthatdatamayproduceunexpectedresults.
81.Whatarethedifferenttypesoflocks?
SQLServerusestheseresourcelockmodes.
Lock
mode

Description

Shared
(S)

Usedforoperationsthatdonotchangeorupdatedata(readonlyoperations),suchasa
SELECTstatement.

http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

13/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

Update
(U)

Usedonresourcesthatcanbeupdated.Preventsacommonformofdeadlockthatoccurs
whenmultiplesessionsarereading,locking,andpotentiallyupdatingresourceslater.

Exclusive Usedfordatamodificationoperations,suchasINSERT,UPDATE,orDELETE.Ensuresthat
(X)
multipleupdatescannotbemadetothesameresourceatthesametime.
Intent

Usedtoestablishalockhierarchy.Thetypesofintentlocksare:intentshared(IS),intent
exclusive(IX),andsharedwithintentexclusive(SIX).

Schema

Usedwhenanoperationdependentontheschemaofatableisexecuting.Thetypesof
schemalocksare:schemamodification(SchM)andschemastability(SchS).

Bulk
Update
(BU)

UsedwhenbulkcopyingdataintoatableandtheTABLOCKhintisspecified.

82.Whatisadeadlock?Giveapracticalsample?Howyoucanminimizethedeadlocksituation?What
isadeadlockandwhatisalivelock?Howwillyougoaboutresolvingdeadlocks?
Deadlockisasituationwhentwoprocesses,eachhavingalockononepieceofdata,attempttoacquirea
lockontheother'spiece.Eachprocesswouldwaitindefinitelyfortheothertoreleasethelock,unlessone
oftheuserprocessesisterminated.SQLServerdetectsdeadlocksandterminatesoneuser'sprocess.
Alivelockisone,wherearequestforanexclusivelockisrepeatedlydeniedbecauseaseriesof
overlappingsharedlockskeepsinterfering.SQLServerdetectsthesituationafterfourdenialsandrefuses
furthersharedlocks.(Alivelockalsooccurswhenreadtransactionsmonopolizeatableorpage,forcinga
writetransactiontowaitindefinitely.)
83.Whatisisolationlevel?
Anisolationleveldeterminesthedegreeofisolationofdatabetweenconcurrenttransactions.Thedefault
SQLServerisolationlevelisReadCommitted.Alowerisolationlevelincreasesconcurrency,butatthe
expenseofdatacorrectness.Conversely,ahigherisolationlevelensuresthatdataiscorrect,butcanaffect
concurrencynegatively.TheisolationlevelrequiredbyanapplicationdeterminesthelockingbehaviorSQL
Serveruses.
SQL92definesthefollowingisolationlevels,allofwhicharesupportedbySQLServer:
Readuncommitted(thelowestlevelwheretransactionsareisolatedonlyenoughtoensurethat
physicallycorruptdataisnotread).
Readcommitted(SQLServerdefaultlevel).
Repeatableread.
Serializable(thehighestlevel,wheretransactionsarecompletelyisolatedfromoneanother).
Isolationlevel

Dirtyread

Nonrepeatableread

Phantom

Readuncommitted

Yes

Yes

Yes

Readcommitted

No

Yes

Yes

Repeatableread

No

No

Yes

Serializable

No

No

No

84.UncommittedDependency(DirtyRead)Uncommitteddependencyoccurswhenasecondtransaction
selectsarowthatisbeingupdatedbyanothertransaction.Thesecondtransactionisreadingdatathathas
notbeencommittedyetandmaybechangedbythetransactionupdatingtherow.Forexample,aneditoris
makingchangestoanelectronicdocument.Duringthechanges,asecondeditortakesacopyofthe
documentthatincludesallthechangesmadesofar,anddistributesthedocumenttotheintendedaudience.
InconsistentAnalysis(NonrepeatableRead)Inconsistentanalysisoccurswhenasecondtransaction
accessesthesamerowseveraltimesandreadsdifferentdataeachtime.Inconsistentanalysisissimilarto
uncommitteddependencyinthatanothertransactionischangingthedatathatasecondtransactionis
reading.However,ininconsistentanalysis,thedatareadbythesecondtransactionwascommittedbythe
transactionthatmadethechange.Also,inconsistentanalysisinvolvesmultiplereads(twoormore)ofthe
samerowandeachtimetheinformationischangedbyanothertransactionthus,thetermnonrepeatable
read.Forexample,aneditorreadsthesamedocumenttwice,butbetweeneachreading,thewriterrewrites
thedocument.Whentheeditorreadsthedocumentforthesecondtime,ithaschanged.
PhantomReadsPhantomreadsoccurwhenaninsertordeleteactionisperformedagainstarowthat
belongstoarangeofrowsbeingreadbyatransaction.Thetransaction'sfirstreadoftherangeofrows
showsarowthatnolongerexistsinthesecondorsucceedingread,asaresultofadeletionbyadifferent
transaction.Similarly,astheresultofaninsertbyadifferenttransaction,thetransaction'ssecondor
succeedingreadshowsarowthatdidnotexistintheoriginalread.Forexample,aneditormakeschanges
toadocumentsubmittedbyawriter,butwhenthechangesareincorporatedintothemastercopyofthe
documentbytheproductiondepartment,theyfindthatnewuneditedmaterialhasbeenaddedtothe
documentbytheauthor.Thisproblemcouldbeavoidedifnoonecouldaddnewmaterialtothedocument
untiltheeditorandproductiondepartmentfinishworkingwiththeoriginaldocument.
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

14/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

85.nolock?WhatisthedifferencebetweentheREPEATABLEREADandSERIALIZEisolationlevels?
LockingHintsArangeoftablelevellockinghintscanbespecifiedusingtheSELECT,INSERT,
UPDATE,andDELETEstatementstodirectMicrosoftSQLServer2000tothetypeoflockstobeused.
Tablelevellockinghintscanbeusedwhenafinercontrolofthetypesoflocksacquiredonanobjectis
required.Theselockinghintsoverridethecurrenttransactionisolationlevelforthesession.
Lockinghint

Description

HOLDLOCK

Holdasharedlockuntilcompletionofthetransactioninsteadof
releasingthelockassoonastherequiredtable,row,ordata
pageisnolongerrequired.HOLDLOCKisequivalentto
SERIALIZABLE.

NOLOCK

Donotissuesharedlocksanddonothonorexclusivelocks.
Whenthisoptionisineffect,itispossibletoreadan
uncommittedtransactionorasetofpagesthatarerolledbackin
themiddleofaread.Dirtyreadsarepossible.Onlyappliesto
theSELECTstatement.

PAGLOCK

Usepagelockswhereasingletablelockwouldusuallybe
taken.

READCOMMITTED

Performascanwiththesamelockingsemanticsasa
transactionrunningattheREADCOMMITTEDisolationlevel.
Bydefault,SQLServer2000operatesatthisisolationlevel.

READPAST

Skiplockedrows.Thisoptioncausesatransactiontoskiprows
lockedbyothertransactionsthatwouldordinarilyappearinthe
resultset,ratherthanblockthetransactionwaitingfortheother
transactionstoreleasetheirlocksontheserows.The
READPASTlockhintappliesonlytotransactionsoperatingat
READCOMMITTEDisolationandwillreadonlypastrowlevel
locks.AppliesonlytotheSELECTstatement.

READUNCOMMITTED EquivalenttoNOLOCK.
REPEATABLEREAD

Performascanwiththesamelockingsemanticsasa
transactionrunningattheREPEATABLEREADisolationlevel.

ROWLOCK

Userowlevellocksinsteadofthecoarsergrainedpageand
tablelevellocks.

SERIALIZABLE

Performascanwiththesamelockingsemanticsasa
transactionrunningattheSERIALIZABLEisolationlevel.
EquivalenttoHOLDLOCK.

TABLOCK

Useatablelockinsteadofthefinergrainedroworpagelevel
locks.SQLServerholdsthislockuntiltheendofthestatement.
However,ifyoualsospecifyHOLDLOCK,thelockishelduntil
theendofthetransaction.

TABLOCKX

Useanexclusivelockonatable.Thislockpreventsothersfrom
readingorupdatingthetableandishelduntiltheendofthe
statementortransaction.

UPDLOCK

Useupdatelocksinsteadofsharedlockswhilereadingatable,
andholdlocksuntiltheendofthestatementortransaction.
UPDLOCKhastheadvantageofallowingyoutoreaddata
(withoutblockingotherreaders)andupdateitlaterwiththe
assurancethatthedatahasnotchangedsinceyoulastreadit.

XLOCK

Useanexclusivelockthatwillbehelduntiltheendofthe
transactiononalldataprocessedbythestatement.Thislock
canbespecifiedwitheitherPAGLOCKorTABLOCK,inwhich
casetheexclusivelockappliestotheappropriatelevelof
granularity.

86.Forexample,ifthetransactionisolationlevelissettoSERIALIZABLE,andthetablelevellockinghint
NOLOCKisusedwiththeSELECTstatement,keyrangelockstypicallyusedtomaintainserializable
transactionsarenottaken.
USEpubs
GO
SETTRANSACTIONISOLATIONLEVELSERIALIZABLE
GO
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

15/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

BEGINTRANSACTION
SELECTau_lnameFROMauthorsWITH(NOLOCK)
GO
87.Whatisescalationoflocks?
Lockescalationistheprocessofconvertingalotoflowlevellocks(likerowlocks,pagelocks)intohigher
levellocks(liketablelocks).Everylockisamemorystructuretoomanylockswouldmean,morememory
beingoccupiedbylocks.Topreventthisfromhappening,SQLServerescalatesthemanyfinegrainlocksto
fewercoarsegrainlocks.LockescalationthresholdwasdefinableinSQLServer6.5,butfromSQLServer
7.0onwardsit'sdynamicallymanagedbySQLServer.
VIEW
88.WhatisView?Use?SyntaxofView?
Aviewisavirtualtablemadeupofdatafrombasetablesandotherviews,butnotstoredseparately.
Viewssimplifyusersperceptionofthedatabase(canbeusedtopresentonlythenecessary
informationwhilehidingdetailsinunderlyingrelations)
Viewsimprovedatasecuritypreventingundesiredaccesses
Viewsfacilitetheprovisionofadditionaldataindependence

89.DoestheViewoccupymemoryspace?
No
90.Canudropatableifithasaview?
ViewsortablesparticipatinginaviewcreatedwiththeSCHEMABINDINGclausecannotbedropped.Ifthe
viewisnotcreatedusingSCHEMABINDING,thenwecandropthetable.
91.Whydoesn'tSQLServerpermitanORDERBYclauseinthedefinitionofaview?
SQLServerexcludesanORDERBYclausefromaviewtocomplywiththeANSISQL92standard.
Becauseanalyzingtherationaleforthisstandardrequiresadiscussionoftheunderlyingstructureofthe
structuredquerylanguage(SQL)andthemathematicsuponwhichitisbased,wecan'tfullyexplainthe
restrictionhere.However,ifyouneedtobeabletospecifyanORDERBYclauseinaview,considerusing
thefollowingworkaround:
USEpubs
GO
CREATEVIEWAuthorsByName
AS
SELECTTOP100PERCENT*
FROMauthors
ORDERBYau_lname,au_fname
GO
TheTOPconstruct,whichMicrosoftintroducedinSQLServer7.0,ismostusefulwhenyoucombineitwith
theORDERBYclause.TheonlytimethatSQLServersupportsanORDERBYclauseinaviewiswhenit
isusedinconjunctionwiththeTOPkeyword.(NotethattheTOPkeywordisaSQLServerextensiontothe
ANSISQL92standard.)
TRANSACTION
92.WhatisTransaction?
Atransactionisasequenceofoperationsperformedasasinglelogicalunitofwork.Alogicalunitofwork
mustexhibitfourproperties,calledtheACID(Atomicity,Consistency,Isolation,andDurability)properties,
toqualifyasatransaction:
AtomicityAtransactionmustbeanatomicunitofworkeitherallofitsdatamodificationsare
performedornoneofthemisperformed.
ConsistencyWhencompleted,atransactionmustleavealldatainaconsistentstate.Inarelational
database,allrulesmustbeappliedtothetransaction'smodificationstomaintainalldataintegrity.All
internaldatastructures,suchasBtreeindexesordoublylinkedlists,mustbecorrectattheendofthe
transaction.
IsolationModificationsmadebyconcurrenttransactionsmustbeisolatedfromthemodifications
madebyanyotherconcurrenttransactions.Atransactioneitherseesdatainthestateitwasinbefore
anotherconcurrenttransactionmodifiedit,oritseesthedataafterthesecondtransactionhas
completed,butitdoesnotseeanintermediatestate.Thisisreferredtoasserializabilitybecauseit
resultsintheabilitytoreloadthestartingdataandreplayaseriesoftransactionstoendupwiththe
datainthesamestateitwasinaftertheoriginaltransactionswereperformed.
DurabilityAfteratransactionhascompleted,itseffectsarepermanentlyinplaceinthesystem.The
modificationspersistevenintheeventofasystemfailure.

http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

16/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

93.AfteroneBeginTransactionatruncatestatementandaRollBackstatementsarethere.Willitbe
rollbacked?SincethetruncatestatementdoesnotperformloggedoperationhowdoesitRollBack?
Itwillrollback.
94.GivenaSQLlike
BeginTran
Select@@Rowcount
BeginTran
Select@@Rowcount
BeginTran
Select@@Rowcount
CommitTran
Select@@Rowcount
RollBack
Select@@Rowcount
RollBack
Select@@Rowcount
Whatisthevalueof@@Rowcountateachstmtlevels?
Ans:0zero.
@@ROWCOUNTReturnsthenumberofrowsaffectedbythelaststatement.
@@TRANCOUNTReturnsthenumberofactivetransactionsforthecurrentconnection.
EachBeginTranwilladdcount,eachcommitwillreducecountandONErollbackwillmakeit0.
OTHER
95.WhataretheconstraintsforTableConstraintsdefinerulesregardingthevaluesallowedincolumns
andarethestandardmechanismforenforcingintegrity.SQLServer2000supportsfiveclassesof
constraints.
NOTNULL
CHECK
UNIQUE
PRIMARYKEY
FOREIGNKEY
96.Thereare50columnsinatable.Writeaquerytogetfirst25columns
Ans:Needtomentioneachcolumnnames.
97.Howtolistallthetablesinaparticulardatabase?
USEpubs
GO
sp_help
98.Whatarecursors?Explaindifferenttypesofcursors.Whatarethedisadvantagesofcursors?How
canyouavoidcursors?
Cursorsallowrowbyrowprocessingoftheresultsets.
Typesofcursors:Static,Dynamic,Forwardonly,Keysetdriven.
Disadvantagesofcursors:Eachtimeyoufetcharowfromthecursor,itresultsinanetworkroundtrip.
Cursorsarealsocostlybecausetheyrequiremoreresourcesandtemporarystorage(resultsinmoreIO
operations).Further,therearerestrictionsontheSELECTstatementsthatcanbeusedwithsometypesof
cursors.
Howtoavoidcursor:
Mostofthetimes,setbasedoperationscanbeusedinsteadofcursors.Hereisanexample:Ifyou
havetogiveaflathiketoyouremployeesusingthefollowingcriteria:
Salarybetween30000and400005000hike
Salarybetween40000and550007000hike
Salarybetween55000and650009000hike
Inthissituationmanydeveloperstendtouseacursor,determineeachemployee'ssalaryandupdate
hissalaryaccordingtotheaboveformula.Butthesamecanbeachievedbymultipleupdate
statementsorcanbecombinedinasingleUPDATEstatementasshownbelow:
UPDATEtbl_empSETsalary=
CASEWHENsalaryBETWEEN30000AND40000THENsalary+5000
WHENsalaryBETWEEN40000AND55000THENsalary+7000
WHENsalaryBETWEEN55000AND65000THENsalary+10000
END
Youneedtocallastoredprocedurewhenacolumninaparticularrowmeetscertaincondition.You
don'thavetousecursorsforthis.ThiscanbeachievedusingWHILEloop,aslongasthereisa
uniquekeytoidentifyeachrow.ForexamplesofusingWHILEloopforrowbyrowprocessing,check
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

17/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

outthe'Mycodelibrary'sectionofmysiteorsearchforWHILE.

99.WhatisDynamicCursor?Suppose,Ihaveadynamiccursorattachedtotableinadatabase.Ihave
anothermeansbywhichIwillmodifythetable.Whatdoyouthinkwillthevaluesinthecursorbe?
Dynamiccursorsreflectallchangesmadetotherowsintheirresultsetwhenscrollingthroughthecursor.
Thedatavalues,order,andmembershipoftherowsintheresultsetcanchangeoneachfetch.All
UPDATE,INSERT,andDELETEstatementsmadebyallusersarevisiblethroughthecursor.Updatesare
visibleimmediatelyiftheyaremadethroughthecursorusingeitheranAPIfunctionsuchasSQLSetPosor
theTransactSQLWHERECURRENTOFclause.Updatesmadeoutsidethecursorarenotvisibleuntil
theyarecommitted,unlessthecursortransactionisolationlevelissettoreaduncommitted.
100.WhatisDATEPART?
Returnsanintegerrepresentingthespecifieddatepartofthespecifieddate.
101.DifferencebetweenDeleteandTruncate?
TRUNCATETABLEisfunctionallyidenticaltoDELETEstatementwithnoWHEREclause:bothremoveall
rowsinthetable.
(1)ButTRUNCATETABLEisfasterandusesfewersystemandtransactionlogresourcesthanDELETE.
TheDELETEstatementremovesrowsoneatatimeandrecordsanentryinthetransactionlogforeach
deletedrow.TRUNCATETABLEremovesthedatabydeallocatingthedatapagesusedtostorethetable's
data,andonlythepagedeallocationsarerecordedinthetransactionlog.
(2)BecauseTRUNCATETABLEisnotlogged,itcannotactivateatrigger.
(3)Thecounterusedbyanidentityfornewrowsisresettotheseedforthecolumn.Ifyouwanttoretain
theidentitycounter,useDELETEinstead.
Ofcourse,TRUNCATETABLEcanberolledback.
102.Whatareglobalvariables?Tellmesomeofthem?
TransactSQLglobalvariablesareaformoffunctionandarenowreferredtoasfunctions.
ABSReturnstheabsolute,positivevalueofthegivennumericexpression.
SUM
AVG
AND
103.WhatisDDL?
Datadefinitionlanguage(DDL)statementsareSQLstatementsthatsupportthedefinitionordeclarationof
databaseobjects(forexample,CREATETABLE,DROPTABLE,andALTERTABLE).
YoucanusetheADOCommandobjecttoissueDDLstatements.TodifferentiateDDLstatementsfroma
tableorstoredprocedurename,settheCommandTypepropertyoftheCommandobjecttoadCmdText.
BecauseexecutingDDLquerieswiththismethoddoesnotgenerateanyrecordsets,thereisnoneedfora
Recordsetobject.
104.WhatisDML?
DataManipulationLanguage(DML),whichisusedtoselect,insert,update,anddeletedataintheobjects
definedusingDDL
105.WhatarekeysinRDBMS?Whatisaprimarykey/foreignkey?
Therearetwokindsofkeys.
Aprimarykeyisasetofcolumnsfromatablethatareguaranteedtohaveuniquevaluesforeachrowof
thattable.
Foreignkeysareattributesofonetablethathavematchingvaluesinaprimarykeyinanothertable,
allowingforrelationshipsbetweentables.
106.WhatisthedifferencebetweenPrimaryKeyandUniqueKey?
Bothprimarykeyanduniquekeyenforceuniquenessofthecolumnonwhichtheyaredefined.Butby
defaultprimarykeycreatesaclusteredindexonthecolumn,whereareuniquecreatesanonclusteredindex
bydefault.Anothermajordifferenceisthat,primarykeydoesn'tallowNULLs,butuniquekeyallowsone
NULLonly.
107.Definecandidatekey,alternatekey,compositekey?
Acandidatekeyisonethatcanidentifyeachrowofatableuniquely.Generallyacandidatekeybecomes
theprimarykeyofthetable.Ifthetablehasmorethanonecandidatekey,oneofthemwillbecomethe
primarykey,andtherestarecalledalternatekeys.
Akeyformedbycombiningatleasttwoormorecolumnsiscalledcompositekey.
108.WhatistheReferentialIntegrity?
Referentialintegrityreferstotheconsistencythatmustbemaintainedbetweenprimaryandforeignkeys,
i.e.everyforeignkeyvaluemusthaveacorrespondingprimarykeyvalue.
109.Whataredefaults?Isthereacolumntowhichadefaultcan'tbebound?
Adefaultisavaluethatwillbeusedbyacolumn,ifnovalueissuppliedtothatcolumnwhileinsertingdata.
IDENTITYcolumnsandtimestampcolumnscan'thavedefaultsboundtothem.
110. WhatisQueryoptimization?Howistuningaperformanceofquerydone?
111. Whatistheuseofshellcommands?xp_cmdshell
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

18/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

Executesagivencommandstringasanoperatingsystemcommandshellandreturnsanyoutputasrows
oftext.Grantsnonadministrativeuserspermissionstoexecutexp_cmdshell.
112. Whatisuseofshrinkdatabase?
MicrosoftSQLServer2000allowseachfilewithinadatabasetobeshrunktoremoveunusedpages.Both
dataandtransactionlogfilescanbeshrunk.
113. Iftheperformanceofthequerysuddenlydecreasedwhereyouwillcheck?
114. Whatisapassthroughquery?
MicrosoftSQLServer2000sendspassthroughqueriesasuninterpretedquerystringstoanOLEDBdata
source.ThequerymustbeinasyntaxtheOLEDBdatasourcewillaccept.ATransactSQLstatement
usestheresultsfromapassthroughqueryasthoughitisaregulartablereference.
ThisexampleusesapassthroughquerytoretrievearesultsetfromaMicrosoftAccessversionofthe
Northwindsampledatabase.
SELECT*
FROMOpenRowset('Microsoft.Jet.OLEDB.4.0',
'c:\northwind.mdb''admin''',
'SELECTCustomerID,CompanyName
FROMCustomers
WHERERegion=''WA''')
115. HowdoyoudifferentiateLocalandGlobalTemporarytable?
Youcancreatelocalandglobaltemporarytables.Localtemporarytablesarevisibleonlyinthecurrent
sessionglobaltemporarytablesarevisibletoallsessions.Prefixlocaltemporarytablenameswithsingle
numbersign(#table_name),andprefixglobaltemporarytablenameswithadoublenumbersign
(##table_name).SQLstatementsreferencethetemporarytableusingthevaluespecifiedfortable_namein
theCREATETABLEstatement:
CREATETABLE#MyTempTable(colaINTPRIMARYKEY)
INSERTINTO#MyTempTableVALUES(1)
116. HowtheExistskeywordworksinSQLServer?
USEpubs
SELECTau_lname,au_fname
FROMauthors
WHEREexists
(SELECT*
FROMpublishers
WHEREauthors.city=publishers.city)
WhenasubqueryisintroducedwiththekeywordEXISTS,itfunctionsasanexistencetest.TheWHERE
clauseoftheouterquerytestsfortheexistenceofrowsreturnedbythesubquery.Thesubquerydoesnot
actuallyproduceanydataitreturnsavalueofTRUEorFALSE.
117. ANY?
USEpubs
SELECTau_lname,au_fname
FROMauthors
WHEREcity=ANY
(SELECTcity
FROMpublishers)
118. toselectdatepartonly
SELECTCONVERT(char(10),GetDate(),101)
toselecttimepartonly
SELECTright(GetDate(),7)
119. HowcanIsendamessagetouserfromtheSQLServer?
Youcanusethexp_cmdshellextendedstoredproceduretorunnetsendcommand.Thisistheexampleto
sendthe'Hello'messagetoJOHN:
EXECmaster..xp_cmdshell"netsendJOHN'Hello'"
TogetnetsendmessageontheWindows9xmachines,youshouldruntheWinPopuputility.Youcanplace
WinPopupintheStartupgroupunderProgramFiles.
120.Whatisnormalization?Explaindifferentlevelsofnormalization?ExplainThirdnormalizationform
withanexample?
Theprocessofrefiningtables,keys,columns,andrelationshipstocreateanefficientdatabaseiscalled
normalization.Thisshouldeliminatesunnecessaryduplicationandprovidesarapidsearchpathtoall
necessaryinformation.
Someofthebenefitsofnormalizationare:
Dataintegrity(becausethereisnoredundant,neglecteddata)
Optimizedqueries(becausenormalizedtablesproducerapid,efficientjoins)
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

19/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

Fasterindexcreationandsorting(becausethetableshavefewercolumns)
FasterUPDATEperformance(becausetherearefewerindexespertable)
Improvedconcurrencyresolution(becausetablelockswillaffectlessdata)
Eliminateredundancy
Thereareafewrulesfordatabasenormalization.Eachruleiscalleda"normalform."Ifthefirstruleis
observed,thedatabaseissaidtobein"firstnormalform."Ifthefirstthreerulesareobserved,the
databaseisconsideredtobein"thirdnormalform."Althoughotherlevelsofnormalizationarepossible,
thirdnormalformisconsideredthehighestlevelnecessaryformostapplications.

1.FirstNormalForm(1NF)
Eliminaterepeatinggroupsinindividualtables
Createaseparatetableforeachsetofrelateddata.
Identifyeachsetofrelateddatawithaprimarykey.
Donotusemultiplefieldsinasingletabletostoresimilardata.
Example
Subordinate1

Subordinate2

Subordinate3

Subordinate4

Bob

Jim

Mary

Beth

Mary

Mike

Jason

Carol

Mark

Jim

Alan

Eliminateduplicativecolumnsfromthesametable.Clearly,theSubordinate1Subordinate4
columnsareduplicative.Whathappenswhenweneedtoaddorremoveasubordinate?
Subordinates
Bob

Jim,Mary,Beth

Mary

Mike,Jason,Carol,Mark

Jim

Alan

Thissolutioniscloser,butitalsofallsshortofthemark.Thesubordinatescolumnisstill
duplicativeandnonatomic.Whathappenswhenweneedtoaddorremoveasubordinate?We
needtoreadandwritetheentirecontentsofthetable.Thatsnotabigdealinthissituation,but
whatifonemanagerhadonehundredemployees?Also,itcomplicatestheprocessofselecting
datafromthedatabaseinfuturequeries.
Solution:
Subordinate
Bob

Jim

Bob

Mary

Bob

Beth

Mary

Mike

Mary

Jason

Mary

Carol

Mary

Mark

Jim

Alan

2.SecondNormalForm(2NF)
Createseparatetablesforsetsofvaluesthatapplytomultiplerecords.
Relatethesetableswithaforeignkey.
Recordsshouldnotdependonanythingotherthanatable'sprimarykey(acompoundkey,if
necessary).
Forexample,consideracustomer'saddressinanaccountingsystem.Theaddressisneeded
bytheCustomerstable,butalsobytheOrders,Shipping,Invoices,AccountsReceivable,and
Collectionstables.Insteadofstoringthecustomer'saddressasaseparateentryineachof
thesetables,storeitinoneplace,eitherintheCustomerstableorinaseparateAddresses
table.

3.ThirdNormalForm(3NF)
Eliminatefieldsthatdonotdependonthekey.
Valuesinarecordthatarenotpartofthatrecord'skeydonotbelonginthetable.Ingeneral,any
timethecontentsofagroupoffieldsmayapplytomorethanasinglerecordinthetable,
considerplacingthosefieldsinaseparatetable.
Forexample,inanEmployeeRecruitmenttable,acandidate'suniversitynameandaddress
maybeincluded.Butyouneedacompletelistofuniversitiesforgroupmailings.Ifuniversity
informationisstoredintheCandidatestable,thereisnowaytolistuniversitieswithnocurrent
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

20/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

candidates.CreateaseparateUniversitiestableandlinkittotheCandidatestablewitha
universitycodekey.
AnotherExample:
MemberId

Name

Company

CompanyLoc

JohnSmith

ABC

Alabama

DaveJones

MCI

Florida

TheMembertablesatisfiesfirstnormalformitcontainsnorepeatinggroups.Itsatisfies
secondnormalformsinceitdoesn'thaveamultivaluedkey.ButthekeyisMemberID,andthe
companynameandlocationdescribeonlyacompany,notamember.Toachievethirdnormal
form,theymustbemovedintoaseparatetable.Sincetheydescribeacompany,CompanyCode
becomesthekeyofthenew"Company"table.
Themotivationforthisisthesameforsecondnormalform:wewanttoavoidupdateanddelete
anomalies.Forexample,supposenomembersfromtheIBMwerecurrentlystoredinthe
database.Withthepreviousdesign,therewouldbenorecordofitsexistence,eventhough20
pastmemberswerefromIBM!
MemberTable
MemberId

Name

CID

JohnSmith

DaveJones

CId

Name

Location

ABC

Alabama

MCI

Florida

CompanyTable

4.BoyceCoddNormalForm(BCNF)
ArelationisinBoyce/Coddnormalformifandonlyiftheonlydeterminantsarecandidatekey.Itsa
differentversionof3NF,indeed,wasmeanttoreplaceit.[Adeterminantisanyattributeonwhich
someotherattributeis(fully)functionallydependent.]
5.4thNormalForm(4NF)
Atableisin4NFifitisinBCNFandifithasnomultivalueddependencies.Thisappliesprimarilyto
keyonlyassociativetables,andappearsasaternaryrelationship,buthasincorrectlymerged2
distinct,independentrelationships.
Eg:Thiscouldbeany2M:Mrelationshipsfromasingleentity.Forinstance,amembercouldknow
manysoftwaretools,andasoftwaretoolmaybeusedbymanymembers.Also,amembercouldhave
recommendedmanybooks,andabookcouldberecommendedbymanymembers.

Software

member

Book

6.Thecorrectsolution,tocausethemodeltobein4thnormalform,istoensurethatallM:M
relationshipsareresolvedindependentlyiftheyareindeedindependent.
Software

membersoftware

member

memberBook

book

7.5thNormalForm(5NF)(PJNF)
Atableisin5NF,alsocalled"ProjectionJoinNormalForm",ifitisin4NFandifeveryjoindependency
inthetableisaconsequenceofthecandidatekeysofthetable.
8.Domain/keynormalform(DKNF).Akeyuniquelyidentifieseachrowinatable.Adomainistheset
ofpermissiblevaluesforanattribute.Byenforcingkeyanddomainrestrictions,thedatabaseis
assuredofbeingfreedfrommodificationanomalies.DKNFisthenormalizationlevelthatmost
designersaimtoachieve.
Remember,thesenormalizationguidelinesarecumulative.Foradatabasetobein2NF,itmustfirst
fulfillallthecriteriaofa1NFdatabase.

121.Ifadatabaseisnormalizedby3NFthenhowmanynumberoftablesitshouldcontaininminimum?
Howmanyminimumif2NFand1NF?
122.Whatisdenormalizationandwhenwouldyougoforit?
Asthenameindicates,denormalizationisthereverseprocessofnormalization.It'sthecontrolled
introductionofredundancyintothedatabasedesign.Ithelpsimprovethequeryperformanceasthenumber
ofjoinscouldbereduced.
123.HowcanIrandomlysortqueryresults?
Torandomlyorderrows,ortoreturnxnumberofrandomlychosenrows,youcanusetheRANDfunction
insidetheSELECTstatement.ButtheRANDfunctionisresolvedonlyoncefortheentirequery,soevery
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

21/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

rowwillgetsamevalue.YoucanuseanORDERBYclausetosorttherowsbytheresultfromtheNEWID
function,asthefollowingcodeshows:
SELECT*
FROMNorthwind..Orders
ORDERBYNEWID()
124.sp_who
ProvidesinformationaboutcurrentMicrosoftSQLServerusersandprocesses.Theinformationreturned
canbefilteredtoreturnonlythoseprocessesthatarenotidle.
125.HaveyouworkedonDynamicSQL?HowwillYouhandled(DoubleQuotes)inDynamicSQL?
126.Howtofinddependentsofatable?
Verifydependencieswithsp_dependsbeforedroppinganobject
127.WhatisthedifferencebetweenaCONSTRAINTANDRULE?
RulesareabackwardcompatibilityfeaturethatperformsomeofthesamefunctionsasCHECK
constraints.CHECKconstraintsarethepreferred,standardwaytorestrictthevaluesinacolumn.CHECK
constraintsarealsomoreconcisethanrulestherecanonlybeoneruleappliedtoacolumn,butmultiple
CHECKconstraintscanbeapplied.CHECKconstraintsarespecifiedaspartoftheCREATETABLE
statement,whilerulesarecreatedasseparateobjectsandthenboundtothecolumn.
128.HowtocallaCOMdllfromSQLServer2000?
sp_OACreateCreatesaninstanceoftheOLEobjectonaninstanceofMicrosoftSQLServer
Syntax
sp_OACreateprogid,|clsid,
objecttokenOUTPUT
[,context]
contextSpecifiestheexecutioncontextinwhichthenewlycreatedOLEobjectruns.Ifspecified,this
valuemustbeoneofthefollowing:
1=Inprocess(.dll)OLEserveronly
4=Local(.exe)OLEserveronly
5=BothinprocessandlocalOLEserverallowed
Examples
A.UseProgIDThisexamplecreatesaSQLDMOSQLServerobjectbyusingitsProgID.

DECLARE@objectint
DECLARE@hrint
DECLARE@srcvarchar(255),@descvarchar(255)
EXEC@hr=sp_OACreate'SQLDMO.SQLServer',@objectOUT
IF@hr<>0
BEGIN
EXECsp_OAGetErrorInfo@object,@srcOUT,@descOUT
SELECThr=convert(varbinary(4),@hr),Source=@src,Description=@desc
RETURN
END
B.UseCLSIDThisexamplecreatesaSQLDMOSQLServerobjectbyusingitsCLSID.

DECLARE@objectint
DECLARE@hrint
DECLARE@srcvarchar(255),@descvarchar(255)
EXEC@hr=sp_OACreate'{00026BA100000000C000000000000046}',
@objectOUT
IF@hr<>0
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

22/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

BEGIN
EXECsp_OAGetErrorInfo@object,@srcOUT,@descOUT
SELECThr=convert(varbinary(4),@hr),Source=@src,Description=@desc
RETURN
END
129.Differencebetweensysusersandsyslogins?
sysusersContainsonerowforeachMicrosoftWindowsuser,Windowsgroup,MicrosoftSQLServer
user,orSQLServerroleinthedatabase.
sysloginsContainsonerowforeachloginaccount.
130.WhatistherowsizeinSQLServer2000?
8060bytes.
131.Howwillyoufindstructureoftable,alltables/viewsinonedb,alldbs?
//structureoftable
sp_helpdbtbl_emp
//listofalldatabases
sp_helpdb
OR
SELECT*FROMmaster.dbo.sysdatabases
//detailsaboutdatabasepubs..mdf,.ldffilelocations,sizeofdatabase
sp_helpdbpubs
//listsalltablesundercurrentdatabase
sp_tables
OR
SELECT*FROMinformation_schema.tablesWHERE(table_type='basetable')
OR
SELECT*FROMsysobjectsWHEREtype='U'//faster
132.Btreeindexesordoublylinkedlists?
133.Whatisthesystemfunctiontogetthecurrentuser'suserid?
USER_ID().AlsocheckoutothersystemfunctionslikeUSER_NAME(),SYSTEM_USER,
SESSION_USER,CURRENT_USER,USER,SUSER_SID(),HOST_NAME().
134.WhataretheseriesofstepsthathappenonexecutionofaqueryinaQueryAnalyzer?
1)Syntaxchecking2)Parsing3)Executionplan
135.Whichevent(Checkconstraints,ForeignKey,Rule,trigger,Primarykeycheck)willbeperformed
lastforintegritycheck?
IdentityInsertCheck
Nullabilityconstraint
Datatypecheck
Insteadoftrigger
Primarykey
Checkconstraint
Foreignkey
DMLExecution(updatestatements)
AfterTrigger

136.Howwillyoushowmanytomanyrelationinsql?
Create3rdtablewith2columnswhichhavingonetomanyrelationtothesetables.
137.Whenaqueryissenttothedatabaseandanindexisnotbeingused,whattypeofexecutionis
takingplace?
Atablescan.
138.Whatis#,##,@,@@means?
@@Systemvariables
@userdefinedvariables
139.WhatisthedifferencebetweenaLocaltemporarytableandaGlobaltemporarytable?Howiseach
onedenoted?
Localtemporarytablewillbeaccessibletoonlycurrentusersession,itsnamewillbeprecededwitha
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

23/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

singlehash(#mytable)
Globaltemporarytablewillbeaccessibletoallusers,&itwillbedroppedonlyafterendingofallactive
connections,itsnamewillbeprecededwithdoublehash(##mytable)
140.WhatiscoveredqueriesinSQLServer?
141.WhatisHASHJOIN,MERGEJOIN?
TOOLS
142.HaveyoueverusedDBCCcommand?Giveanexampleforit.
TheTransactSQLprogramminglanguageprovidesDBCCstatementsthatactasDatabaseConsole
CommandsforMicrosoftSQLServe2000.Thesestatementscheckthephysicalandlogical
consistencyofadatabase.ManyDBCCstatementscanfixdetectedproblems.DatabaseConsole
Commandstatementsaregroupedintothesecategories.
Statementcategory

Perform

Maintenance
statements

Maintenancetasksonadatabase,index,orfilegroup.

Miscellaneous
statements

Miscellaneoustaskssuchasenablingrowlevellockingorremovingadynamiclink
library(DLL)frommemory.

Statusstatements

Statuschecks.

Validation
statements

Validationoperationsonadatabase,table,index,catalog,filegroup,systemtables,or
allocationofdatabasepages.

DBCCCHECKDB,DBCCCHECKTABLE,DBCCCHECKCATALOG,DBCCCHECKALLOC,DBCC
SHOWCONTIG,DBCCSHRINKDATABASE,DBCCSHRINKFILEetc.

143.WhatistheoutputofDBCCShowcontigstatement?
Displaysfragmentationinformationforthedataandindexesofthespecifiedtable.
144.HowdoIresettheidentitycolumn?
YoucanusetheDBCCCHECKIDENTstatement,ifyouwanttoresetorreseedtheidentitycolumn.For
example,ifyouneedtoforcethecurrentidentityvalueinthejobstabletoavalueof100,youcanusethe
following:
USEpubs
GO
DBCCCHECKIDENT(jobs,RESEED,100)
GO
145.AboutSQLCommandlineexecutables
Utilities
bcp
console
isql
sqlagent
sqldiag
sqlmaint
sqlservr
vswitch
dtsrun
dtswiz
isqlw
itwiz
odbccmpt
osql
rebuildm
sqlftwiz
distrib
logread
replmerg
snapshot
scm
regxmlss

146.WhatisDTC?
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

24/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

TheMicrosoftDistributedTransactionCoordinator(MSDTC)isatransactionmanagerthatallowsclient
applicationstoincludeseveraldifferentsourcesofdatainonetransaction.MSDTCcoordinatescommitting
thedistributedtransactionacrossalltheserversenlistedinthetransaction.
147.WhatisDTS?AnydrawbacksinusingDTS?
MicrosoftSQLServer2000DataTransformationServices(DTS)isasetofgraphicaltoolsand
programmableobjectsthatletsyouextract,transform,andconsolidatedatafromdisparatesourcesinto
singleormultipledestinations.
148.WhatisBCP?
ThebcputilitycopiesdatabetweenaninstanceofMicrosoftSQLServer2000andadatafileinauser
specifiedformat.
C:\DocumentsandSettings\sthomas>bcp
usage:bcp{dbtable|query}{in|out|queryout|format}datafile
[mmaxerrors][fformatfile][eerrfile]
[Ffirstrow][Llastrow][bbatchsize]
[nnativetype][ccharactertype][wwidecharactertype]
[Nkeepnontextnative][Vfileformatversion][qquotedidentifier]
[Ccodepagespecifier][tfieldterminator][rrowterminator]
[iinputfile][ooutfile][apacketsize]
[Sservername][Uusername][Ppassword]
[Ttrustedconnection][vversion][Rregionalenable]
[kkeepnullvalues][Ekeepidentityvalues]
[h"loadhints"]
149.HowcanIcreateaplaintextflatfilefromSQLServerasinputtoanotherapplication?
OneofthepurposesofExtensibleMarkupLanguage(XML)istosolvechallengeslikethis,butuntilall
applicationsbecomeXMLenabled,considerusingourfaithfulstandby,thebulkcopyprogram(bcp)utility.
Thisutilitycandomorethanjustdumpatablebcpalsocantakeitsinputfromaviewinsteadoffroma
table.Afteryouspecifyaviewastheinputsource,youcanlimittheoutputtoasubsetofcolumnsortoa
subsetofrowsbyselectingappropriatefiltering(WHEREandHAVING)clauses.
Moreimportant,byusingaview,youcanexportdatafrommultiplejoinedtables.Theonlythingyoucannot
doisspecifythesequenceinwhichtherowsarewrittentotheflatfile,becauseaviewdoesnotletyou
includeanORDERBYclauseinitunlessyoualsousetheTOPkeyword.
Ifyouwanttogeneratethedatainaparticularsequenceorifyoucannotpredictthecontentofthedatayou
wanttoexport,beawarethatinadditiontoaview,bcpalsosupportsusinganactualquery.Theonly
"gotcha"aboutusingaqueryinsteadofatableorviewisthatyoumustspecifyqueryoutinplaceofoutin
thebcpcommandline.
Forexample,youcanusebcptogeneratefromthepubsdatabasealistofauthorswhoresideinCalifornia
bywritingthefollowingcode:
bcp"SELECT*FROMpubs..authorsWHEREstate='CA'"queryoutc:\CAauthors.txt
cTS
150.Whatarethedifferentwaysofmovingdata/databasesbetweenserversanddatabasesinSQLServer?
Therearelotsofoptionsavailable,youhavetochooseyouroptiondependinguponyourrequirements.
Someoftheoptionsyouhaveare:BACKUP/RESTORE,detachingandattachingdatabases,replication,
DTS,BCP,logshipping,INSERT...SELECT,SELECT...INTO,creatingINSERTscriptstogeneratedata.
151.HowwillIexportdatabase?
ThroughDTSImport/Exportwizard
BackupthroughComplete/Differential/TransactionLog
152.Howtoexportdatabaseataparticulartime,everyweek?
BackupSchedule
DTSSchedule
Jobscreateanewjob
153.HowdoyouloadlargedatatotheSQLserverdatabase?
bcp
154.Howdoyoutransferdatafromtextfiletodatabase(otherthanDTS)?
bcp
155.WhatisOSQLandISQLutility?
TheosqlutilityallowsyoutoenterTransactSQLstatements,systemprocedures,andscriptfiles.This
utilityusesODBCtocommunicatewiththeserver.
TheisqlutilityallowsyoutoenterTransactSQLstatements,systemprocedures,andscriptfilesanduses
DBLibrarytocommunicatewithMicrosoftSQLServer2000.
AllDBLibraryapplications,suchasisql,workasSQLServer6.5levelclientswhenconnectedtoSQL
Server2000.TheydonotsupportsomeSQLServer2000features.
TheosqlutilityisbasedonODBCanddoessupportallSQLServer2000features.Useosqltorunscripts
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

25/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

thatisqlcannotrun.
156.WhatToolyouhaveusedforcheckingQueryOptimization?Whatistheuseofprofilerinsql
server?WhatisthefirstthingulookatinaSQLProfiler?
SQLProfilerisagraphicaltoolthatallowssystemadministratorstomonitoreventsinaninstanceof
MicrosoftSQLServer.YoucancaptureandsavedataabouteacheventtoafileorSQLServertableto
analyzelater.Forexample,youcanmonitoraproductionenvironmenttoseewhichstoredproceduresis
hamperingperformancebyexecutingtooslowly.
UseSQLProfilerto:
MonitortheperformanceofaninstanceofSQLServer.
DebugTransactSQLstatementsandstoredprocedures.
Identifyslowexecutingqueries.
TestSQLstatementsandstoredproceduresinthedevelopmentphaseofaprojectbysinglestepping
throughstatementstoconfirmthatthecodeworksasexpected.
TroubleshootproblemsinSQLServerbycapturingeventsonaproductionsystemandreplayingthem
onatestsystem.Thisisusefulfortestingordebuggingpurposesandallowsuserstocontinueusing
theproductionsystemwithoutinterference.
AuditandreviewactivitythatoccurredonaninstanceofSQLServer.Thisallowsasecurity
administratortoreviewanyoftheauditingevents,includingthesuccessandfailureofaloginattempt
andthesuccessandfailureofpermissionsinaccessingstatementsandobjects.
Permissions

157.Ifauserdoesnothavepermissiononatable,buthehaspermissiontoaviewcreatedonit,willhe
beabletoviewthedataintable?
Yes.
158.Afterremovingatablefromdatabase,whatotherrelatedobjectshavetobedroppedexplicitly?
(view,SP)
159.DifferentAuthenticationmodesinSqlserver?Ifauserisloggedunderwindowsauthentication
mode,howtofindhisuserid?
ThereareThreeDifferentauthenticationmodesinsqlserver.
14.WindowsAuthenticationMode
15.SqlServerAuthenticationMode
16.MixedAuthenticationMode
system_usersystemfunctioninsqlservertofetchtheloggedonusername.

160.Givetheconnectionstringsfromfrontendforbothtypelogins(windows,sqlserver)?
ThisarespecificallyforsqlservernotforanyotherRDBMS
DataSource=MySQLServerInitialCatalog=NORTHWINDIntegratedSecurity=SSPI
(windows)
DataSource=MySQLServerInitialCatalog=NORTHWINDUid=Pwd=(sqlserver)
161.WhatarethreeSQLkeywordsusedtochangeorsetsomeonespermissions?
Grant,DenyandRevoke
Administration
162.DifferenttypesofBackups?
Afulldatabasebackupisafullcopyofthedatabase.
Atransactionlogbackupcopiesonlythetransactionlog.
Adifferentialbackupcopiesonlythedatabasepagesmodifiedafterthelastfulldatabasebackup.
Afileorfilegrouprestoreallowstherecoveryofjusttheportionofadatabasethatwasonthefailed
disk.

163.WhatarejobsinSQLServer?Howdowecreateone?Whatistasks?
UsingSQLServerAgentjobs,youcanautomateadministrativetasksandrunthemonarecurringbasis.
164.Whatisdatabasereplication?WhatarethedifferenttypesofreplicationyoucansetupinSQL
Server?Howaretheyused?WhatissnapshotreplicationhowisitdifferentfromTransactional
replication?
Replicationistheprocessofcopying/movingdatabetweendatabasesonthesameordifferentservers.
SQLServersupportsthefollowingtypesofreplicationscenarios:
SnapshotreplicationItdistributesdataexactlyasitappearsataspecificmomentintimeanddoesnt
monitorforupdates.Itcanbeusedwhendatachangesareinfrequent.Itisoftenusedforbrowsing
datasuchaspricelists,onlinecatalog,ordatafordecisionsupportwherethecurrentdataisnot
requiredanddataisusedasreadonly.
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

26/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

Transactionalreplication(withimmediateupdatingsubscribers,withqueuedupdatingsubscribers)
Withthisaninitialsnapshotofdataisapplied,andwheneverdatamodificationsaremadeatthe
publisher,theindividualtransactionsarecapturedandpropagatedtothesubscribers.
MergereplicationItistheprocessofdistributingthedatabetweenpublisherandsubscriber,itallows
thepublisherandsubscribertoupdatethedatawhileconnectedordisconnected,andthenmergingthe
updatesbetweenthesiteswhentheyareconnected.

165.HowcanulookatwhataretheprocessrunningonSQLserver?HowcanyoukillaprocessinSQL
server?
Expandaservergroup,andthenexpandaserver.
ExpandManagement,andthenexpandCurrentActivity.
ClickProcessInfo.Thecurrentserveractivityisdisplayedinthedetailspane.
Inthedetailspane,rightclickaProcessID,andthenclickKillProcess.

166.WhatisRAIDandwhataredifferenttypesofRAIDconfigurations?
RAIDstandsforRedundantArrayofInexpensiveDisks,usedtoprovidefaulttolerancetodatabase
servers.TherearesixRAIDlevels0through5offeringdifferentlevelsofperformance,faulttolerance.
167.
Someofthetools/waysthathelpyoutroubleshootingperformanceproblemsare:SETSHOWPLAN_ALL
ON,SETSHOWPLAN_TEXTON,SETSTATISTICSIOON,SQLServerProfiler,WindowsNT/2000
Performancemonitor,GraphicalexecutionplaninQueryAnalyzer.
168.HowtodeterminetheservicepackcurrentlyinstalledonSQLServer?
Theglobalvariable@@Versionstoresthebuildnumberofthesqlservr.exe,whichisusedtodeterminethe
servicepackinstalled.
eg:MicrosoftSQLServer20008.00.760(IntelX86)Dec17200214:22:05Copyright(c)19882003
MicrosoftCorporationEnterpriseEditiononWindowsNT5.0(Build2195:ServicePack3)
169.WhatisthepurposeofusingCOLLATEinaquery?
Theterm,collation,referstoasetofrulesthatdeterminehowdataissortedandcompared.InMicrosoft
SQLServer2000,itisnotrequiredtoseparatelyspecifycodepageandsortorderforcharacterdata,and
thecollationusedforUnicodedata.Instead,specifythecollationnameandsortingrulestouse.Character
dataissortedusingrulesthatdefinethecorrectcharactersequence,withoptionsforspecifyingcase
sensitivity,accentmarks,kanacharactertypes,andcharacterwidth.MicrosoftSQLServer2000collations
includethesegroupings:
WindowscollationsWindowscollationsdefinerulesforstoringcharacterdatabasedontherules
definedforanassociatedWindowslocale.ThebaseWindowscollationrulesspecifywhichalphabetor
languageisusedwhendictionarysortingisapplied,aswellasthecodepageusedtostorenon
Unicodecharacterdata.ForWindowscollations,thenchar,nvarchar,andntextdatatypeshavethe
samesortingbehavioraschar,varchar,andtextdatatypes
SQLcollationsSQLcollationsareprovidedforcompatibilitywithsortordersinearlierversionsof
MicrosoftSQLServer.
SortOrder
Binaryisthefastestsortingorder,andiscasesensitive.IfBinaryisselected,theCasesensitive,
Accentsensitive,Kanasensitive,andWidthsensitiveoptionsarenotavailable.
Sortorder

Description

Binary

SortsandcomparesdatainMicrosoftSQLServertablesbasedonthebit
patternsdefinedforeachcharacter.Binarysortorderiscasesensitive,thatis
lowercaseprecedesuppercase,andaccentsensitive.Thisisthefastestsorting
order.
Ifthisoptionisnotselected,SQLServerfollowssortingandcomparisonrulesas
definedindictionariesfortheassociatedlanguageoralphabet.

Case
sensitive

SpecifiesthatSQLServerdistinguishbetweenuppercaseandlowercaseletters.
Ifnotselected,SQLServerconsiderstheuppercaseandlowercaseversionsof
letterstobeequal.SQLServerdoesnotdefinewhetherlowercaseletterssortlower
orhigherinrelationtouppercaseletterswhenCasesensitiveisnotselected.

Accent
sensitive

SpecifiesthatSQLServerdistinguishbetweenaccentedandunaccentedcharacters.
Forexample,'a'isnotequalto''.
Ifnotselected,SQLServerconsiderstheaccentedandunaccentedversionsof
letterstobeequal.

Kana

SpecifiesthatSQLServerdistinguishbetweenthetwotypesofJapanesekana

sensitive
characters:HiraganaandKatakana.
InterviewQuestionsandanswersforAll

search

Ifnotselected,SQLServerconsidersHiraganaandKatakanacharacterstobeequal.

http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

27/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

Width
SpecifiesthatSQLServerdistinguishbetweenasinglebytecharacter(halfwidth)
Classic Flipcard Magazine Mosaic Sidebar Snapshot
sensitive
andthesamecharacterwhenrepresentedasadoublebytecharacter(fullwidth).
Ifnotselected,SQLServerconsidersthesinglebyteanddoublebyterepresentation
Timeslide
2
Asp.NetInterview
ofthesamecharactertobeequal.
Windowscollationoptions:

HRInterviewQue

SQLServerFreq

C#InterviewQue

C#InterviewQue

InterviewQuestio

UseLatin1_GeneralfortheU.S.Englishcharacterset(codepage1252).
UseModern_SpanishforallvariationsofSpanish,whichalsousethesamecharactersetasU.S.
English(codepage1252).
UseArabicforallvariationsofArabic,whichusetheArabiccharacterset(codepage1256).
UseJapanese_UnicodefortheUnicodeversionofJapanese(codepage932),whichhasadifferent
sortorderfromJapanese,butthesamecodepage(932).

169.WhatistheSTUFFFunctionandhowdoesitdifferfromtheREPLACEfunction?
STUFFDeletesaspecifiedlengthofcharactersandinsertsanothersetofcharactersataspecified
startingpoint.
SELECTSTUFF('abcdef',2,3,'ijklmn')
GO
Hereistheresultset:

aijklmnef
REPLACEReplacesalloccurrencesofthesecondgivenstringexpressioninthefirststringexpression
withathirdexpression.
SELECTREPLACE('abcdefghicde','cde','xxx')
GO
Hereistheresultset:

abxxxfghixxx

171.Whatdoesitmeantohavequoted_identifieron?Whataretheimplicationsofhavingitoff?
WhenSETQUOTED_IDENTIFIERisOFF(default),literalstringsinexpressionscanbedelimitedbysingle
ordoublequotationmarks.
WhenSETQUOTED_IDENTIFIERisON,allstringsdelimitedbydoublequotationmarksareinterpretedas
objectidentifiers.Therefore,quotedidentifiersdonothavetofollowtheTransactSQLrulesforidentifiers.
SETQUOTED_IDENTIFIERmustbeONwhencreatingormanipulatingindexesoncomputedcolumnsor
indexedviews.IfSETQUOTED_IDENTIFIERisOFF,CREATE,UPDATE,INSERT,andDELETE
statementsontableswithindexesoncomputedcolumnsorindexedviewswillfail.
TheSQLServerODBCdriverandMicrosoftOLEDBProviderforSQLServerautomaticallyset
QUOTED_IDENTIFIERtoONwhenconnecting.
Whenastoredprocedureiscreated,theSETQUOTED_IDENTIFIERandSETANSI_NULLSsettingsare
capturedandusedforsubsequentinvocationsofthatstoredprocedure.Whenexecutedinsideastored
procedure,thesettingofSETQUOTED_IDENTIFIERisnotchanged.
SETQUOTED_IDENTIFIEROFF
GO
Attempttocreateatablewithareservedkeywordasaname
shouldfail.
CREATETABLE"select"("identity"intIDENTITY,"order"int)
GO
SETQUOTED_IDENTIFIERON
GO
Willsucceed.
CREATETABLE"select"("identity"intIDENTITY,"order"int)
GO
172.WhatisthepurposeofUPDATESTATISTICS?
Updatesinformationaboutthedistributionofkeyvaluesforoneormorestatisticsgroups(collections)inthe
specifiedtableorindexedview.
173.FundamentalsofDatawarehousing&olap?
174.WhatdoumeanbyOLAPserver?WhatisthedifferencebetweenOLAPandOLTP?
175.Whatisatuple?DynamicViewstemplate.PoweredbyBlogger.
Atupleisaninstanceofdatawithinarelationaldatabase.
176.ServicesanduserAccountsmaintenance
177.sp_configurecommands?
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

28/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

Displaysorchangesglobalconfigurationsettingsforthecurrentserver.
178.Whatisthebasicfunctionsformaster,msdb,tempdbdatabases?
MicrosoftSQLServer2000systemshavefoursystemdatabases:
masterThemasterdatabaserecordsallofthesystemlevelinformationforaSQLServersystem.It
recordsallloginaccountsandallsystemconfigurationsettings.masteristhedatabasethatrecords
theexistenceofallotherdatabases,includingthelocationofthedatabasefiles.
tempdbtempdbholdsalltemporarytablesandtemporarystoredprocedures.Italsofillsanyother
temporarystorageneedssuchasworktablesgeneratedbySQLServer.tempdbisrecreatedevery
timeSQLServerisstartedsothesystemstartswithacleancopyofthedatabase.
Bydefault,tempdbautogrowsasneededwhileSQLServerisrunning.Ifthesizedefinedfortempdb
issmall,partofyoursystemprocessingloadmaybetakenupwithautogrowingtempdbtothesize
neededtosupportyourworkloadeachtimetorestartSQLServer.Youcanavoidthisoverheadby
usingALTERDATABASEtoincreasethesizeoftempdb.
modelThemodeldatabaseisusedasthetemplateforalldatabasescreatedonasystem.Whena
CREATEDATABASEstatementisissued,thefirstpartofthedatabaseiscreatedbycopyinginthe
contentsofthemodeldatabase,thentheremainderofthenewdatabaseisfilledwithemptypages.
BecausetempdbiscreatedeverytimeSQLServerisstarted,themodeldatabasemustalwaysexist
onaSQLServersystem.
msdbThemsdbdatabaseisusedbySQLServerAgentforschedulingalertsandjobs,andrecording
operators.

179.Whataresequencediagrams?Whatyouwillgetoutofthissequencediagrams?
Sequencediagramsdocumenttheinteractionsbetweenclassestoachievearesult,suchasausecase.
BecauseUMLisdesignedforobjectorientedprogramming,thesecommunicationsbetweenclassesare
knownasmessages.Thesequencediagramlistsobjectshorizontally,andtimevertically,andmodelsthese
messagesovertime.
180.WhatarethenewfeaturesofSQL2000thanSQL7?Whatarethenewdatatypesinsql?
XMLSupportTherelationaldatabaseenginecanreturndataasExtensibleMarkupLanguage(XML)
documents.Additionally,XMLcanalsobeusedtoinsert,update,anddeletevaluesinthedatabase.
(forxmlrawtoretrieveoutputasxmltype)
UserDefinedFunctionsTheprogrammabilityofTransactSQLcanbeextendedbycreatingyourown
TransactSQLfunctions.Auserdefinedfunctioncanreturneitherascalarvalueoratable.
IndexedViewsIndexedviewscansignificantlyimprovetheperformanceofanapplicationwhere
queriesfrequentlyperformcertainjoinsoraggregations.Anindexedviewallowsindexestobecreated
onviews,wheretheresultsetoftheviewisstoredandindexedinthedatabase.
NewDataTypesSQLServer2000introducesthreenewdatatypes.bigintisan8byteintegertype.
sql_variantisatypethatallowsthestorageofdatavaluesofdifferentdatatypes.tableisatypethat
allowsapplicationstostoreresultstemporarilyforlateruse.Itissupportedforvariables,andasthe
returntypeforuserdefinedfunctions.
INSTEADOFandAFTERTriggersINSTEADOFtriggersareexecutedinsteadofthetriggering
action(forexample,INSERT,UPDATE,DELETE).Theycanalsobedefinedonviews,inwhichcase
theygreatlyextendthetypesofupdatesaviewcansupport.AFTERtriggersfireafterthetriggering
action.SQLServer2000introducestheabilitytospecifywhichAFTERtriggersfirefirstandlast.
MultipleInstancesofSQLServerSQLServer2000supportsrunningmultipleinstancesofthe
relationaldatabaseengineonthesamecomputer.Eachcomputercanrunoneinstanceoftherelational
databaseenginefromSQLServerversion6.5or7.0,alongwithoneormoreinstancesofthedatabase
enginefromSQLServer2000.Eachinstancehasitsownsetofsystemanduserdatabases.
IndexEnhancementsYoucannowcreateindexesoncomputedcolumns.Youcanspecifywhether
indexesarebuiltinascendingordescendingorder,andifthedatabaseengineshoulduseparallel
scanningandsortingduringindexcreation.

181.HowdoweopenSQLServerinsingleusermode?
Wecanaccomplishthisinanyofthethreewaysgivenbelow:
21.FromCommandPrompt:
sqlservrm
22.FromStartupOptions:
GotoSQLServerPropertiesbyrightclickingontheServernameintheEnterprisemanager.
Underthe'General'tab,clickon'StartupParameters'.
EnteravalueofmintheParameter.
23.FromRegistry:
GotoHKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServer\MSSQLServer\Parameters.
Addnewstringvalue.
http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

29/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

Specifythe'Name'asSQLArg(n)&'Data'asm.
Wherenistheargumentnumberinthelistofarguments.

182.WhatisLogShipping?
InMicrosoftSQLServer2000EnterpriseEdition,youcanuselogshippingtofeedtransactionlogsfrom
onedatabasetoanotheronaconstantbasis.Continuallybackingupthetransactionlogsfromasource
databaseandthencopyingandrestoringthelogstoadestinationdatabasekeepsthedestinationdatabase
synchronizedwiththesourcedatabase.Thisallowsyoutohaveabackupserverandalsoprovidesaway
tooffloadqueryprocessingfromthemaincomputer(thesourceserver)toreadonlydestinationservers.
XML

183.HowcanIconvertdatainaMicrosoftAccesstableintoXMLformat?
ThefollowingapplicationscanhelpyouconvertAccessdataintoXMLformat:Access2002,ADO2.5,and
SQLXML.Access2002(partofMicrosoftOfficeXP)enablesyoutoqueryorsaveatableinXMLformat.
Youmightbeabletoautomatethisprocess.ADO2.5andlaterenablesyoutoopenthedataintoa
recordset,thenpersisttherecordsetinXMLformat,asthefollowingcodeshows:
rs.Save"c:\rs.xml",adPersistXML
YoucanuselinkedserverstoaddtheAccessdatabasetoyourSQLServer2000databasesoyoucanrun
queriesfromwithinSQLServertoretrievedata.Then,throughHTTP,youcanusetheSQLXMLtechnology
toextracttheAccessdataintheXMLformatyouwant.
NEW
184.@@IDENTITY?
Ans:Returnsthelastinsertedidentityvalue.

Posted27thFebruary2012byprakash.varanasi
1 Viewcomments

DomainKING 21July2015at08:33
ThankyouforsuchawonderfulInformation!!
HereisalistofTopLINUXINTERVIEWQUESTIONS
VeritasClusterInterviewQuestions
SAMBAServerInterviewQuestions
LinuxFTPvsftpdInterviewQuestions
SSHInterviewQuestions
ApacheInterviewQuestions
NagiosInterviewquestions
IPTABLESInterviewQuestions
LdapServerInterviewQuestions
LVMInterviewquestions
SendmailServerInterviewQuestions
YUMInterviewQuestions
NFSInterviewQuestions
ReadMoreat:LinuxTroubleshooting
Reply

http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

30/31

4/27/2016

SQLServerFrequentlyAskedQuestions(FAQs)

Enteryourcomment...

Commentas:

Publish

YalavarthiGopinath(Google)

Preview

http://interviewquestionsall.blogspot.in/2012/02/sqlserverfrequentlyaskedquestions.html

Signout

Notifyme

31/31

Vous aimerez peut-être aussi