You are on page 1of 25

INDEX

SQLSERVERInterviewQuestions 1 2 3
Notice: Allrightsreservedworldwide.Nopartofthisbookmaybereproducedor copiedortranslatedinanyformbyanyelectronicormechanicalmeans (includingphotocopying,recording,orinformationstorageandretrieval) withoutpermissioninwritingfromthepublisher,exceptforreadingand browsingviatheWorldWideWeb.Usersarenotpermittedtomountthisfileon anynetworkservers. Formoreinformationsendemailto:pinal@sqlauthority.com

GeneralQuestionsofSQLSERVER...2 CommonQuestionsAsked.8 QuestionsofSQLSERVER200816

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

1) GeneralQuestionsofSQLSERVER
WhatisRDBMS? Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from differentfiles,providingpowerfultoolsfordatausage.(ReadMoreHere) WhatarethepropertiesoftheRelationaltables? Relationaltableshavesixproperties: Valuesareatomic. Columnvaluesareofthesamekind. Eachrowisunique. Thesequenceofcolumnsisinsignificant. Thesequenceofrowsisinsignificant. Eachcolumnmusthaveauniquename. WhatisNormalization? Databasenormalizationisadatadesignandorganizationprocessappliedtodatastructures based on rules that help building relational databases. In relational database design, the process of organizing data to minimize redundancy is called normalization. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modificationsofafieldcanbemadeinjustonetableandthenpropagatedthroughtherest ofthedatabaseviathedefinedrelationships. WhatisDenormalization? Denormalizationistheprocessofattemptingtooptimizetheperformanceofadatabaseby adding redundant data. It is sometimes necessary because current DBMSs implement the relationalmodelpoorly.AtruerelationalDBMSwouldallowforafullynormalizeddatabase at the logical level, while providing physical storage of data that is tuned for high performance.Denormalizationisatechniquetomovefromhighertolowernormalforms ofdatabasemodelinginordertospeedupdatabaseaccess.

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

Whataredifferentnormalizationforms? 1NF:EliminateRepeatingGroups Makeaseparatetableforeachsetofrelatedattributes,andgiveeachtableaprimarykey. Eachfieldcontainsatmostonevaluefromitsattributedomain. 2NF:EliminateRedundantData Ifanattributedependsononlypartofamultivaluedkey,removeittoaseparatetable. 3NF:EliminateColumnsNotDependentOnKey Ifattributesdonotcontributetoadescriptionofthekey,removethemtoaseparatetable. Allattributesmustbedirectlydependentontheprimarykey.(ReadMoreHere) BCNF:BoyceCoddNormalForm Iftherearenontrivialdependenciesbetweencandidatekeyattributes,separatethemout intodistincttables. 4NF:IsolateIndependentMultipleRelationships Notablemaycontaintwoormore1:norn:mrelationshipsthatarenotdirectlyrelated. 5NF:IsolateSemanticallyRelatedMultipleRelationships Theremaybepracticalconstrainsoninformationthatjustifyseparatinglogicallyrelated manytomanyrelationships. ONF:OptimalNormalForm Amodellimitedtoonlysimple(elemental)facts,asexpressedinObjectRoleModel notation. DKNF:DomainKeyNormalForm AmodelfreefromallmodificationanomaliesissaidtobeinDKNF. Remember,thesenormalizationguidelinesarecumulative.Foradatabasetobein3NF,it mustfirstfulfillallthecriteriaofa2NFand1NFdatabase. WhatisStoredProcedure? AstoredprocedureisanamedgroupofSQLstatementsthathavebeenpreviouslycreated and stored in the server database. Stored procedures accept input parameters so that a singleprocedurecanbeusedoverthenetworkbyseveralclientsusingdifferentinputdata. Andwhentheprocedureismodified,allclientsautomaticallygetthenewversion.Stored procedures reduce network traffic and improve performance. Stored procedures can be usedtohelpensuretheintegrityofthedatabase. e.g.sp_helpdb,sp_renamedb,sp_dependsetc.

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisTrigger? A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A triggercannotbecalledorexecuted;DBMSautomaticallyfiresthetriggerasaresultofa data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Storedprocedures,however,arenoteventdriveandarenotattachedtoaspecifictableas triggersare.StoredproceduresareexplicitlyexecutedbyinvokingaCALLtotheprocedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures. NestedTrigger:AtriggercanalsocontainINSERT,UPDATEandDELETElogicwithinitself,so when the trigger is fired because of data modification it can also cause another data modification,therebyfiringanothertrigger.Atriggerthatcontainsdatamodificationlogic withinitselfiscalledanestedtrigger.(ReadMoreHere) WhatisView? Asimpleviewcanbethoughtofasasubsetofatable.Itcanbeusedforretrievingdata,as well as updating or deleting rows. Rows updated or deleted in the view are updated or deletedinthetabletheviewwascreatedwith.Itshouldalsobenotedthatasdatainthe originaltablechanges,sodoesdataintheview,asviewsarethewaytolookatpartofthe originaltable.Theresultsofusingaviewarenotpermanentlystoredinthedatabase.The dataaccessedthroughaviewisactuallyconstructedusingstandardTSQLselectcommand andcancomefromonetomanydifferentbasetablesorevenotherviews. WhatisIndex? An index is a physical structure containing pointers to the data. Indices are created in an existingtabletolocaterowsmorequicklyandefficiently.Itispossibletocreateanindexon oneormorecolumnsofatable,andeachindexisgivenaname.Theuserscannotseethe indexes;theyarejustusedtospeedupqueries.Effectiveindexesareoneofthebestways toimproveperformanceinadatabaseapplication.Atablescanhappenswhenthereisno indexavailabletohelpaquery.InatablescanSQLServerexamineseveryrowinthetable to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scanshaveaterrificimpactonperformance. WhatisaLinkedServer? LinkedServersisaconceptinSQLServerbywhichwecanaddotherSQLServertoaGroup andqueryboththeSQLServerdbsusingTSQLStatements.Withalinkedserver,youcan create veryclean,easyto follow, SQL statements that allow remote data to be retrieved, joined and combined with local data. Stored Procedure sp_addlinkedserver, sp_addlinkedsrvloginwillbeusedaddnewLinkedServer.(ReadMoreHere)

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisCursor? Cursorisadatabaseobjectusedbyapplicationstomanipulatedatainasetonarowby rowbasis,insteadofthetypicalSQLcommandsthatoperateonalltherowsinthesetat onetime. Inordertoworkwithacursorweneedtoperformsomestepsinthefollowingorder: Declarecursor Opencursor Fetchrowfromthecursor Processfetchedrow Closecursor Deallocatecursor(ReadMoreHere) WhatisCollation? Collationreferstoasetofrulesthatdeterminehowdataissortedandcompared.Character data is sorted using rules that define the correct character sequence, with options for specifyingcase sensitivity, accentmarks, kana character types andcharacter width. (Read MoreHere) WhatisDifferencebetweenFunctionandStoredProcedure? UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereasStoredprocedurescannotbe.UDFsthatreturntablescanbetreatedasanother rowset.ThiscanbeusedinJOINswithothertables.InlineUDF'scanbethoughtofasviews thattakeparametersandcanbeusedinJOINsandotherRowsetoperations. Whatissubquery?Explainpropertiesofsubquery? Subqueries are often referred to as subselects, as they allow a SELECT statement to be executedarbitrarilywithinthebodyofanotherSQLstatement.Asubqueryisexecutedby enclosingitinasetofparentheses.Subqueriesaregenerallyusedtoreturnasinglerowas anatomicvalue,thoughtheymaybeusedtocomparevaluesagainstmultiplerowswiththe INkeyword. A subquery is a SELECT statement that is nested within another TSQL statement. A subquerySELECTstatementifexecutedindependentlyoftheTSQLstatement,inwhichitis nested,willreturnaresultset.MeaningasubquerySELECTstatementcanstandaloneandis not depended on the statement in which it is nested. A subquery SELECT statement can returnanynumberofvalues,andcanbefoundin,thecolumnlistofaSELECTstatement,a FROM,GROUPBY,HAVING,and/orORDERBYclausesofaTSQLstatement.ASubquerycan alsobeusedasaparametertoafunctioncall.Basicallyasubquerycanbeusedanywhere anexpressioncanbeused.(ReadMoreHere)

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhataredifferentTypesofJoin? CrossJoin A cross join that does not have a WHERE clause produces the Cartesian product of the tablesinvolvedinthejoin.ThesizeofaCartesianproductresultsetisthenumberofrows in the first table multiplied by the number of rows in the second table. The common exampleiswhencompanywantstocombineeachproductwithapricingtabletoanalyze eachproductateachprice. InnerJoin Ajointhatdisplaysonlytherowsthathaveamatchinbothjoinedtablesisknownasinner Join.ThisisthedefaulttypeofjoinintheQueryandViewDesigner. OuterJoin A join that includes rows even if they do not have related rows in the joined table is an OuterJoin.Youcancreatethreedifferentouterjointospecifytheunmatchedrowstobe included: LeftOuterJoin:InLeftOuterJoinallrowsinthefirstnamedtablei.e."left"table, whichappearsleftmostintheJOINclauseareincluded.Unmatchedrowsintheright tabledonotappear. RightOuterJoin:InRightOuterJoinallrowsinthesecondnamedtablei.e."right" table,whichappearsrightmostintheJOINclauseareincluded.Unmatchedrowsin thelefttablearenotincluded. FullOuterJoin:InFullOuterJoinallrowsinalljoinedtablesareincluded,whether theyarematchedornot.

SelfJoin This is a particular case when one table joins to itself, with one or two aliases to avoid confusion.Aselfjoincanbeofanytype,aslongasthejoinedtablesarethesame.Aself join is rather unique in that it involves a relationship with only one table. The common example is when company has a hierarchal reporting structure whereby one member of staffreportstoanother.SelfJoincanbeOuterJoinorInnerJoin.(ReadMoreHere) Whatareprimarykeysandforeignkeys? Primarykeysaretheuniqueidentifiersforeachrow.Theymustcontainuniquevaluesand cannotbenull.Duetotheirimportanceinrelationaldatabases,Primarykeysarethemost fundamentalofallkeysandconstraints.AtablecanhaveonlyonePrimarykey. Foreign keys are both a method of ensuring data integrity and a manifestation of the relationshipbetweentables.

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisUserDefinedFunctions?WhatkindofUserDefinedFunctionscanbecreated? UserDefinedFunctionsallowdefiningitsownTSQLfunctionsthatcanaccept0ormore parametersandreturnasinglescalardatavalueoratabledatatype. DifferentKindsofUserDefinedFunctionscreatedare: ScalarUserDefinedFunction AScalaruserdefinedfunctionreturnsoneofthescalardatatypes.Text,ntext,imageand timestampdatatypesarenotsupported.Thesearethetypeofuserdefinedfunctionsthat mostdevelopersareusedtoinotherprogramminglanguages.Youpassin0tomany parametersandyougetareturnvalue. InlineTableValueUserDefinedFunction AnInlineTableValueuserdefinedfunctionreturnsatabledatatypeandisanexceptional alternativetoaviewastheuserdefinedfunctioncanpassparametersintoaTSQLselect commandandinessenceprovideuswithaparameterized,nonupdateableviewofthe underlyingtables. MultistatementTableValueUserDefinedFunction AMultiStatementTableValueuserdefinedfunctionreturnsatableandisalsoan exceptionalalternativetoaviewasthefunctioncansupportmultipleTSQLstatementsto buildthefinalresultwheretheviewislimitedtoasingleSELECTstatement.Also,theability topassparametersintoaTSQLselectcommandoragroupofthemgivesusthecapability toinessencecreateaparameterized,nonupdateableviewofthedataintheunderlying tables.Withinthecreatefunctioncommandyoumustdefinethetablestructurethatis beingreturned.Aftercreatingthistypeofuserdefinedfunction,ItcanbeusedintheFROM clauseofaTSQLcommandunlikethebehaviorfoundwhenusingastoredprocedurewhich canalsoreturnrecordsets.(ReadHereForExample) WhatisIdentity? Identity(orAutoNumber)isacolumnthatautomaticallygeneratesnumericvalues.Astart and increment value can be set, but most DBA leave these at 1. A GUID column also generatesnumbers;thevalueofthiscannotbecontrolled. Identity/GUIDcolumns donot needtobeindexed. WhatisDataWarehousing? Subjectoriented,meaningthatthedatainthedatabaseisorganizedsothatallthe dataelementsrelatingtothesamerealworldeventorobjectarelinkedtogether; Timevariant,meaningthatthechangestothedatainthedatabasearetrackedand recordedsothatreportscanbeproducedshowingchangesovertime; Nonvolatile, meaning that data in the database is never overwritten or deleted, oncecommitted,thedataisstatic,readonly,butretainedforfuturereporting. Integrated, meaning that the database contains data from most or all of an organization'soperationalapplications,andthatthisdataismadeconsistent. 7 Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

2) CommonQuestionsAsked
WhichTCP/IPportdoesSQLServerrunon?Howcanitbechanged? SQLServerrunsonport1433.ItcanbechangedfromtheNetworkUtilityTCP/IPproperties >Portnumber,bothonclientandtheserver. Whatarethedifferencebetweenclusteredandanonclusteredindex?(ReadMoreHere) Aclusteredindexisaspecialtypeofindexthatreordersthewayrecordsinthetableare physicallystored.Thereforetablecanhaveonlyoneclusteredindex.Theleafnodesofa clusteredindexcontainthedatapages. Anonclusteredindexisaspecialtypeofindexinwhichthelogicalorderoftheindexdoes notmatchthephysicalstoredorderoftherowsondisk.Theleafnodeofanonclustered indexdoesnotconsistofthedatapages.Instead,theleafnodescontainindexrows. Whatarethedifferentindexconfigurationsatablecanhave? Atablecanhaveoneofthefollowingindexconfigurations: Noindexes Aclusteredindex Aclusteredindexandmanynonclusteredindexes Anonclusteredindex Manynonclusteredindexes WhataredifferenttypesofCollationSensitivity? CasesensitivityAanda,Bandb,etc. Accentsensitivityaand,oand,etc. KanaSensitivityWhenJapanesekanacharactersHiraganaandKatakanaaretreated differently,itiscalledKanasensitive. WidthsensitivityAsinglebytecharacter(halfwidth)andthesamecharacterrepresented asadoublebytecharacter(fullwidth)aretreateddifferentlythanitiswidthsensitive. (ReadMoreHere) WhatisOLTP(OnlineTransactionProcessing)? InOLTPonlinetransactionprocessingsystemsrelationaldatabasedesignusethediscipline of data modeling and generally follow the Codd rules of data normalization in order to ensureabsolutedataintegrity.Usingtheserulescomplexinformationisbrokendowninto itsmostsimplestructures(atable)wherealloftheindividualatomiclevelelementsrelate toeachotherandsatisfythenormalizationrules.

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

What'sthedifferencebetweenaprimarykeyandauniquekey? Bothprimarykeyanduniquekeyenforcesuniquenessofthecolumnonwhichtheyare defined.Butbydefaultprimarykeycreatesaclusteredindexonthecolumn,whereare uniquecreatesanonclusteredindexbydefault.Anothermajordifferenceisthat,primary keydoesn'tallowNULLs,butuniquekeyallowsoneNULLonly.(ReadMoreHere) WhatisdifferencebetweenDELETE&TRUNCATEcommands? Deletecommandremovestherowsfromatablebasedontheconditionthatweprovide withaWHEREclause.Truncatewillactuallyremovealltherowsfromatableandtherewill benodatainthetableafterwerunthetruncatecommand. TRUNCATE TRUNCATEisfasterandusesfewersystemandtransactionlogresourcesthan DELETE. TRUNCATEremovesthedatabydeallocatingthedatapagesusedtostorethetables data,andonlythepagedeallocationsarerecordedinthetransactionlog. TRUNCATEremovesallrowsfromatable,butthetablestructure,itscolumns, constraints,indexesandsoon,remains.Thecounterusedbyanidentityfornew rowsisresettotheseedforthecolumn. YoucannotuseTRUNCATETABLEonatablereferencedbyaFOREIGNKEY constraint.BecauseTRUNCATETABLEisnotlogged,itcannotactivateatrigger. TRUNCATEcannotberolledback. TRUNCATEisDDLCommand. TRUNCATEResetsidentityofthetable DELETE DELETEremovesrowsoneatatimeandrecordsanentryinthetransactionlogfor eachdeletedrow. Ifyouwanttoretaintheidentitycounter,useDELETEinstead.Ifyouwanttoremove tabledefinitionanditsdata,usetheDROPTABLEstatement. DELETECanbeusedwithorwithoutaWHEREclause DELETEActivatesTriggers. DELETEcanberolledback. DELETEisDMLCommand. DELETEdoesnotresetidentityofthetable. (ReadMoreHere) WhenistheuseofUPDATE_STATISTICScommand? Thiscommandisbasicallyusedwhenalargeprocessingofdatahasoccurred.Ifalarge amountofdeletionsanymodificationorBulkCopyintothetableshasoccurred,ithasto updatetheindexestotakethesechangesintoaccount.UPDATE_STATISTICSupdatesthe indexesonthesetablesaccordingly.

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisthedifferencebetweenaHAVINGCLAUSEandaWHERECLAUSE? They specify a search condition for a group or an aggregate. But the difference is that HAVINGcanbeusedonlywiththeSELECTstatement.HAVINGistypicallyusedinaGROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having ClauseisbasicallyusedonlywiththeGROUPBYfunctioninaquerywhereasWHEREClause is applied to each row before they are part of the GROUP BY function in a query. (Read MoreHere) WhatarethepropertiesanddifferentTypesofSubQueries? PropertiesofSubQuery Asubquerymustbeenclosedintheparenthesis. Asubquerymustbeputintherighthandofthecomparisonoperator,and AsubquerycannotcontainanORDERBYclause. Aquerycancontainmorethanonesubquery. TypesofSubquery Singlerowsubquery,wherethesubqueryreturnsonlyonerow. Multiplerowsubquery,wherethesubqueryreturnsmultiplerows,.and Multiplecolumnsubquery,wherethesubqueryreturnsmultiplecolumns WhatisSQLProfiler? SQL Profiler is a graphical tool that allows system administrators to monitor events in an instanceofMicrosoftSQLServer.Youcancaptureandsavedataabouteacheventtoafile or SQL Server table to analyze later. For example, you can monitor a production environmenttoseewhichstoredproceduresarehamperingperformancesbyexecutingtoo slowly. Use SQL Profiler to monitor only the events in which you are interested. If traces are becomingtoolarge,youcanfilterthembasedontheinformationyouwant,sothatonlya subset of the event data is collected. Monitoring too many events adds overhead to the serverandthemonitoringprocessandcancausethetracefileortracetabletogrowvery large,especiallywhenthemonitoringprocesstakesplaceoveralongperiodoftime. WhataretheauthenticationmodesinSQLServer?Howcanitbechanged? WindowsmodeandMixedModeSQL&Windows. To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. Select the server then from the Tools menu select SQL Server ConfigurationProperties,andchoosetheSecuritypage.

10

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhichcommandusingQueryAnalyzerwillgiveyoutheversionofSQLserverand operatingsystem? SELECTSERVERPROPERTY('productversion'),SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition'). WhatisSQLServerAgent? SQL Server agent plays an important role in the daytoday tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management.ItspurposeistoeasetheimplementationoftasksfortheDBA,withitsfull functionschedulingengine,whichallowsyoutoscheduleyourownjobsandscripts.(Read MoreHere) Canastoredprocedurecallitselforrecursivestoredprocedure?HowmuchlevelSP nestingispossible? Yes. Because TransactSQL supports recursion, you can write stored procedures that call themselves.Recursioncanbedefinedasamethodofproblemsolvingwhereinthesolution isarrivedatbyrepetitivelyapplyingittosubsetsoftheproblem.Acommonapplicationof recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored procedure calls another or executes managedcode byreferencing aCLR routine, type, or aggregate.Youcanneststoredproceduresandmanagedcodereferencesupto32levels. WhatisLogShipping? Logshippingistheprocessofautomatingthebackupofdatabaseandtransactionlogfiles on a production SQL server, and then restoring them onto a standby server. Enterprise Editionsonlysupportslogshipping.Inlogshippingthetransactionallogfilefromoneserver isautomaticallyupdatedintothebackupdatabaseontheotherserver.Ifoneserverfails, theotherserverwillhavethesamedbandcanbeusedthisastheDisasterRecoveryplan. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval. Name3waystogetanaccuratecountofthenumberofrecordsinatable? SELECT*FROMtable1 SELECTCOUNT(*)FROMtable1 SELECTrowsFROMsysindexesWHEREid=OBJECT_ID(table1)ANDindid<2 WhatdoesitmeantohaveQUOTED_IDENTIFIERON?Whataretheimplicationsofhaving itOFF? When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIERisOFF,identifierscannotbequotedandmustfollowallTransactSQL rulesforidentifiers.(ReadMoreHere)

11

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisthedifferencebetweenaLocalandaGlobaltemporarytable? Alocaltemporarytableexistsonlyforthedurationofaconnectionor,ifdefinedinsidea compoundstatement,forthedurationofthecompoundstatement. A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary tabledisappears.However,thetabledefinitionremainswiththedatabaseforaccesswhen databaseisopenednexttime. WhatistheSTUFFfunctionandhowdoesitdifferfromtheREPLACEfunction? STUFF function is used to overwrite existing characters. Using this syntax, STUFF (string_expression, start, length, replacement_characters), string_expression is the string thatwillhavecharacterssubstituted,startisthestartingposition,lengthisthenumberof characters in the string that are substituted, and replacement_characters are the new charactersinterjectedintothestring.REPLACEfunctiontoreplaceexistingcharactersofall occurrences. Using the syntax REPLACE (string_expression, search_string, replacement_string),whereeveryincidenceofsearch_stringfoundinthestring_expression willbereplacedwithreplacement_string. WhatisPRIMARYKEY? A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primarykeyconstraintcanbecreatedforeachtable.Theprimarykeyconstraintsareused toenforceentityintegrity. WhatisUNIQUEKEYconstraint? A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicatevaluesareentered.Theuniquekeyconstraintsareusedtoenforceentityintegrity astheprimarykeyconstraints. WhatisFOREIGNKEY? A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the corresponding data values. A foreign key in one table points to a primary key in anothertable.Foreignkeyspreventactionsthatwouldleaverowswithforeignkeyvalues when there are no primary keys with that value. The foreign key constraints are used to enforcereferentialintegrity. WhatisCHECKConstraint? ACHECKconstraintisusedtolimitthevaluesthatcanbeplacedinacolumn.Thecheck constraintsareusedtoenforcedomainintegrity.(ReadMoreHere)

12

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisNOTNULLConstraint? ANOTNULLconstraintenforcesthatthecolumnwillnotacceptnullvalues.Thenotnull constraintsareusedtoenforcedomainintegrity,asthecheckconstraints. (ReadMoreHere) Howtoget@@ERRORand@@ROWCOUNTatthesametime? If@@RowcountischeckedafterErrorcheckingstatementthenitwillhave0asthevalueof @@Recordcountasitwouldhavebeenreset.Andif@@Recordcountischeckedbeforethe errorchecking statement then @@Error would get reset. To get @@error and @@rowcountatthesametimedobothinsamestatementandstoretheminlocalvariable. SELECT@RC=@@ROWCOUNT,@ER=@@ERROR WhatisaScheduledJobsorWhatisaScheduledTasks? Scheduledtasksletuserautomateprocessesthatrunonregularorpredictablecycles.User can schedule administrative tasks, such as cube processing, to run during times of slow businessactivity.Usercanalsodeterminetheorderinwhichtasksrunbycreatingjobsteps withinaSQLServerAgentjob.E.g.backupdatabase,UpdateStatsofTables.Jobstepsgive usercontroloverflowofexecution.Ifonejobfails,usercanconfigureSQLServerAgentto continuetoruntheremainingtasksortostopexecution. WhataretheadvantagesofusingStoredProcedures? Storedprocedurecanreducednetworktrafficandlatency,boostingapplication performance. Storedprocedureexecutionplanscanbereused,stayingcachedinSQLServer's memory,reducingserveroverhead. Storedprocedureshelppromotecodereuse. Storedprocedurescanencapsulatelogic.Youcanchangestoredprocedurecode withoutaffectingclients. Storedproceduresprovidebettersecuritytoyourdata. Whatisatablecalled,ifithasneitherClusternorNonclusterIndex?Whatisitusedfor? UnindexedtableorHeap.MicrosoftPressBooksandBookonLine(BOL)refersitasHeap.A heapisatablethatdoesnothaveaclusteredindexand,therefore,thepagesarenotlinked bypointers.TheIAMpagesaretheonlystructuresthatlinkthepagesinatabletogether. Unindexed tables are good for fast storing of data. Many times it is better to drop all indexesfromtableandthendobulkofinsertsandtorestorethoseindexesafterthat. CanSQLServerslinkedtootherserverslikeOracle? SQLServercanbelinkedtoanyserverprovidedithasOLEDBproviderfromMicrosoftto allowalink.E.g.OraclehasanOLEDBproviderfororaclethatMicrosoftprovidestoaddit aslinkedservertoSQLServergroup

13

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisBCP?Whendoesitused? BulkCopyisatoolusedtocopyhugeamountofdatafromtablesandviews.BCPdoesnot copythestructuressameassourcetodestination.BULKINSERTcommandhelpstoimporta datafileintoadatabasetableorviewinauserspecifiedformat. Whatcommanddoweusetorenameadb,atableandacolumn? Torenamedb sp_renamedboldname,newname Ifsomeoneisusingdbitwillnotacceptsp_renmaedb.Inthatcasefirstbringdbtosingle userusingsp_dboptions.Usesp_renamedbtorenamedatabase.Usesp_dboptionstobring databasetomultiusermode. E.g. USEmaster; GO EXECsp_dboptionAdventureWorks,'SingleUser',True GO EXECsp_renamedb'AdventureWorks','AdventureWorks_New' GO EXECsp_dboptionAdventureWorks,'SingleUser',False GO TorenameTable Wecanchangethetablenameusingsp_renameasfollows, sp_renameoldTableNamenewTableName E.g. SP_RENAMETable_First,Table_Last GO TorenameColumn Thescriptforrenaminganycolumn: sp_renameTableName.[OldcolumnName],NewColumnName,Column E.g. sp_RENAMETable_First.Name,NameChange,COLUMN GO

14

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

Whataresp_configurecommandsandsetcommands? Usesp_configuretodisplayorchangeserverlevelsettings.Tochangedatabaselevel settings,useALTERDATABASE.Tochangesettingsthataffectonlythecurrentusersession, usetheSETstatement. E.g. sp_CONFIGUREshowadvanced,0 GO RECONFIGURE GO sp_CONFIGURE GO Youcanrunfollowingcommandandcheckadvanceglobalconfigurationsettings. sp_CONFIGUREshowadvanced,1 GO RECONFIGURE GO sp_CONFIGURE GO (ReadMoreHere) Howtoimplementonetoone,onetomanyandmanytomanyrelationshipswhile designingtables? OnetoOnerelationshipcanbeimplementedasasingletableandrarelyastwotableswith primaryandforeignkeyrelationships.OnetoManyrelationshipsareimplementedby splittingthedataintotwotableswithprimarykeyandforeignkeyrelationships. ManytoManyrelationshipsareimplementedusingajunctiontablewiththekeysfrom boththetablesformingthecompositeprimarykeyofthejunctiontable. Whatisanexecutionplan?Whenwouldyouuseit?Howwouldyouviewtheexecution plan? Anexecutionplanisbasicallyaroadmapthatgraphicallyortextuallyshowsthedata retrievalmethodschosenbytheSQLServerqueryoptimizerforastoredprocedureorad hocqueryandisaveryusefultoolforadevelopertounderstandtheperformance characteristicsofaqueryorstoredproceduresincetheplanistheonethatSQLServerwill placeinitscacheandusetoexecutethestoredprocedureorquery.FromwithinQuery Analyzerisanoptioncalled"ShowExecutionPlan"(locatedontheQuerydropdown menu).Ifthisoptionisturnedonitwilldisplayqueryexecutionplaninseparatewindow whenqueryisranagain.

15

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

3) QuestionsofSQLSERVER2008
Whatarethebasicfunctionsformaster,msdb,model,tempdbandresourcedatabases? ThemasterdatabaseholdsinformationforalldatabaseslocatedontheSQLServerinstance andisthegluethatholdstheenginetogether.BecauseSQLServercannotstartwithouta functioningmasterdatabase,youmustadministerthisdatabasewithcare. Themsdbdatabasestoresinformationregardingdatabasebackups,SQLAgentinformation, DTSpackages,SQLServerjobs,andsomereplicationinformationsuchasforlogshipping. Thetempdbholdstemporaryobjectssuchasglobalandlocaltemporarytablesandstored procedures. Themodelisessentiallyatemplatedatabaseusedinthecreationofanynewuserdatabase createdintheinstance. TheresoureDatabaseisareadonlydatabasethatcontainsallthesystemobjectsthatare includedwithSQLServer.SQLServersystemobjects,suchassys.objects,arephysically persistedintheResourcedatabase,buttheylogicallyappearinthesysschemaofevery database.TheResourcedatabasedoesnotcontainuserdataorusermetadata. WhatisServiceBroker? ServiceBrokerisamessagequeuingtechnologyinSQLServerthatallowsdevelopersto integrateSQLServerfullyintodistributedapplications.ServiceBrokerisfeaturewhich providesfacilitytoSQLServertosendanasynchronous,transactionalmessage.itallowsa databasetosendamessagetoanotherdatabasewithoutwaitingfortheresponse,sothe applicationwillcontinuetofunctioniftheremotedatabaseistemporarilyunavailable. (ReadMoreHere) WhereSQLserverusernamesandpasswordsarestoredinSQLserver? TheygetstoredinSystemCatalogViewssys.server_principalsandsys.sql_logins. WhatisPolicyManagement? PolicyManagementinSQLSERVER2008allowsyoutodefineandenforcepoliciesfor configuringandmanagingSQLServeracrosstheenterprise.PolicyBasedManagementis configuredinSQLServerManagementStudio(SSMS).NavigatetotheObjectExplorerand expandtheManagementnodeandthePolicyManagementnode;youwillseethePolicies, Conditions,andFacetsnodes.(ReadMoreHere)

16

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisReplicationandDatabaseMirroring? Databasemirroringcanbeusedwithreplicationtoprovideavailabilityforthepublication database.Databasemirroringinvolvestwocopiesofasingledatabasethattypicallyreside ondifferentcomputers.Atanygiventime,onlyonecopyofthedatabaseiscurrently availabletoclientswhichareknownastheprincipaldatabase.Updatesmadebyclientsto theprincipaldatabaseareappliedontheothercopyofthedatabase,knownasthemirror database.Mirroringinvolvesapplyingthetransactionlogfromeveryinsertion,update,or deletionmadeontheprincipaldatabaseontothemirrordatabase. WhatareSparseColumns? Asparsecolumnisanothertoolusedtoreducetheamountofphysicalstorageusedina database.Theyaretheordinarycolumnsthathaveanoptimizedstoragefornullvalues. Sparsecolumnsreducethespacerequirementsfornullvaluesatthecostofmoreoverhead toretrievenonnullvalues.(ReadMoreHere) WhatdoesTOPOperatorDo? TheTOPoperatorisusedtospecifythenumberofrowstobereturnedbyaquery.TheTOP operatorhasnewadditioninSQLSERVER2008thatitacceptsvariablesaswellasliteral valuesandcanbeusedwithINSERT,UPDATE,andDELETESstatements. WhatisCTE? CTEisanabbreviationCommonTableExpression.ACommonTableExpression(CTE)isan expressionthatcanbethoughtofasatemporaryresultsetwhichisdefinedwithinthe executionofasingleSQLstatement.ACTEissimilartoaderivedtableinthatitisnotstored asanobjectandlastsonlyforthedurationofthequery.(ReadMoreHere) WhatisMERGEStatement? MERGEisanewfeaturethatprovidesanefficientwaytoperformmultipleDMLoperations. InpreviousversionsofSQLServer,wehadtowriteseparatestatementstoINSERT,UPDATE, orDELETEdatabasedoncertainconditions,butnow,usingMERGEstatementwecan includethelogicofsuchdatamodificationsinonestatementthatevencheckswhenthe dataismatchedthenjustupdateitandwhenunmatchedtheninsertit.Oneofthemost importantadvantagesofMERGEstatementisallthedataisreadandprocessedonlyonce.
(ReadMoreHere)

WhatisFilteredIndex? FilteredIndexisusedtoindexaportionofrowsinatablethatmeansitappliesfilteron INDEXwhichimprovesqueryperformance,reduceindexmaintenancecosts,andreduce indexstoragecostscomparedwithfulltableindexes.WhenweseeanIndexcreatedwith somewhereclausethenthatisactuallyaFILTEREDINDEX.

17

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhicharenewdatatypesintroducedinSQLSERVER2008? TheGEOMETRYType:TheGEOMETRYdatatypeisasystem.NETcommonlanguage runtime(CLR)datatypeinSQLServer.Thistyperepresentsdatainatwodimensional Euclideancoordinatesystem. TheGEOGRAPHYType:TheGEOGRAPHYdatatypesfunctionsarethesameaswith GEOMETRY.ThedifferencebetweenthetwoisthatwhenyouspecifyGEOGRAPHY,youare usuallyspecifyingpointsintermsoflatitudeandlongitude. NewDateandTimeDatatypes:SQLServer2008introducesfournewdatatypesrelatedto dateandtime:DATE,TIME,DATETIMEOFFSET,andDATETIME2. DATE: The new DATE type just stores the date itself. It is based on the Gregorian calendarandhandlesyearsfrom1to9999. TIME:ThenewTIME(n)typestorestimewitharangeof00:00:00.0000000through 23:59:59.9999999. The precision is allowed with this type. TIME supports seconds downto100nanoseconds.TheninTIME(n)definesthisleveloffractionalsecond precision,from0to7digitsofprecision. TheDATETIMEOFFSETType:DATETIMEOFFSET(n)isthetimezoneawareversionof adatetimedatatype.Thenamewillappearlessoddwhenyouconsiderwhatitreally is: a date + a time + a timezone offset. The offset is based on how far behind or aheadyouarefromCoordinatedUniversalTime(UTC)time. TheDATETIME2Type:Itisanextensionofthedatetimetypeinearlierversionsof SQLServer.ThisnewdatatypehasadaterangecoveringdatesfromJanuary1of year1throughDecember31ofyear9999.Thisisadefiniteimprovementoverthe 1753 lower boundary of the datetime datatype. DATETIME2 not only includes the largerdaterange,butalsohasatimestampandthesamefractionalprecisionthat TIMEtypeprovides WhataretheAdvantagesofusingCTE? UsingCTEimprovesthereadabilityandmakesmaintenanceofcomplexquerieseasy. Thequerycanbedividedintoseparate,simple,logicalbuildingblockswhichcanbe thenusedtobuildmorecomplexCTEsuntilfinalresultsetisgenerated. CTEcanbedefinedinfunctions,storedprocedures,triggersorevenviews. AfteraCTEisdefined,itcanbeusedasaTableoraViewandcanSELECT,INSERT, UPDATEorDELETEData.

18

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

Howcanwerewritesubqueriesintosimpleselectstatementsorwithjoins? YeswecanwriteusingCommonTableExpression(CTE).ACommonTableExpression(CTE) isanexpressionthatcanbethoughtofasatemporaryresultsetwhichisdefinedwithinthe executionofasingleSQLstatement.ACTEissimilartoaderivedtableinthatitisnotstored asanobjectandlastsonlyforthedurationofthequery. E.g. USEAdventureWorks GO WITHEmployeeDepartment_CTEAS( SELECTEmployeeID,DepartmentID,ShiftID FROMHumanResources.EmployeeDepartmentHistory ) SELECTecte.EmployeeId,ed.DepartmentID,ed.Name,ecte.ShiftID FROMHumanResources.Departmented INNERJOINEmployeeDepartment_CTEecteONecte.DepartmentID=ed.Department ID GO WhatisCLR? InSQLServer2008,SQLServerobjectssuchasuserdefinedfunctionscanbecreatedusing suchCLRlanguages.ThisCLRlanguagesupportextendsnotonlytouserdefinedfunctions, butalsotostoredproceduresandtriggers.YoucandevelopsuchCLRaddonstoSQLServer usingVisualStudio2008.(ReadMoreHere)

Whataresynonyms? Synonymsgiveyoutheabilitytoprovidealternatenamesfordatabaseobjects.Youcan aliasobjectnames;forexample,usingtheEmployeetableasEmp.Youcanalsoshorten names.Thisisespeciallyusefulwhendealingwiththreeandfourpartnames;forexample, shorteningserver.database.owner.objecttoobject.(ReadMoreHere) WhatisLINQ? LanguageIntegratedQuery(LINQ)addstheabilitytoqueryobjectsusing.NETlanguages. TheLINQtoSQLobject/relationalmapping(O/RM)frameworkprovidesthefollowingbasic features: Toolstocreateclasses(usuallycalledentities)mappedtodatabasetables CompatibilitywithLINQsstandardqueryoperations TheDataContextclass,withfeaturessuchasentityrecordmonitoring,automatic SQLstatementgeneration,recordconcurrencydetection,andmuchmore

19

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisIsolationLevels? Transactionsspecifyanisolationlevelthatdefinesthedegreetowhichonetransaction mustbeisolatedfromresourceordatamodificationsmadebyothertransactions.Isolation levelsaredescribedintermsofwhichconcurrencysideeffects,suchasdirtyreadsor phantomreads,areallowed. Transactionisolationlevelscontrol: Whetherlocksaretakenwhendataisread,andwhattypeoflocksarerequested. Howlongthereadlocksareheld. Whetherareadoperationreferencingrowsmodifiedbyanothertransaction: Blocksuntiltheexclusivelockontherowisfreed. Retrievesthecommittedversionoftherowthatexistedatthetimethe statementortransactionstarted. Readstheuncommitteddatamodification.(ReadMoreHere)

WhatisuseofEXCEPTClause? EXCEPTclauseissimilartoMINUSoperationinOracle.TheEXCEPTqueryandMINUSquery returnsallrowsinthefirstquerythatarenotreturnedinthesecondquery.EachSQL statementwithintheEXCEPTqueryandMINUSquerymusthavethesamenumberoffields intheresultsetswithsimilardatatypes.(ReadMoreHere) WhatisXPath? XPathusesasetofexpressionstoselectnodestobeprocessed.Themostcommon expressionthatyoulluseisthelocationpathexpression,whichreturnsbackasetofnodes calledanodeset.XPathcanusebothanunabbreviatedandanabbreviatedsyntax.The followingistheunabbreviatedsyntaxforalocationpath: /axisName::nodeTest[predicate]/axisName::nodeTest[predicate] WhatisNOLOCK? UsingtheNOLOCKqueryoptimizerhintisgenerallyconsideredgoodpracticeinorderto improveconcurrencyonabusysystem.WhentheNOLOCKhintisincludedinaSELECT statement,nolocksaretakenwhendataisread.TheresultisaDirtyRead,whichmeans thatanotherprocesscouldbeupdatingthedataattheexacttimeyouarereadingit.There arenoguaranteesthatyourquerywillretrievethemostrecentdata.Theadvantageto performanceisthatyourreadingofdatawillnotblockupdatesfromtakingplace,and updateswillnotblockyourreadingofdata.SELECTstatementstakeShared(Read)locks. ThismeansthatmultipleSELECTstatementsareallowedsimultaneousaccess,butother processesareblockedfrommodifyingthedata.Theupdateswillqueueuntilallthereads havecompleted,andreadsrequestedaftertheupdatewillwaitfortheupdatesto complete.Theresulttoyoursystemisdelay(blocking).(ReadMoreHere) 20 Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

HowwouldyouhandleerrorinSQLSERVER2008? SQLServernowsupportstheuseofTRY...CATCHconstructsforprovidingricherror handling.TRY...CATCHletsusbuilderrorhandlingatthelevelweneed,inthewayweneed to,bysettingaregionwhereifanyerroroccurs,itwillbreakoutoftheregionandheadto anerrorhandler.Thebasicstructureisasfollows: BEGINTRY <code> ENDTRY BEGINCATCH <code> ENDCATCH SoifanyerroroccursintheTRYblock,executionisdivertedtotheCATCHblock,andthe errorcanbedealt. WhatisRAISEERROR? RaiseErrorgeneratesanerrormessageandinitiateserrorprocessingforthesession. RAISERRORcaneitherreferenceauserdefinedmessagestoredinthesys.messagescatalog vieworbuildamessagedynamically.Themessageisreturnedasaservererrormessageto thecallingapplicationortoanassociatedCATCHblockofaTRYCATCHconstruct.(Read MoreHere) HowtorebuildMasterDatabse? Masterdatabaseissystemdatabaseanditcontainsinformationaboutrunningservers configuration.WhenSQLServer2005isinstalleditusuallycreatesmaster,model,msdb, tempdbresourceanddistributionsystemdatabasebydefault.OnlyMasterdatabaseisthe onewhichisabsolutelymusthavedatabase.WithoutMasterdatabaseSQLServercannot bestarted.ThisisthereasonitisextremelyimportanttobackupMasterdatabase. TorebuildtheMasterdatabase,RunSetup.exe,verify,andrepairaSQLServerinstance,and rebuildthesystemdatabases.Thisprocedureismostoftenusedtorebuildthemaster databaseforacorruptedinstallationofSQLServer. WhatisXMLDatatype? ThexmldatatypeletsyoustoreXMLdocumentsandfragmentsinaSQLServerdatabase. AnXMLfragmentisanXMLinstancethatismissingasingletoplevelelement.Youcan createcolumnsandvariablesofthexmltypeandstoreXMLinstancesinthem.Thexml datatypeandassociatedmethodshelpintegrateXMLintotherelationalframeworkofSQL Server.

21

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisDataCompression? InSQLSERVE2008DataCompressioncomesintwoflavors: RowCompression PageCompression

RowCompression Rowcompressionchangestheformatofphysicalstorageofdata.Itminimizethemetadata (columninformation,length,offsetsetc)associatedwitheachrecord.Numericdatatypes and fixed length strings are stored in variablelength storage format, just like Varchar. (ReadMoreHere) PageCompression Pagecompressionallowscommondatatobesharedbetweenrowsforagivenpage.Its usesthefollowingtechniquestocompressdata: Rowcompression. PrefixCompression.Foreverycolumninapageduplicateprefixesareidentified. Theseprefixesaresavedincompressioninformationheaders(CI)whichresides after page header. A reference number is assigned to these prefixes and that referencenumberisreplacedwhereeverthoseprefixesarebeingused.

DictionaryCompression. Dictionarycompressionsearchesforduplicatevaluesthroughoutthepageandstoresthem inCI.Themaindifferencebetweenprefixanddictionarycompressionisthatprefixisonly restrictedtoonecolumnwhiledictionaryisapplicabletothecompletepage. WhatisuseofDBCCCommands? The TransactSQL programming language provides DBCC statements that act as Database ConsoleCommandsforSQLServer.DBCCcommandsareusedtoperformfollowingtasks. Maintenancetasksondatabase,index,orfilegroup. Tasksthatgatheranddisplayvarioustypesofinformation. Validationoperationsonadatabase,table,index,catalog,filegroup,or allocationofdatabasepages. MiscellaneoustaskssuchasenablingtraceflagsorremovingaDLLfrom memory. (ReadMoreHere)

22

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

HowtofindtableswithoutIndexes? RunfollowingqueryinQueryEditor. USE<database_name>; GO SELECTSCHEMA_NAME(schema_id)ASschema_name ,nameAStable_name FROMsys.tables WHEREOBJECTPROPERTY(OBJECT_ID,'IsIndexed')=0 ORDERBYschema_name,table_name; GO Howtocopythetables,schemaandviewsfromoneSQLServertoanother? Therearemultiplewaystodothis. 1) DetachDatabasefromoneserverandAttachDatabasetoanotherserver. 2) ManuallyscriptalltheobjectsusingSSMSandrunthescriptonnewserver. 3) UseWizardofSSMS.(ReadMoreHere) Howtocopydatafromonetabletoanothertable? Therearemultiplewaystodothis. 1) INSERTINTOSELECT Thismethodisusedwhentableisalreadycreatedinthedatabaseearlieranddataisto be inserted into this table from another table. If columns listed in insert clause and selectclausearesame,theyarenotrequiredtolistthem. 2)SELECTINTO This method is used when table is not created earlier and needs to be created when datafromonetableistobeinsertedintonewlycreatedtablefromanothertable.New tableiscreatedwithsamedatatypesasselectedcolumns. (ReadMoreHere) WhatisCatalogViews? CatalogviewsreturninformationthatisusedbytheSQLServerDatabaseEngine.Catalog Viewsarethemostgeneralinterfacetothecatalogmetadataandprovidethemostefficient way to obtain, transform, and present customized forms of this information. All user availablecatalogmetadataisexposedthroughcatalogviews. WhatisPIVOTandUNPIVOT? A Pivot Table can automatically sort, count, and total the data stored in one table or spreadsheetandcreateasecondtabledisplayingthesummarizeddata.ThePIVOToperator turnsthevaluesofaspecifiedcolumnintocolumnnames,effectivelyrotatingatable. UNPIVOTtableisreverseofPIVOTTable.(ReadMoreHere)

23

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatisFilestream? Filestream allows you to store large objects in the file system and have these files integrated within the database. It enables SQL Server based applications to store unstructured data such as documents, images, audios, videos etc. in the file system.FILESTREAM basically integrates the SQL Server Database Engine with New Technology File System (NTFS); it basically stores the data in varbinary (max) data type. Using this data type, the unstructured data is stored in the NTFS file system and the SQL ServerDatabaseEnginemanagesthelinkbetweentheFilestreamcolumnandtheactualfile located in the NTFS. Using Transact SQL statements users can insert, update, delete and selectthedatastoredinFILESTREAMenabledtables. WhatisDirtyRead? A dirty read occurs when two operations say, read and write occurs together giving the incorrect or unedited data. Suppose, A has changed a row, but has not committed the changes.Breadstheuncommitteddatabuthisviewofthedatamaybewrongsothatis DirtyRead. WhatisSQLCMD? sqlcmdisenhancedversionoftheisqlandosqlanditprovideswaymorefunctionalitythan other two options. In other words sqlcmd is better replacement of isql (which will be deprecatedeventually)andosql(notincludedinSQLServer2005RTM).sqlcmdcanwork twomodesi)BATCHandii)interactivemodes.(ReadMore) WhatisAggregateFunctions? Aggregate functions perform a calculation on a set of values and return a single value. Aggregate functions ignore NULL values except COUNT function. HAVING clause is used, alongwithGROUPBY,forfilteringqueryusingaggregatevalues. Followingfunctionsareaggregatefunctions. AVG,MIN,CHECKSUM_AGG,SUM,COUNT,STDEV,COUNT_BIG,STDEVP,GROUPING, VAR,MAX,VARP(ReadMoreHere) WhatdoyoumeanbyTableSample? TABLESAMPLEallowsyoutoextractasamplingofrowsfromatableintheFROMclause. Therowsretrievedarerandomandtheyarenotinanyorder.Thissamplingcanbebased onapercentageofnumberofrows.YoucanuseTABLESAMPLEwhenonlyasamplingof rowsisnecessaryfortheapplicationinsteadofafullresultset.(ReadMoreHere) WhatisRow_Number()? ROW_NUMBER()returnsacolumnasanexpressionthatcontainstherowsnumberwithin theresultset.Thisisonlyanumberusedinthecontextoftheresultset,iftheresult changes,theROW_NUMBER()willchange.

24

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

WhatareRankingFunctions? Rankingfunctionsreturnarankingvalueforeachrowinapartition.Alltheranking functionsarenondeterministic.DifferentRankingfunctionsare: ROW_NUMBER()OVER([<partition_by_clause>]<order_by_clause>) Returnsthesequentialnumberofarowwithinapartitionofaresultset,startingat1for thefirstrowineachpartition. RANK()OVER([<partition_by_clause>]<order_by_clause>) Returnstherankofeachrowwithinthepartitionofaresultset. DENSE_RANK()OVER([<partition_by_clause>]<order_by_clause>) Returnstherankofrowswithinthepartitionofaresultset,withoutanygapsintheranking. (ReadMoreHere) WhatisthedifferencebetweenUNIONandUNIONALL? UNION TheUNIONcommandisusedtoselectrelatedinformationfromtwotables,muchlikethe JOINcommand.However,whenusingtheUNIONcommandallselectedcolumnsneedtobe ofthesamedatatype.WithUNION,onlydistinctvaluesareselected. UNIONALL TheUNIONALLcommandisequaltotheUNIONcommand,exceptthatUNIONALLselects allvalues. The difference between Union and Union all is that Union all will not eliminate duplicate rows,insteaditjustpullsallrowsfromalltablesfittingyourqueryspecificsandcombines themintoatable.(ReadMoreHere) WhatisBTree? ThedatabaseserverusesaBtreestructuretoorganizeindexinformation.BTreegenerally hasfollowingtypesofindexpagesornodes: root node: A root node contains node pointers to branch nodes which can be onlyone. branch nodes: A branch node contains pointers to leaf nodes or other branch nodeswhichcanbetwoormore. leafnodesAleafnodecontainsindexitemsandhorizontalpointerstootherleaf nodeswhichcanbemany.

25

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

You might also like