Basic SQL Faq Ans

  • Upload
    amjalu

  • View
    226

  • Download
    0

Embed Size (px)

Citation preview

  • 8/12/2019 Basic SQL Faq Ans

    1/24

    SQL SERVER Questions And Answers

    What is an Entity?

    The basic data item stored in database is called entity. Anentity can be any object, item, place, person, concept, oractivity about which data is stored.

    What is an attribute?

    An attribute is a property of an entity. It describes a part ofan entity. Entity could have one or more attributes.

    What is ER diagram?

    An Entity Relationship Diagram is diagrammaticrepresentation of the logical structure of a databasesystem.

    Describe the concept of keys

    !andidate keyAn attribute that uni uely identifies a row is called candidate!ey. It is also called das surrogate !ey.

    "rimary keyA candidate !ey that you choose to identify rows uni uely iscalled a primary !ey.A#ternate keyIf there are multiple candidate !eys in a table, the candidate!eys that are chosen as primary !ey are called the alternate!eys.!omposite key"hen the !ey that uni uely identifies the rows of a table ismade up of more than one attribute, it is called as acomposite !ey.

    $oreign key Two tables can be related using a common attribute. "hen aprimary !ey of one table is also available as an attribute inanother related table it is called a foreign !ey.

    1

  • 8/12/2019 Basic SQL Faq Ans

    2/24

    What are %oins?

    #ometimes, data from multiple tables is to be displayedusing select statement. $or this purpose, the tables in usemust have a column that is e uated. This is termed assimple join or multiple join.

    #ometimes, you might want to display all records from onetable and some from another. This type of join is called anouter join. An outer join is only possible between twotables.

    There are two types of outer join, namely left and right. In aleft outer join, all the rows of the first table named in the

    $R%& clause are displayed. In a right outer join all therows from the second table mentioned in the $R%&clause are displayed. In either case, all the matching rowsfrom other table are displayed.

    What is a sub &uery?

    #ometimes the results of one uery are dependant on theresults of another uery. $or this purpose one uery isnested inside another uery, this is called as sub uery.

    What are the types of constraints?

    'ou can enforce data integrity by using constraints.(onstraints are divided in to five categories.

    "rimary key constraint

    A primary !ey constraint is defined on a column are a set ofcolumns whose values uni uely identify the rows in a table.It cannot contain null values.

    'ni&ue constraint

    2

  • 8/12/2019 Basic SQL Faq Ans

    3/24

    )ni ue constraints are used to enforce uni ueness on non*primary !ey columns. It allows null values but only one rowcan have a null value.&ultiple uni ue constraints can be created on a table.

    $oreign (ey constraint

    'ou can use the foreign !ey constraint to remove theinconsistency in two tables when the data in the one table isdependant on the other table.!heck constraint

    It enforces domain integrity by restricting the values to beinserted in a column. It is possible to define multiple chec!constraints on a single column. These are evaluated in theorder in which they are defined.Defau#t !onstraint

    A default constraint can be use to assign a constant value toa column and the user need not insert values in to thatcolumn.

    ) What is a ru#e?

    The re uired integrity can be enforced by specifying a chec!constraint or by defining a rule. +ut chec! constraintmodifies the table structure. The constraint can there fore beimplemented using rules with out changing the tablestructure. This rule is applied before an insert or updatestatement .A rule must be bound to a column or a user*define d datatype. This is done using stored procedure sp bindrule. Rulesdo not apply to data that has already been inserted in thetable. The e-isting values in tables do not have to meet thecriteria specified by the rule.

    What are inde*es?

    To speed up data retrieval inde-es are used. Inde-es alsoenforce the uni ueness of rows.

    3

  • 8/12/2019 Basic SQL Faq Ans

    4/24

    Ad+antages

    Improves the speed of e-ecution.Enforces uni ueness of data.#peeds up joins between tables.

    Disad+antages

    .Ta!es dis! space to store.

    /.Data modification ta!es longer.

    0.Ta!es time to create inde-.

    ,ypes of inde*es

    !#ustered inde*

    .The data is physically sorted

    /.%ne clustered inde- can be created per table, so youshould build it on attributes that have a high percentageof uni ue values and that are not modified often.

    -onc#ustered inde*

    .The physical order of the rows is not the same as the inde-order.

    /.There can be as many as /12 nonclustered inde-es percolumn.

    What are +iews?

    A view is a virtual table, which gives access to a subset ofcolumns from one or more tables. It is a uery stored asan object in the database. 3ence a view is an object thatderives it data from one or more tables.

    Ad+antages

    .A view serves as a security mechanism.

    4

  • 8/12/2019 Basic SQL Faq Ans

    5/24

    /.A view simplifies the usage of comple- ueries.

    . What are store procedures and its ad+antages?

    A stored procedure is collection or batch of Transact*#45statements and control flow language that is stored underone name, and e-ecuted as single unit. It helps in improvingthe performance of a uery. It is a precompiled object. As itis ready to e-ecute no time is needed for parsing andcompiling the procedure.

    Ad+antages

    Improved performance 6 Applications do not have to compile

    the procedure over and over again.Reduction in networ! congestion 6 applications need notsubmit multiple #45 statements to server for the purpose ofprocessing.

    Enhanced accuracy 6 #45 statements included in aprocedure are designed by e-perienced programmers andare therefore more efficient, error free, and tested.

    +etter security mechanism 6 users can be grantedpermission to e-ecute a stored procedure even if they do notown it.

    ,ypes of stored procedures

    .)ser*defined

    /.#ystem defined

    These are prefi-ed with sp . These are for administrativepurpose and are stored in the database and are accessible toall users.

    0.Temporary

    5

  • 8/12/2019 Basic SQL Faq Ans

    6/24

    These are prefi-ed with 7, stored in tempdb and areautomatically dropped when connection terminates.

    1.Remote

    These are created and stored in remote servers and canaccessed by users with appropriate permissions.

    8.E-tended

    These are dlls that are e-ecuted outside #45 #erver. Theyare prefi-ed by -p .

    E*p#ain about /!" and D,S

    /!"

    The transfer data from an e-ternal source to #45 #erver isperformed using +ul! (opy 9rogram utility. The e-ternalsource is a flat file. Data transfer from e-ternal source to#45 #erver in +(9 I:. The transfer of data from #45#erver to e-ternal source is +(9 %)T.

    D,S

    Data transformation services can be used to import ande-port data between heterogeneous data sources and#45 #erver. The e-ternal data sources include ;isual$o-9ro, E-cel, 9arado-, Access, Dbase, and te-tfiles.

    What are transactions and their properties?

    A transaction is a se uence of operations performedtogether as a single unit of logical wor!. It has fourproperties.

    Atomicity 6 it states that either all the data modifications areperformed or none are performed.

    6

  • 8/12/2019 Basic SQL Faq Ans

    7/24

    (onsistency * it states that all the data is in a consistentstate after a successful completion of transaction.

    Isolation 6 it states any data modification made myconcurrent transactions must be isolated from themodifications made by other concurrent transaction.

    Durability 6 it states that ay change made by a completedtransaction remains permanently in the system.

    0 Locking mechanism

    #45 #erver uses the concept of loc!ing to ensuretransactional integrity and database consistency. 5oc!ing, by

    functionally prevents users from accessing information beingchanged by other users. In a multi*user environment,5oc!ing prevents users from changing the same data at thesame time. In #45 #erver loc!ing is implementedautomatically.

    #45 #erver implements multi*granular loc!ing, which allowstransactions to loc! different types of resources at differentlevels. #45 #erver can loc! the following resources.

    RID 6 is a row identifier that individually loc!s a row in atable.

  • 8/12/2019 Basic SQL Faq Ans

    8/24

    This loc! is implemented when a transaction modify a row.%nly one update loc! is allowed on a resource at a time.

    E*c#usi+e #ocks1ntent #ocks

    Schema Locks

    What is dead#ock?

    A dead loc! is a situation in which two users >or transactions?have loc!s on separate objects, and each user is waiting for

    a loc! on the other@s object. It usually occurs in a multi*userenvironment.

    What are triggers?

    A trigger is a bloc! of code that constitutes with a set of T*#45 statements that are activated in response to certainactions. A trigger can also be interpreted as a special !ind ofstored procedure that is e-ecuted whenever an action, suchas data modification, ta!es place.A trigger is always defined on a table, and is said to havefired whenever the data in the underlying table is affectedby any of the Data &anipulation 5anguage >D&5?statements*I:#ERT, )9DATE, or DE5ETE. A trigger fires inresponse to an event li!e insertion, updation, and deletion ofdata.

    Triggers help in maintaining consistent, reliable, and correctdata in tables. They enable the performance of comple-

    actions and cascade these actions to other dependanttables.(haracteristics of a trigger

    It can be associated with tables.

    8

  • 8/12/2019 Basic SQL Faq Ans

    9/24

    It cannot be defined on temporary tables or views.3owever, it can reference temporary tables andviews.

    "henever any data modification statement is issued

    then #45 #erver fires it automatically. It cannot be e-plicitly invo!ed or e-ecuted, as in thecase of stored procedures. Triggers can be nested up to B levels. Thenesting of triggers occurs when a trigger performs anaction that initiates another trigger.

    It prevents incorrect, unauthoriCed, and inconsistentchanges in data.

    It cannot return data to the user.

    There are three types of triggers? I:#ERT

    /? DE5ETE0? )9DATE

    What is -orma#i2ation? E*p#ain three norma# forms?

    :ormaliCation is a scientific method of brea!ing downcomple- table structures in to simple table structures byusing certain rules. 3ence reduce redundancy in a tableand eliminate inconsistency problems and dis! spaceusage.

    $irst :ormal $orm

    A table is said to be in :$ when each cell of the tablecontains precisely one value.

    $unctional dependency

    If you have two attribute A and +, A is said to be functionallydependant on +, if for each value of +, there is e-actlyone value of A.

    #econd :ormal $orm

    9

  • 8/12/2019 Basic SQL Faq Ans

    10/24

    Identify the functionally dependent !eys and place them in adifferent table.

    Third :ormal $orm

    A relation is said to be 0:$ when every non*!ey attribute isfunctionally dependant only on the primary !ey.

    What are !ursors and types of cursors?

    A cursor is a wor! area called private #45 area, whiche-ecutes #45 statements and stores the results.

    !ursor ,ypes

    #o you can specify the four*cursor types for Transact*#45cursors. These cursors vary in their ability to detect changesto the result set and in the resources, such as memory andspace in tempdb, they consume. The four A9I server cursortypes supported by #45 #erver are

    #tatic cursors Dynamic cursors $orward*only cursors

  • 8/12/2019 Basic SQL Faq Ans

    11/24

    Although the database A9I cursor models consider a forward*only cursor to be a distinct type of cursor, #45 #erver doesnot. #45 #erver considers both $orward only and scroll to beoptions that can be applied to static, !ey set*driven, and

    dynamic cursors.3 What is Encryption option in SQL Ser+er?

    Encryption is a method for !eeping sensitive informationconfidential by changing data into an unreadable form.Encryption ensures that data remains secure by !eeping theinformation hidden from everyone, even if the encrypteddata is viewed directly. Decryption is the process ofchanging encrypted data bac! into its original form and so

    authoriCed users can view it.4 What are time5stamped data types?

    It is a database*wide uni ue number. The storage siCe is =bytes. A table can have only one timestamp column. Thevalue in the timestamp column is updated every time a rowcontaining a timestamp column is inserted or updated. Thisproperty ma!es a timestamp column a poor candidate for!eys, especially primary !eys. Any update made to the rowchanges the timestamp value, thereby changing the !eyvalue. If the column is in a primary !ey, the old !ey value isno longer valid, and foreign !eys referencing the old valueare no longer valid. If the table is referenced in a dynamiccursor, all updates change the position of the rows in thecursor. If the column is in an inde- !ey, all updates to thedata row also generate updates of the inde-.

    6 !orre#ated &ueries

    In correlated ueries a sub uery is e-ecuted for each rowthe parent uery is e-ecuted.E-

    #elect e. from E&9 e where e.sal F>select Avg >#al? fromemp where e.deptno G emp.deptno

    11

  • 8/12/2019 Basic SQL Faq Ans

    12/24

    7 What is 8LA" and how it works with SQL Ser+er?

    %5A9 #ervices is a new middle*tier server for onlineanalytical processing >%5A9?. %5A9 #ervices provideswiCards, editors, and information to ma!e %5A9 technologyeasier to use. %5A9 #ervices supports various data andstorage models to help you create and maintain an %5A9system that meets your organiCation@s needs.

    .4 What are the ad+antages of SQL Ser+er 7 9 o+erSQL Ser+er 6 4?

    Trigger Enhancements

    Recursive triggers &ultiple triggers per I:#ERT, )9DATE, orDE5ETE statement

    Data Transformation #ervices"eb Assistant "iCard

    The "eb Assistant "iCard has been enhanced in #45#erver H. . In addition to e-porting #45 #erver data out toan 3T&5 file, it can also import tabular data from an 3T&5

    file into #45 #erver, and post to and read from 3TT9 and$T9 locations.

    Row*level loc!ing

    #45 #erver H. supports complete row*level loc!ing onboth data pages and inde- pages.

    #45 #erver H. supports applications that span a broadrange of platforms.

    Jigabytes of memory, and a terabyte or more of dis!storage.

    #tored 9rocedures

    The stored procedure model has been enhanced in #45#erver H. to provide improved performance andincreased application fle-ibility. "hen a stored

    12

  • 8/12/2019 Basic SQL Faq Ans

    13/24

    procedure is compiled and placed in the procedurecache, all users of the stored procedure share that onecopy of the compiled plan.

    The most notable feature is update replication. )sing updatereplication, data replicated by #45 #erver H. can bemodified at multiple sites.

    SQL5Ser+er,runcate : De#ete

    .Truncate a table means data will be lost, but structure ofthe table will be present in the database.

    Synta*; ,runcate tab#e

    /.If you drop a table then the structure of the table also goesalong with the data.Synta*; drop tab#e

    0.'ou can@t delete a tableK you can delete the data in arecord wise manner.

    Synta*; de#ete from

  • 8/12/2019 Basic SQL Faq Ans

    14/24

    . If you have a clustered inde- on a column, then alsoyou can assign a primary !ey to that columnM

    /. 'ou are having rowid already then why you are goingfor the inde-M

    0. 3ow many non*clustered inde-es can be allowed in atableM

    Synta*;!reate inde*

  • 8/12/2019 Basic SQL Faq Ans

    15/24

    If a rule is applied on a table it will not apply to the alreadye-isting data in the table. The rule will be imposed from nowon the updation and insertion of data.

    Synta*

    !reate ru#e

  • 8/12/2019 Basic SQL Faq Ans

    16/24

    Rep#ication;

    Definition;

    Replication is an important and powerful technology fordistributing data and the e-ecution of stored proceduresacross an enterprise.

    The replication technology allows you to ma!e duplicatecopies of your data, move those copies to different locations,and synchroniCe the data automatically so that all copieshave the same data values. Replication can be implementedbetween databases on the same server or different serversconnected by 5A:s, "A:s, or the Internet.

    /1."hat are the types of replicationM

    ,ypes of the rep#ications;

    #napshot Replication

    %ption #napshot, with immediate*updating #ubscribers

    Transactional Replication

    %ption Transactional, with immediate*updating#ubscribers

    &erge Replication

    "hich type of replication you choose for your applicationdepends on your re uirements for data consistency, site

    autonomy, and networ! resources./8.Differences between the #45*server / and #45*#erverH. .

    /B."hat is the s l using by the #45*#erver and oracleM

    16

  • 8/12/2019 Basic SQL Faq Ans

    17/24

    #45*#erver Transact*#45%racle A:#I*#45

    /=.Is it possible to create a view with out a base tableM

    Actually the answer is :%.+ut this is possible by using the $%R(ED ;IE"#O#ynta-(reate force view P'QAs#elect from QQQK

    /2.Inde- is the only second object, which holds data in thedatabase.

    0 . &%DI$'O is a !eyword only it is not a clause.

    0 ."hat will happen if you add a not null constraint on to acolumn if that column is already having the null values andwhat is the status of those null values, which are alreadypresentM

    An error is given stating that null values are found.

    0/.I am doing a transaction, I am having four activities inthose four fourth activity got some problem, then will be thetransaction committed or roll bac!edM

    Automatically it will rollbac!, because a transaction is said tobe committed when all the activities of that transaction isperfectly e-ecuted.

    Coins

    00."hat is a joinM

    01.3ow many types of joins are thereM

    08."hat is the difference between the outer join and leftouter joinM

    17

  • 8/12/2019 Basic SQL Faq Ans

    18/24

    0B.3ow to ma!e a copy of a table >if you have a table withsome name P, is it possible to create a table with a name 'by using the table PM

    E*p#anation;

    SQL ser+er

    Se#ect

  • 8/12/2019 Basic SQL Faq Ans

    19/24

    1 .Is it possible to create a single stored procedure onmultiple tablesM

    'E#.

    What is SQL and where does it come from?

    #tructured 4uery 5anguage >#45? is a language thatprovides an interface to relational database systems. I+&developed #45 in the 2H s for use in #ystem R. #45 is a defacto standard, as well as an I#% and A:#I standard. #45 isoften pronounced #E4)E5.

    In common usage #45 also encompasses D&5 >Data&anipulation 5anguage?, for I:#ERTs, )9DATEs, DE5ETEsand DD5 >Data Definition 5anguage?, used for creating andmodifying tables and other database structures.

    The development of #45 is governed by standards. A majorrevision to the #45 standard was completed in 22/, called#45/. #450 support object e-tensions and will be >partiallyM?Implemented in %racle=.

    ow can 1 e#iminate dup#icates +a#ues in a tab#e?

    (hoose one of the following ueries to identify or removeduplicate rows from a table

    &ethod

    #45F DE5ETE $R%& table name A "3ERE R%"ID F > / #E5E(T min>rowid? $R%& table name + 0 "3ERE A.!ey values G +.!ey values?K

    &ethod /

    #45F create table table name/ as select distinct fromtable name K

    19

  • 8/12/2019 Basic SQL Faq Ans

    20/24

    #45F drop table name K #45F rename table name/ to table name K

    &ethod 0

    #45F Delete from where rowid not in> #45F select ma->rowid? from #45F group by ?K

    &ethod 1

    #45F delete from mytable t #45F where e-ists >select S-S from mytable t/ #45F where t/.!ey value G t .!ey value #45F and t/.!ey value/ G t .!ey value/ #45F and t/.rowid G t .rowid?K

    :ote If you create an inde- on the joined fields in the innerloop, you for all intensive purposes eliminate :U/ operations>no need to loop through the entire table on each pass by arecord?.

    ow can 1 generate primary key +a#ues for my tab#e?

    (reate your table with a :%T :)55 column >say #E4:%?. This column can now be populated with uni ue values

    #45F )9DATE table name #ET se no G R%":)&Kor use a se uences generator

    #45F (REATE #E4)E:(E se uence name #TART "IT3 I:(RE&E:T +' K

    #45F )9DATE table name #ET se no Gse uence name.:EPT;A5K$inally, create a uni ue inde- on this column.

    20

  • 8/12/2019 Basic SQL Faq Ans

    21/24

    ow can 1 get the time difference between two dateco#umns

    select floor>>date *date/? /1 B B ?N0B ?

    VV S 3%)R# S VV floor>>>>date *date/? /1 B B ? * floor>>>date *date/? /1 B B ?N0B ? 0B ?NB ? VV S &I:)TE# S VV round>>>>date *date/? /1 B B ? * floor>>>date *date/? /1 B B ?N0B ? 0B * >floor>>>>date *date/? /1 B B ? * floor>>>date *date/? /1 B B ?N0B ? 0B ?NB ? B ??? VV S #E(# S time difference from ...

    ow does one count different data +a#ues in aco#umn?

    select dept, sum> decode>se-,S&S, , ?? &A5E, sum> decode>se-,S$S, , ?? $E&A5E, count>decode>se-,S&S, ,S$S, ?? T%TA5 from my emp table group by deptK

    ow does one se#ect e+ery n th row from a tab#e?

    &ethod )sing a sub uery #E5E(T $R%& emp "3ERE >R%"ID, ? I: >#E5E(T R%"ID,&%D>R%":)&,1? $R%& emp?K&ethod / )se dynamic views >available from %racleH./? #E5E(T $R%& > #E5E(T rownum rn, empno, ename $R%& emp ? temp "3ERE &%D>temp.R%":)&,1? G K

    ow does one se#ect the top n rows from a tab#e?

    21

  • 8/12/2019 Basic SQL Faq Ans

    22/24

    #E5E(T $R%& TableP a "3ERE FG >#E5E(T (%):T>DI#TI:(T ma-col?

    $R%& tableP b "3ERE b.ma-col FG a.ma-col? %RDER +' ma-col DE#(K

    ow to imp#ement if5then5e#se in a se#ect statement?

    The %racle decode function acts li!e a procedural statementinside an #45 statement to return different values orcolumns based on the values of other columns in the selectstatement.

    E-ample select decode>se-, S&S, S&aleS, S$S, S$emaleS, S)n!nownS ? from employeesK

    :ote The decode function is not A:#I #45 and are rarely

    implemented in other RD+ offerings. It is one of the goodthings about %racle, but use it sparingly if portability isre uired.

    ow can one dumpF e*amine the e*act content of adatabase co#umn?

    #E5E(T D)&9>col ? $R%& tab "3ERE cond G val K

    D)&9>(%5 ? ************************************* TypG2B 5enG1 B8,BB,BH,0/

    22

  • 8/12/2019 Basic SQL Faq Ans

    23/24

    $or this e-ample the type is 2B, indicating (3AR, and thelast byte in the column is 0/, which is the A#(II code for aspace. This tells us that this column is blan!*padded.

    !an one drop a co#umn from a tab#e?%racle does not provide a way to DR%9 a column.

    . update t set column to drop G :)55K rename t to t baseK create view t as select specific columnsF from t baseK/. create table t/ as select specific columnsF from t K drop table t K rename t/ to t K

    !an one rename a co#umn in a tab#e?

    :o. rename t to t baseK

    create view t column list with new nameF as select from t baseK/. create table t/ column list with new nameF as select from t K

    drop table t K rename t/ to t K

    ow can 1 change my 8rac#e password?

    Issue the following #45 command A5TER )#ER usernameFIDE:TI$IED +' new passwordFN$rom %racle= you can just type WpasswordW from #45 9lus,or if you need to change another userSs password, typeWpassword user nameW.

    Workaround for snapshots on tab#es with L8-Gco#umns

    23

  • 8/12/2019 Basic SQL Faq Ans

    24/24

    'ou can use the #45 9lus (%9' command instead ofsnapshots if you need to copy 5%:J and 5%:J RA"variables from one location to another. Eg

    (%9' T% #(%TTNTIJERXRE&%TE *(REATE I&AJE TA+5E )#I:J * #E5E(T I&AJE :%, I&AJE * $R%& I&AJE#K

    :ote If you run %racle=, convert your 5%:Js to 5%+s, as itcan be replicated.