0% found this document useful (0 votes)
108 views39 pages

Dbms 1&2

..

Uploaded by

Tushar Rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
108 views39 pages

Dbms 1&2

..

Uploaded by

Tushar Rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 39
PUBLISHED BY: Apram Singh Quantum Publications? (A Unit of Quantum Page Prt. L1a) Plot No, 59217, Site 4, Industrial Ac, Sahibabad, Ghaziabad-201 010 Phone :0120- 4160479 Email: pagequantum@@igmai.com Website: www.quantumpage cain Delhi Office : 16500, Bast Rohtas Nagar, Shahdara, Delhi-110032 © Au Riess Restnveo No pat of this pblaton may be mpl or meni, ‘nay for o by amy means, Information contained in this wok served fom scares beteved oe reliable Every effort hasbeen nade terse accuracy however reither the publisher nor the authors suntan the accuracy or completeness of any information Publshed heen and ether he publisher north authoes | shal be responsible for any errors, omissions oF damages arising out of use of this information. Database Management System (CS/IT : Sem-5) 1 Baition : 2010-11 2 Edition : 2017-12 5 Baton : 2072-19 4 Baition : 2013-14 5 Edition : 2014-15 2015-16 2016-17 2017-18 2018-19 10° Eaition : 2020-21 (Thoroughly Revised Ration) Price: Rs. 10/- only CONTENTS ECS 501: DATABASE MANAGEMENT SYSTEM, ‘UNIT: : INTRODUCTION (-1A101-384) arr patabase Systm vs Bile System, Database Sytem Seer chitecare, Data Model Schema ad Instances, Con a ree an Dashes Langue and interes, Dat Oa ere ngs, DML Overall Database Strut. Data Pett ae Ent Reatenhip Model ER Model Concept Neti fer Bk Dagram, Mapping Constains, Keys, Concepts Novo Wey, Candidate Key, Primary Key, Generalization, pe tution of an ER Diagrams to Table, Etended En Model Relabonshp of Higher Degree Untr2: RELATIONAL DATA MODEL @1Ate2434) ‘atl Dts Model Coe ey Cotas Ey say Fetka iaegiy Rye Castins Denotn Cran, Keltirl Restaura Ct, Tpi snd Dea Cae econ a Garceteof SQL veg SOL 5 Dt Type and fen typeset 8 Corus SOL Opt nd Tet Pdi ‘ise Visonic Que and Sa are ape rts irre Up snl Dt Opt Unie beret Mus (Gres Prete SOL/FLSO UNITS: DATABASE DESIGN & NORMALIZATION (3-1 Ato8-19) Fanta dependencies, ormal forms st second, 8 third foal forme BCNF,Teluuton dependence, fovs lev in decompositions, nornaliztion wing FD, MVD, and [Ds Stematve approaches daubve destgn UUNIT«: TRANSACTION PROCESSING CONCEPT. (4-1 Ato4-844) Teanuacon Syn, Testing of Serazabiiy, Sella of Scheie Cont View Serle Sede Recovery, Recovery from Tranaation Faltes, Lag Boed Recover, Checkpoints" Deadiock Handing. Dntbute, Database Dante Data Storage Concurrency Cor, Dieta) Stem UNITS : CONCURRENCY CONTROL TECHNIQUES G1 105-27 4) ‘encutecy Cnta, Laing Teco Cacurency Cal “ime Stamping Pests fr Conteency Cont, Valaton ated Procol, Mulple Granular, Mall Version Scher, Recovery with Concent Taran Case Stu of One SHORT QUESTIONS, (SQ:1A1050:184) ‘SOLVED PAPERS (2015-1670 2019.20) (SPI AWSPASA Parti : Parez : Parta : Part-t Pars ~ CONTENTS Overview, Database Syatem vs File System, Database System Concept and Architecture 1-28 to 1-88 Data Made! Schema and Instances, Data Jndependence and Databste Language and Interfaces, Data Definition Language, DML, Overall Database Structure 1-94 to 1-168 Data Modeling using 1-16A to 1-224, the Entity Relationship Madel ER Model Concepts, Notation for ER Diagram, Mapping Constraints Keys, Concept of Super 1-824 to 1-27 Key, Candidate Key Primary Key, Generalization, Agerogation Reduction of an BR Diagram 1-27A to 1-828 to Tables, Extended ER Model . Relationship of Higher Degree - 1-1A (CBAT-Sem-5) SES ath / Introduction Introduction ‘overview, Database System vs File System, ‘Database System Concept and Architecture Gee | What is database management are the tasks performed by users in DBMS 7 siware whichis use to Database management system (DBMS) is a software which it vee cae the database. For example, MySQL, Oracle, are commercial TTtabase which is used in different applications 2 DBMS provides an interface to perform various operations like database eee atoning data, updating data creating a table in the database ate ‘4. Itprovides protection and security tothe database, Incase of multiple ‘users italso maintains data consistency. DBMS allows users the following task 1. Data definition :It is used for creation, modification, and removal of database object that defines the organization of data inthe database, 2 Data updation :Itisused forthe insertion, modification, and deletion ofthe actual data in the database, |. Data retrieval: It is used to retrieve the data from the database ‘which ean be used by applications for various purposes 4. User administration :It s used for registering and monitoring users, maintaining data integrity, enforcing data security, dealing with Concurreney control, monitoring performance and recovering information corrupted by unexpected failure. Que ia | What are the advantages and disadvantages of DBMS? “Answer Advantages of DBMS : |. Database redundancy :It controls data redundancy because it stores allthe data in one single database ile and that recorded datas placed inthe database, Database Management System LACS Sem, ota sing ie DOUS, te rind tr rp Feerear penser ne ey mance terested te meets on 4. Hotness ag £ Sitpsipede bcp nd oe lone wh Neen Aaiyet tae bases nd tn Seow beinstnauel Mati werntrce tpi itn eerie Sei were oti rome Dindantage of DMS: "Can tarde and steare 1 gi gh ed da sone some Sean DS wher 2. Gheritecpe tla pe oi ny ema na efficiently. me 2 Copley: Dt ye ee siti empty ee 4 pherimpet fare Pl ih ingacet beatae tetas nao panned node ary aera ceca SS Stn hasan WETS] What do you understand by database users’? Describe the different types of database} “Kawver | aan wert nw atk he enfin, The rt tes es etn on ne nd a fe ct ening onthe ed and way of ceaag 1 Appian programmer 1 They rhe developer wh erat hth lan by mea of DML queries, aoe These DL qrieare writen inte apa pansies C++, JAVA, Paseal ete. i mas ce qui ae converted tn ae cman wi ‘the database, " = 2 Sophnicnted were: 2 Thy ae dtc eos, wrt SQL urn sl insertideletelupdate data, er o S Revere hn yest ge ‘Thee wer canbe cents eines analyst wo thor ody SQL and DBMS a api the cnceptia three onag The ve menus ana oP interfaces meh wil ave menos peel sing application to interact users who use the ex Tor example, nine stems, ATMS he ay pte ket asking 7M. . are data adeministeavors? What are the functions oie “database administrator 7 ‘aswer Datakoce administrators are the perso! Programs used for accessing the date Fenetignsrate of database administrator (DBA) : 1 Schema defini ‘Original database schema is defined by DBA. definitions, which are 1b Ths is accomplished by writing a set of definitions, ‘Tultedy the DDL compiler to aset oflabels that ae permanentiy ‘Moredin the data dstonary. 2 Storage structure and access method definition : ‘4 Thecretin of appropriate storage structure and access method. 1. This is accomplished by writing a set of definitions, which are ‘translated by the data etorage and definition language compile. A. Schema and physical organization and modification ‘Mato ofthe database schema or the description ofthe physical storage organization 1 These changes are secomplished by writing a set of definition odo ‘modifeation othe appropriate internal system ables. ranel's who has control over data and taba Manage! System Home, aon vena ahr er QTR) wrae in date abstraction ? Explain different srnetion ~~ ewer | Ont train the pce fing reer detail acing the background details from the users nim me Ditorent ves at breton View tert ETA. Toe re lero dat betracton 1 Phyleal evel Sortie vet evel a aterm nd deci The plone! eel dacs the comple lowe betes le evel data 2 Lagical evel Lapeal eve the next she data ae sored in smog tae ata The peal level thus deseribes the ent small numberof lative mpl 2 View bevel igher level ofabstretio anit descr the databee, and what elation vi it database i terms os View tee the highest ofthe entire data 4 The view evel of shtrction exist t i Peter be imply thie interaction level of abtrction it desribes aly part "he evtem may provide many tre or he same databa Introduction the dittersares betwors piysten! level view level of data abstraction: aay View evel | Logical evel | "This w the médle evel This 1s the highest no) Physical level 1 Tet es gtdaaaetraction veo daa It deweribe how | It describes what data It describes the user 2 | descrip aster in databave teraction with Sve indatatas : 8 I those series the It deveribey the Wdecrbvead a — low level ‘structure of whole part of the database snr varenn databace and bides|in which the wpers ae hea of physenl snersted nd hides ca storage structure rest of all information from the eure ‘1 Aseripot aware A user in not aware of A user is aware ofthe the complesity the complexity of complesty of database database WET spain ne iteence beoweendatabane management system (DBMS) an file ystem | scoall : co File System 1 In DBMS, the user 1 mot tn this system, the user bas to required to write the, write the procedures for managing procedure [Be fle - 2 DBMS gives an abstract view Fil stem provides the detail of fdatathat hides the details the data representation and l _ storage of data. ‘Types of DBMS architecture, ie request done b L-Tier architecture: 1 2 8 Inthisarctestare the datas ie Any changes done are directly dove o the dstabase ne ‘not provide handy tol orcad ware coe Tee Mier architect is de depot a pplication, where progransercan ditty emma wk "he database forthe qk epanse. iL 2Tier architecture 1 2 ‘The 2-Tier architecture insame arbi clen- weve, Inthe two-tier architecture, applestions on th leat adn directly communiste withthe database a tho sre sie Pe this iteration, APT suc as: ODBC, JDBC are ‘The user interfaces and appliitin roams ar uno te client de retort ent 7 2 ne gl aterat with an appiction Ts enn rete eth he database Se. soil ‘nas no idea about the existence of the database beyond Fate database ao hana de bot a ee reyend the aplatin. se ureter ised in cae oflarge we appiaton. [Aptana ee Wig: 11.991 arcttre, test ata Mode! Schema ond Tnstanes, Data Independence ang Se Language and Interface, Data Definition "anguage DML, Ovrl Database Structure WeeT | wat are data models? Briefly explain different typeg, datum =a Date dl: 1 Dat edo pl rte the abe da, 2 Datobiaclecin cnet dering, ‘relationships, data semantics and consistency constraints. “4 ata ms dete tice cath oierad are processed and stored inside the system. het ‘pero data mol 1. Eat relationship models Teeny eon ER conse alton. ‘paced etre aetna otitis are represented sts, 5 a by means oftheir properties, calla 1 &Therelatonl mode represent by coleion of ate ees ta and relationships among dit wh etn tales cach of which has a numberof eee Gort “rasver | ‘etatioal data mode isused fo data storage and procsing, ea rae a Hierarchical model: Tr bierarchical mode data elements are linked as eninverted cee ‘Revere rot atthe top with branches formed below), ‘bp Below the single oat data element are subordinate element cach Bele chin tra has its own subordinate clement and oon, the trovean grow to multiple levels. ce _ Data clement has parent child relationship asin tree, [Network model: f_ This mols the extension of hierarchical data model ‘LInthismodel here exist a parent child relationship bt seid data ‘ement ca have more than one paeat element or no prea a. Object-oriented model: fa Object-oriented models were introduced to overcome the Shortcomings of conventional models ike relational, heard land network model. 1b Amobjoctoriented databases allection af objects whuse navi, State, and relationships ere defined in acordaee with eet ‘rented concepts such as objets, las, Describe data schema and instances, “The description of a databace i called the database schema, which specified during database design and is not expected to change Frequently Mos of the data models have certain convention fr displaying seh se dingram which called as ehemadigram. ‘schema diagram displays only ome aspects of schems, sch asthe ‘ames of ecord types and data tems, and some types ofeonstrats. For example: Schema diagram fer stuientinf database ‘Student (Name, Student_number, Class, Brae) Course (Course-name, Course number, Department) Instances: ‘The data inthe database at a particular momen called» tabs state or anapshot, tis al aled the current st of erences & Instances inthe database. se bac neater eros evr. pcieen caer ttre ret al ase tte a Sere nen bcemendbomat string ea ono tte edo ae es Erwan eae othe dab SEIT rin tinder witht pe on pi dt ndepndense wih 9% = Data independence: Duta independence defied asthe capacity to chang, etches oe evel os database system without having to change thy schema at the ent ager level ‘Types of data independence 1. Physcal data independence: 4 Pye data ndependence te abit o modify internal hema ‘rat hanging te concepts chem. Madison a te physcal eve eraionally necessary in ode ‘wimproe performance ‘kot mutt cnr cman 4. Raample of phy! dat independence are wa r reorganizations of wing a new access path or odijing indexes ete 2 Login! data independence * ape aa deans be ity te modify the oer scheme sito havng change the extra schemas {cre many of he tral mad changes i te Example of eral at independence are aditinremoval of S| Describe the classification of database Whien em) of database language. Whi haces he following term: o ea erms i) DDL Command (i) DM comman: LALA eM Sem 5) ffeil Guonfication of database angoages 1 pata Definition Language DDL) De DDL is wet of SQL commande used erate utabese structures but net data, ‘oy and deta ‘They are ned by te DBA to limited erecta tahoe desir, Te application developer — «Create, drop alter, treat sre commonly ied DUL emma 2 Data Manipulation Language (DML = "\ DML is language that enables users to sce or maniltes dita as organized bythe appropriate data made » by There are two types of DMs i. Procedural DML :It requires aur specify what ata rv needed and how to get howe da, iL Declarative DML (Non-procedural DMLs):I: eres eee co specify what dain are Seeded without secing how to get those data, vert update, delete, query are commonly wed DML commands 4 Data Control Language (DCL): ois the component of SQL statement that esr reso dta fl tothe database 1 Commit, ollie command are wsed in DCL. A Data Query Language (DQU recs the component of SQL statement that allows tng dia from the databace and imposing order 28 1) Teincudes select statement. 5. View Definition Language (VDL) 1 WDlis used tospeify ser views ander schema onde avaiable to canes reer Beco aapping once 2 defines the subset of re 5) Tete vital ables andthe view pea ewe 4 Teepeifes ser interfaces. SQL isa DML ange asin deta wie ‘SeeTAR n nan ae a LISA(C8TT emg) eee Examples: ppt: (CREATE ALTER, DROP, TRUNCATE, COMMENT, GRANT, REVOK: DML: INSERT, UPDATE, DELETE wtatement pet: (GRANT and REVOKE statement Dau. SELECT statement voL: 1 rea view emp as select "fom employee where dao = 5 Creates view for dept S employees. 2 crate viewempdeptas select fame, Ina, don, dame ‘om employee departent were dnednmber; Creates view sing two tbls, {ee plain DBMS interfaces What are the various DRM interfaces? sre aly “itt uy lng ta "aio DBMS interfaces ane 1 Menu based interac for © Rites the wer ith ito os ‘ser through the formulation ofa request ae sas "Sr pplr tno Ne aed sep © Be abe ten nn rovsg ire {nll rough he ntentoe he anstructured manner. oz ‘eb clients oF browsing 4 aren & ormobasedntertce armen ae sista frente inert ate Dewi aut only certain enti, in which the DBMS wil retrieve ee resleannontyaane 4 Grpha sr nterfaree GUD: sere nals day asebeat the wer in grammai to diagram ti ‘oro a spe aquery ty manipulating thing . ‘many cases, GUIs utilize both menus and forms. —— ar frataraagangentertace hats orn schema, which sina A ra cama ue wel a Setonay of 4 Theatr! lngvge trie refs th word a ches, tart hebetStaandardwrdnisdctonry tener oe €thelnerpretatin a ren the tart generat igh Sane) aromaiecs tu mamnlingsior eee ls Pio he DEMS er prewang oeeane ret Staleudtiewertodnibereneet 5 Speech input and output: ‘The speech inpot is dotectd using Kbrary of predefined words snd used toset up the parameters that are supplied tothe queries b., For output, asi takes pce 6 Interfaces for the DBA: & Most datahase systems contain privileged commands that ean be ‘sed only by the DBAs sta. ‘These include commands for creating accounts, setting system Parameters, granting account authorization, changing schema ‘and reorganizing the storage structures of a database, Qe 1.45, | Brietty describe the overall structure of DBMS, oR ‘Draw the overall structure of DEMS and expla bee ‘Answer lar conversion frm text or nunbersinto speech » A database system i partitioned into modules that deal with each ofthe ‘esponsitlitiesof the overall system, The functional eompunents ofa dataaeo ‘stem can be broadly divided int two components 1 arabes Manse Serta Vesey = weet Pepto] [nee]! Pig 1, 0 oie hese {24th plete Scone Ol src rg eng ri ogra nda i sine vee data toed th date Simmer nomi Be ‘tifction of nin ReeBtY max cic mand ange «tit 4 EMG om ae ty _ mst ate dee sare thatthe database remains in ef tem uae ont need viowonnone Introduction “trmanages te alcation of spac an disk tors Te mana to epreseat nora 0708 File manne! Bae date structs nis for feching data fom ek etacache nm tof the database Sativa ore yaw ste ee un the ize man me: . urn enor (QP): The Query Pret a 2 query Procensa (QP ry tatement sent t SQL Server and pen ata peor the reget operon. he QP components are Sr interpreter:Iisterprets DDL state Pitan mast dition : ares ttrarlnes DNLstatersentsi a guey lene Da comer unconmnting flow lve nstrutions a the ie ation cgi underteds. “edhe optimization +t picks the lowest cost evaluation plan estrone he erative. 42 Gueny evaluation engine : It executes low-level instructions Seercd bythe Dh comple. PART: Dota Modeling using the Entity Relationship Model: BR Model Concepts, ‘Nuttin for ER Diagram, Mapping Constraints. sments and records the Questions-Answers ‘Long Anawer Type and Medium Answer Type Questions, ‘QueTIG] What is ER model ? What are the elements of ER-model ? on What ae the notations of ER diagram ? “Aaewer Anentity relationship model (ER mode!) el ER model isa way of representing tho entities ‘andthe relationships between the entities in arder to create a database Database Management System ecieeetion of EE mode gran 1. Batity: pen nent ina real world object tha-can be easily identifiable, bh Amentity can be abstract <._Anentity isan object that exists and is distinguishable from othe hes 2 Entity set 4 Enftystie a collection of similar typeof entities 1h Amentiy set may contain entities with attribute sharing similar vals, A Attibute Amattribute gives the characteristics of the entity 1, inal called as data clement, data field, afield, adata item or at elementary item, 4 Relationship: 4 Arolationship is the association between entities or entity 4 Relationship is represented by diamond with straight lines ‘connecting the entities, QoeTIT] What do you understand by attributes and domain Explain various types of attributes used in conceptual data model ‘Aaawer Attributes: L {itbutes ar properties which are used to represent the entities A attcioutes have val tac, and age a atibuten Foreenit domain orrangeofvalues that canbe asiged to atibes xample,a student’ me cphatentls ¢ student's name cannot be a numeric value. Its Domains Students age cannot be nogative, ete ues. For example, a student entity may hive domain i is am attribute eo sate Vals tate atte constraint which determines the typeof 2 Rinne Femited fr tha atrbate atts Unains can be very large, or very short. tinny Dedivided frther putPle attributes are atomic values, which e385, ‘valueof i digiar ©" ®4™plo, student's phone number isan at0™ 1 TATACCSAT Sens; 1-194 (CIT SOD) 2 a Introduction posite atribute : Composite attributes are made of more than Composit ciriute, For example, a stulen'scomplee name may have fist -name and lastname attribute Derived attributes are the attributes that donot Derived ter rial databace, but thelr values are derived from eter ca ce resent in the database. For example, average salary in a guribues Popouldnot be saved dretl inthe database, nstead can tederved single-value attribute : Single-value attributes contain single value Forbeample Social Security Number. Muiti-value attribute: Multi-value attributes may contain more than MeMiues, For example, person ean have more than one phone ftomber,email-address ete GReTAS] What is purpose of the ER diagram ? Construct an ER diagram for a University system which should include information ‘shout students, departments, professors, courses, which are enrolled fudents ‘which course, which professors are teaching which courses, student grader, which course a department offers. ==) Purpose of the ER diagram [ER diagram is used to represent the overall logical structure ofthe Atabane ER diagrams emphasis on the schema of the database and not on the Instances because the schema of the database is changed rarely. It is useful to communicate the logical structure of database to end It serves as a documentation tool Whelps the database designer in understanding the information to be ‘Fig. 1.18.1. ER diagram for University system. ACen, {COAT Sag sa) a BR dingram fora small marketing ean ee rn data requiem — ite ero Including number tt in iter (b) course offerings, s-aa(cstT-Sem3) Introduction ar, semester section number, instructors), timings and jluding student-id, name and program; luding identification nus eat aed to students in each course they are enrolled = wwtropriately modeled. Construct an ER diagram for hs ‘office. Document all assumption that you make for must fhe registrar's about the mapping constraints, Taner | diagram, the main nity es are ten, core curs ofering Fa Ra ye court ofleringioaweal ey depend a The avons made re "ler ects nly toe particular plas ad tne Tht ER diagram cae fa aco ncting st diferent paces at ferent ties th There tab gurantes that he dalabese does ot have te csr ectingt eae place and tine Se = Genes > Tro { & [zeta] ~< eatollein) i, ‘Relational Caleulus, Tuple and Domain Calculus caleulus ? Deseribe its importans ‘characteristics. Explain tuple and domain ealeulus, OR ‘What is tuple relational eeu and domain relational ele ‘Anawer Relational seul isa nox-procedura query language. 2 Relational ealewasisa que formulas vesting ofa ‘hese variables, va relational calcul, query. Important characteristics of relational caleulus The relational calculus is sed to measure the el relational languages. 2 Relational calculus is based on predicate calculus ‘In relational cleus, ser isnot tain the resus, 4 Inselationaealels, ot about its eee ‘Tuple Relational Callus (TRC) : 1. TheTRC ss non-procedural query language 2 desribesthedesiredinfoat forobtining tht information, ry sysem where queries are expressed an er of variables and anexpresion nang there is no description of how to evaluate « ectve power of ‘concerned withthe procedure to put valable without knowing the method ion without giving a specie procedure 2ALACSITSem5) ery iw TRC s expressed 8 wi pol et fall tuple such that predicate Pis tre for 1-The ‘titi dente the vac of ope ont Aad anotat used to denote that tuple fis in relation r. Te tara eu {ge are built using the atoms and the following rules Foe BP atom ie forma UP, iv formula, then so are Py and) 8 I, and P, are formulae, then 90 are Py v Py, Py » Py and + erin hen 3oer((oand y ¢7 Pjobarea ruse Feelin ieee Sar ta ch eto wh a es 1 pmain rather than values Tor aneatiee tuple a onrennth DRC of he rm eter? | Pedy ol here fy fps fy Represent domi formula compose of tons 44 Anatou in DRC has one ofthe following forms A egity o> €rewhere ina relation on m attributes and {pane domain variables or domain constant. 1 ey, where x and y are domain variable ond iw comparicn operator |The attribute andy ust have te main that ean be compared & xDe,wherex isa domain variable, Pisa comparion operator and isa eostant in the domain of the atte fr which «i a Somain variable 4 Following re the rules ta build up the formals Anatom isa formula 1h FP in aformula then sis —P, formula, then so are P, v Py Py» Py and — puadnsens elation Data Mode & a a any “4 IF Pie formula ins, where x isa domain vai 412 (P\c) and x ¥ (Pa) are also formulae. a PART-4 Introduction on SQL : Characteristics of SQL, Advantage of Qu, ‘Que 2.10. | Write short note on SQU. Explain various characteris of QL. =a 1. SQL stands for Structured Query Language. 2 Tt is @ non-procedural language that can be used for retrieval sx management of data stored in relational database 3. Teean he wsed for defining the structure of data, modifying ata int database and specifying the socurity constraints 4. The two major categories of SQL commands are a. Data Definition Language (DDL): DDI. provies commis that can be used to create, modify and delete database chee, bs Data Manipulation Language (DML) :DML provides commis that can be used to access aad manipulate the data, tha is retrieve, insert delete and update data ina database ‘Characteristics of SQL 1. SQLusageis extremely flexible 2 Thusesa fre form syntax tha gives the user the ability to struct 'SQh statements ina way best suited to them. ‘Bach SQL request is parsed by the RDBMS before execution, th for proper syntax and to optimize the request. ‘lite certain programming languages, tere sno ned to star i Natesonts n'a pariclar column or be fnisbed ina singe i. ame SQL request ean he written in a variety of Ways 8 Tr] What are the advantages and disadvantage of 544! seein Sn suncarems wea, Fs st net: Leet ee ee ee nae ie fan fo ct Ft fap A Nr nsonona ao Senecio Spee temmnint icin Ce peg rnp ee ee oe Say al din ae owen 5 i nf tm a Partial control: Due whidden business ues, complete contois not piven tothe databace ‘SQL Data Type and Literals, Types of SQL Commands, ‘SQL Operators and their Procedure f Questions-Answers |_Lang Answer Type and Medium Answer Type Questions ‘GueA2, | What are the different datatypes used in SUL? ‘Answer SQL supports following datatypes: 1 chart) A fied length character striate pene length * 2) a - PAA A(CSMT Sem) Relational Data Model & s4accsiTsemS) ane ‘2 varchar (x): Avarible length character string with wer ap = oy ‘aximum length ‘A. int An nteger whic isa finite subset ofthe integers tha dependent. oe 4 small int domain type. 5 numeric (Ps consists of di pont 4 realor double precision: Floating point and double precision Mot juin gumbers with machine dependent precision. “| 4 float in): A floating point number with precision of east digit, a date: Acaendar date containing a year four digit, month two dg and day two digit ofthe month, ‘time: The time of the day in hours, minutes and seconds Que] what are the types of literal wsed in SA? Tower | ‘The four kinds of literal val 1. Character string: ‘a. Character strings ae written a insingle quotes. The single uote characte tp two single quotes. For example Query Language’ 2 Bit string: ‘a. Abit string ia writteneither ass Jhaale quotes and preceded by the Fouaimal digits enclosed in single lester 8 bb Forexample,B 1011011" BY. 3 Exact numerie: ‘Those iterals are written asa signed o possibly with a decimal pot b._ Forexample,9, 90, 90.0, 0.8, + 99. 4. Approximate numerie: “Approximate aumerie literals are writen 35 ibid by the eter‘ followed by asigned oF ns + B5E-5, + 885-5, 0S5E,— mall integer is machine independent subst of iniog, oe 2 eee tues supported in SQL are ssasequence ofcharacters enced in character ting is represented with Eng, Stroctred ‘Computer quence of sand Is enclosed Teatro 25 a Sequens quotes an preceded 1 Bo,Xxas.XT - snsgned decimal nur 99, -98 98. exact numeri itera ign ines 535-2 b Forexample, SES, 85.585, pune Kenereentsnien MEAT m GaeRT | wat are the dierent peo SQ commande? erent pes of SQL command ae Insert: rows command isso inser tpn ata © Fhaveommand ads angle tuple time inate, syntax Sree totable same tbs. ses 2 Update: tc command is used make changes inthe ales atti fthetable tp Tete set and where lause Syntax ee aune sett name =a i Delete pee iscommandis usd to remove nk Taplrcon be deleted romenly ope table at ati Syntax Delete fom table_name where coin: 4g elet hs command ised ote neo aren Ma comare table Syntax Syme bute, atrbte, from ale same one Altertable eure otal ae pisconmand is wed tomake changes bb This command is used i toaddan attribute ii to@ropan attibote it rename anattrbute i. toadd and drop Syntax ‘er table table_nare at same drop qi. ppLeomnant® Juss name dla jum Aker abl table ‘Ales table able name OP Weeds] Write a short note om DAGA(CSITSems) “Anewer 1. SQL DDLinwsed to define relation ofa system. The general syntay SQL sentence is ‘VERB parameter], parameter... parametern) bb Therelations are eeated using CREATE ver, 1. CREATE TABLE: This command isused to create anew eats and he corresponding syntax (CREATE TABLE relation_namne (fick datatype sie, feld2 datatype (s (sie 2 CREATE TABLE... ASSELECT ~: This peofrrate comma, {ruse to create the sructureafanew table frm the structure ‘xisting table “The generalized syntax ofthis or i ‘CREATE TABLE relation_namet (etd, fl. ek) AS SELECT field, fla, FROM relation name Structure of relations are changed using ALTER verb 1. ALTERTABLE... ADD..: hit nused ol some extra coum {nto an existing able The generalized format is ALTERTABLE relation name ADD ine field datatype size, ‘ew field datatype sie, Reatonal Data Mode & Langu Feld dataty, Sieldn ew ieldn datatype size) 2 ALTERTABLE... MODIFY .: This form is wsed to change trith aswell as datatype of existing relations. The gener mts: ALTER TABLE relation_name [MODIFY ifieldt new datatype size, Feld2 new data ype size elds new datatype size) Que 2A6. | Draw an ER diagram of Hospital or Bank with show's the specialization, Aggregation, Generalization, Also convert it jeatian. Also comet a to relational schemas and SQL DDL. [AKT 2017-18 Marke patbase Management System slational chemise Franch branch-name, branch axes) 2TAICSTTSem5) vevmercusoniet name, customers, cetera seaunt account number, balance) Har fran oan-number, amount) oe ariel lcrroee bea a i esa hen, a eee eee ieee orisertet et a 2IGA(CSITSem-5) SQLDDL of BR diagram: create table braneh creat table customer create table loan create table employee ‘ereate table payment create table ecount create table saving-account creat table checking-aecount ‘Que 247] Deseribe the operators and i Aniwer Operators and ondit (branch-ity branch-name ansets (eustomerid customer street ceattomercity \loan-number (employeeid employee: telephone. umber start date ‘employment length dependent. (payment umber payment Payment-date (account: umber balance (interest-rate (overdraft amount Relational Data Model =a varchar 4, “rh pi umber (20, 8g umber varchar (40), vere a, varchar) umber (6) prim umber (19), 7 umber) pina har 40), umber (10, date number (4), varchar (10) ‘number (6), number (10), date), ‘number (12) primary by number (10) number (3) saumber (15); types in SQL. ions are used to perform operations such as aii ‘ubtracton or comparison onthe data items in an SQL statement Different types of SQL operators are: 1. Arithmetic o, expressions to, 4 Arithmetic operators are used ia Sd subtract, multiply, divide and negate data va ‘The result ofthis expression is a number value jgement System r 2ABA(CSITSem5) nary operators) | See "Binary operators (B) [= [ Matiteaton | Division Addition patabase Mana Subtraction ig. 2171 Arithmetic operetors, parison operators : These are used to compare one expression 2 Compre pre: Do [Operator Definition ay Inequality than Less than Tester thn or oo [Less than or equal to | ‘Fig. 217.2, Comparison operators 4. Logical operators : A logieal operator is used to produce single result from combining the two separate conditions [opertes Definition AND | Retarastroeifbath component oto | | are tru; there return ie | oR} Retr fiter mp tins te ree reur NOT | Rearstre it oti | otherwise returns false. ig 2.173.Legea operators 4. Set operators : Set operators combine the rns fo sr auerieeinta singe result “Return aldistint rows that ar ‘query, but mot in second one ig: RITA, Set operator, 15. Operator precedence: 4 Precidence defines the order thatthe DBMS uses when, the diferent operators inthe same expression, ‘b TheDBMS evaluates operators with the highest prece ‘wre evaluating the operators of lower precedence ted from the lett righ. — Definition a | Orie then _| Motiteatonand division (Character conestenation ever el ofan expen | Serrounde tale or column alias o eral teat >] oral operator precedence ‘Aiton and wabestion ~ or Fear camnon erly tg | erating — Operation not are the relational algebra (ART 2016-17, Marks 7.5] | PIA(CSITSems) operations supported te the SQL statement foreach operation. eutional algebra operations fer @.25, Page 6A, Unit gvetatemeat fr rtational algebra operations 1. Select operat toa an. numbe, branch name, amount) ‘onside the loan relation, Frndal he tuplsin whch the amount ismore than 1200 then we serie na 0180) 4. Projectoperation We write the query li al th customer names ntheireitios as n (customer) 4. Set difference operation : We can find all customers of the bank ‘Nhu have an acount but not a loan by writ ing une nme AHPOROF~ Dae al DFTOWEE) {Cartesian product: We ave the flowing wo tbls PERSONNEL, SOFTWARE PACKAGES ia | Name 3 | ai EA [ice [ser a vor | xx js» | lame_cc__] ‘We man to manipulate the x operation between [persone sofware Packages. 2a2A(CSITSem5) Pid Pam 101 = 108 108 io & Rename: ans the Bok ration wh thts Tie et Threane precede aan Aa Fe ye (Book) ‘Here both the relation name ad the attribute ames are rsa Autor, Yay ion as fallow ‘ables, Views and Indes, Queries and Sub Queri ‘QGe210.] Give the brief explanation of view. ‘Answer Aview isa vetual relation, whose contents are derived from lo ‘existing relations and it does Matin at i py m ny relation anit doc a ne tenting» query based Each time a form te part of database she Esch tn a view is refered, et lations on whichis based Sts contents are derived from snnpoetsyten ACTS i ie ii tn on ert om i cs nh Views complex view ee asin indo er aN nih nt Sd stor creating view Ce CREATE VIEW view name ASSELECT* FROM tae_name ‘MME Catezry IN att, oth or examle Conant to cut ie ansing of te Hor er angry, sb. the BOOK ean, Pane aa aol he PUBLISHER relation ca be pce as ‘GREATE VIEW BOOK. ae gELECTBOOK tie, Cteqr. Pc, BOOK. SoM BOOK, PUBLISHER HERE BOOK P ID= PUBLISHER “GaaaT pesei ndenesin se Toomer | 1 tex are seca ok abst eaapeed up data retrieval 12 Aninexbeipsto speed up SEL aa data inp withthe UPDATE and th ‘Indexes can be reted or dropped with we fet on te data teres ae used to retrieve data fromthe databae mare a nrrsannot se ends ny ae sd ape pares! quence & Syntax (CREATE INDEX index ON TABLE column: vherethe inde isthe name even [rae tale on which hat inde is that column for which itis apie 1. Unique indeses nee use for Ue maine sergeant inn ble at elas fr the fas eta tla multiple values to ente into tbe table ‘Syntax for creating unidve index i (CREATE UNIQUE INDEX index.mae Pau, Sate ut the database search engine an LECT quis WHERE dows it to that nde snd TABLE the ne ated ad con stb ae of ance of eit Relational Data Model & Langu, ON TABLE column; ‘To remove an index from the data dictionary by wing the DROP INDE command DROP INDEX index name; WHER] exptain sub-query with example. ‘Anewor A sub-query is SQL query nested inside a larger query’ Sub-queries must be enclosed within parenthesis 4. The aub-query can be used with the SELECT, INSERT, UPDATE, op DELETE statement along with the operators like =,>,'<,>=, <=, IN, ANY, ALL, BETWEEN. 4 Avub-query is usually added within the WHERE clause of another SQL SELECT statement, A sub-query is als called an inner query while the statement containing ft subs query i lao called an outer query. 5. Theinner query execute ist before its parent query so that the result of an inner query can be passed tothe outer query Syntax of SQL sub-query:A sub-query with the IN operator, SELECT column names FROM table namel WHERE columa_name IN (SELI FROM table- name WHERE condition) Example: ‘We have the following two tables student” and ‘marks! with common field Student iD. Student — | StadenttD | Name StudentiD | Total marks) wn ‘von |e va | ee ™ [we a! Now considering table ‘Staten. we want a me wan o write a query to identify al students who get more marks than the student wi i ‘but we do not know the marks of "VOO2'. a hoieemeeiat «Management System 2.25A CSI Sem-) : —_ = mar wble Mark contsning total mathaof the ent nd Se ie et oath les aly anoobaers a ‘StudentID, a. Name, b-Total_marks ae ita, marks b vm ao eg stent = VO sry rem a [voor ‘ha = ea) (PART?) ‘Aggregate Functions Insert;Update and Delete Operations. ‘Questions-Answers Long Answer Type and Medium Answer Type Questions _) QusBRD, | Write full relation operation in SQL. Explain any one of them. on Explain aggregate function in SQL al Tn SQL, there are many full relation operations like 1 Bliminating duplicates | Duplicating in union, intersection and difference Grouping |. Aggregate funetion Augregate function : Aggregate funetions are functions thet ts Input and return a single value ake a calection of eles 226A (CIT Sem) 2 SQLoffers Sve built-in aguregate functions Example: Let us consider aSQL query select angi price) as "Average Price” rom book; Output : Minimum : min Syntax: min(| Distinct |All] expe) Purpose: Returns minimum value of expression Example: SQL> selet intuit pic eam bok Output: ‘Minium Price® —Winim rce] 0) Maximum : max Syntax: mas Distinct |All] exp) Purpore: Returns maximum value of expresion Example: SQL> set mai : (nit. pric) as-Maximum Pice™ From book, ' Output ‘asia Price | Sum: sum SyntatnD tine | ALL oro oars a Example a Sic ir br Outpt: ont pie as Total turn average value of, ignoring nll values, _ Relational Data Model & Lang os Management SYS" ee 2ATA(COTTSem) + eount ‘9 Couat erat ({Distint | All] expr) Syme Returns the numberof rows where expr isnot null 7 See Ne ok? war ‘Output: No ofBooks | 5 poplin bw the GROUP BY clus SQL works What eertrenceetween WHERE nd HAVING se? cance: UP BY wa ed SQL tose eprops futon ia SUM) a0 gaol ena vera ya ed, a Ut kc ot pals a eon, niu poten vale eaarthe GROUP BY fin SLC elon SUM cine) HOM ule GROUP BY ann Example: aoe ee ee) ws 500 | emma aki. ‘SLECTCompans, SUM(Amount) FROM Sales SO BY Company . ae 1500 0 earn fooing reat WHERE rtrd __HAVING vs a 1 | WHERE lose ied for’ HAVING due eamaroo ikerng reve sod applies on | groups in SQL. i: ech ud eery 2 | WHERE clas sun bre | HAVING dase i ocd GROUP BY cause. GROUP BY clause “er [WHERE case can be se | HAVING can can epic ith SELECT INSERT, | win SELECT waren 8a THAME abbietEcawe, vont te yer (ae Copatand DELETE will returns an error. * 4 |We cannot use aggregate | We can use aggrogatefancin’ fencons inte WHERE Chur | nHONING ce trnaned ina ANG does ‘GeeTRE] Kaplan how a databases modified in SQL. on Explain database modification, ‘Answer Different operations that modify the contents ofthe database are 1. Delete ‘4 The delete operation is used to delete all oF specific rows from databace Delete command do not delete values of particular attributes © Adlete command operates only on relation or table Syntax, Abelee from table_name where condition; 2 Insert: ® 8. Insert commands used to insert data into a relation/table. ‘The attribute values for inserted tuples must be members af the attribute's domain specified in the same order asin the reli ehema, Syntax: verti ale. ame values attribute, attribute, tte Updates: Update command is used to update aval in a tuple ment Syston 229A (CSTT-Sem-5) sfanasome” 229A C81 ‘Update table_name se column. name = new. valve onion: PARTS. Joins, Unions Intersections, Minus Discus join and types wih stale example, = (ART 2017-18, Marks 10) in. Explain different types of joi einen ARTO BO, ans iw | vee used to combine rows from two rae tables, sed on Aseatumn between thes Tus epes of join operations are: 1 ne join Taner join being ined, le : Consider fllowing two relations roturns the matching rows from the tables that are For exam Employee (Emp. Name, City) Enployee Salary (Emp_Name, Department, Salary) ‘These two relations are shown in Table 2:28. and 2.252 ‘Table. 2.25.1. The Employee relation ~ Employee — | Hari om Sura Ja Y 2.904 (CSTSem-5) Fete Dae Med et ‘Table, 226.2 The Employee Salary relation Employee Salary Tomo 7000 Bila 000 | hi 00 Selet Employee Emp Name, inner join Employee Sal Employee Salary Emp Name Result: The result of preeedin Tole 225 1 and Table 22 2 aye. Salary Salty ro Emp, on Emplayer En Name Mg AUErY with selected fied 9 Emp Name | Salary Han |i om [00 [ow | som 2 Outer join ‘4 Amouter join isan exter forma the ser pi, 6 fereturns hth matching and now matching roe forthe tla ha are heii © Typesuta on ar as lows § Left outer join: The loner oi returns from tho tables being un feu the le teats For example ung a alsa on mating hein the esl al ples mall vast omer the Fight tae Select Empayen np. Name, Salary from Empleyve let ater jon Emplayee Salary en payer Ep Hesult: Th psi trig nr th sete le Table2.25 1 and Tale das ‘“ Name = Emplavee Salary Emp Nae sul oh ule oda The ih ue a opartin rane i Mthng oe nthe les Wig pola use aching os rom the nigh tale the elegans fates the tes that omen om he ae Forexample: Select Employer Emp Name, City, Salary from Eraplayee right outer Enmploste Salary on Employee Emp Name Employee Si ry. Emp Name Renult The result of preceding query with selected fields of ‘Table? 25 Land Table 225 2 Emp Name City | Salary Har 1000 ow Mumbas 7000 nt Solapur 00 ith lt ‘m0 rea et chat rot ao shen ale multipin y the number frown nthe ar fon where clause eet ng with cross join, This kind af result "shee claue is ued with rom jon i funetions ike an one pn oy Relational Data Model & mont Sytem 299 (C9ITSem-5) “Sree gist Manages ce sen) ~ pesult Sees fom ere wen OR 5 ‘Name | Manf | Drinker Poa B i” Beer i] XV [Kanike Beer — 3 s Beer] XY [aa —s [ef . = Fight outer join : Refer Q. 2.25, Page 2-294, Tiser1[ xyz [ Mahesh Bese a enter jon and gt OUT j Beer 2] ARC [Kania [Beer ae [Beer 2] ABC [Aditya [Beer GST ] Describe the SQL set operations. Beer 2 Mahesb| Beer 3] ew Boor ABC [Rani [Boer | dia [Beer] [Beer 3] ANC [Adiya"|Bee ‘mower vations are: Mahesi|Beer3] [Beer] ARC | Mates] Beer) Br SOL we raifon: Union clause merges the output of two or more Natural join = 1 2 3 Natural join joins two tables based on same attribute name and data pes ‘The resulting table will contain all the attributes ofboth the table but keep only one copy of each common column. In natural join, ifthere is no condition specifies then it returns the rows based on the common column, For example : Consider the following two relations Student (Roll_No, Name) Marks Roll_No, Marks) ‘These two relations are shown in Tuble 2.26.1 and 2.26.2. ‘Table 2.26.1. The Student relation aie. a) oil No Kame easione “| Ree gl > A —*_ | 8 ss co Table 2.26.2. The Marks relation Marks Roll_ No — 3 Lo asl der the query. Select * from Student natural join Marks ; intoa single set of rows and column geri into a single oto Beads ‘nly in ‘query one —— Fig. 2.27.1. Output of union clause. tput = Record only in query one + records only in query two + A Sng areca wth common noth queen 2 Intersect operation: The intersect clause output only rows produce ty bth the queries intersected fe, the intersect operation returns tinmon record from the output of both queries Pig. 227 Onpuctintrn aie, pat A single at of records which are commun in both eres & Theexcept operation : The except also called ax Minus outputs ‘hat arin frm table but notin second tale EO” Fig. ae 2UA(CHIT Sem) Melton Dts Moe Lag, Output « Records only in query one PART-9 Cursors, Triggers, Procedures in SQL/PL SQL. eee atte tony WeeRR] pn carom equenesand ceded nny, “Anewer | Corser 1 Acaroriss temporary work area crested inthe sytem memory when a SQL statement is executed i 2 Acursor contain information on a select statement and the rows o! ata accused by it. 3. Acursrcan told more than ane row, but an process lyon row ata 4 Theset of rows the cursor hai calle the active set There are wo types of cursors ‘© Implicit cursors: These are created by default when DML. statement lite, INSERT, UPDATE, and DELETE statements are eareuted They are also created when a SELECT statement that returet {ust one row is executed Explicit cursors: They must be created when we are execut statement that returns more than ove row 4% When we fetch a row the current row position moves to neat Sequences: Sequences are frequently used in databases because many applicatoet "etre cachrom natal toconain augue valu and segarses pone (CREATE SEQUENCE (schema eequence_name a1 Syters LAGA(CSITSem.5) anus ve siete mere ie (vale | NOMAXVALLE 5 NOCYCLE 1m ie | NOCACHE cae ee 7 veces aM The procedure specification brygins with the keyword tir ant ends ith the prcedresae paraeter lt ee cee te es samme a poral ~~ een oe cern ts 5 oo «peace mame TERT] wnat rigger? Explain different trigger with example (aT wir sa ically 1 Atrigger i procedure code segment thats executed autos hen some spe sceur ina tabefview ofa database database are mainly used for maintaining integrity i» ‘Togers are also used for enforcing business rule, auiting chaneee "the datahase and replicating data are diferent types of triggers Sy 2-96A (CSAT-Sem-5) Relational Data Mode! 1 1 Data Manipulation Language (DML) triggers: 2 DML triggers are executed when a DMLenera UPDATE OR DELETE is firedon Table ce 1b DML triggers are of two types 2 APTER triggers 1. APTER tigger ae executed ater the DML sta 7000 select person_name street, «ity fom Employee as E, Works as W whore person name = W.person name sn W.company.names'ABC Bank’ and W.salary7000 Select person_name from Works. whore salary > all, (sce slary fom Works where company_name=X¥2) selet perv. nae from Works where slarytstect maxtsalary fom Works there company. names'X¥2) Update Werks setalaryoslary'LO7 ‘where company. namesABC Bank? Delete fro Works = ___ ancomaeen st pamewABC Bani? ——— “ge en zane (nea, Werks ¥, Comp ac erent dey By name> campy ane saw. Gf soni embeded $0 0d dani SA in da, * oes dard defines enbuddiag of Sq Pa i a Oe Fagen which SQL queries remedied ash Alene the SQL structres pert nthe bl est os a ce ‘Progr to access and update data stored ina database ene ie cee! Te avqartibnmsbeananapeneree Soe eieeane enenee «Taegu een ee on eae eae res 1 a ht oe eee spinal yng to constr wt Pre engender Tetras norent ane oe Cessna aden ec etme the prepared statement use the com? oa 4 SQL defines standards for embedding Sy language, such as C, asin the follow ad eee DBA CSITSem5) char*slprog="opdete account set balance = balange» ‘where arcount-number = 7 [EXEC SQL prepare dyapog fom :ealprog char accout|10)="A-101° EXEC SQL execute dynprog using account S555 Dene procedarein PUBCL th tana disadvantages 1 By ‘Answer 1 PLSQLisa block structured language tht enables developer, the power of SQL with procedural statements — 2 Ased procedure in PLSQL is nothing bt a eres of delaratin Siatements which can be stored inthe databare eataagee et 3. Aprocedure ean be thought of as function or a method ‘They canbe invoked through i onda, PHP te 4 ger, other procedures, ppt, 5 All he statements ofa block ae passed to Oracle engine ll at as ‘which increases processing speed and decreases the traf Advantages of procedures in PLSQL: 1 They result in performance improvement of the application procedure is being called frequentiy in an applicatinn in asi onnecton then the compiled version ofthe procedure i delivered 2. Theyreducethe traffic tween the database and the applications the lengthy statements are already fed nt the database and aed: be sent again and ain via the application, ‘They add to cide reusability, similar to how funetions and mets work nother languages suchas C/C++ and Java, Disadvantages of procedures in PUSQL: 1 Stored procedures can eause a lat of memory usage. The dst ‘dminstrator should decide an upper bound a to how many ate roceures re feasible fora particular application 2 MySQL. does not provide the functionality of debugging the ste procedures, VERY IMPORTANT QUESTIONS Following questions are very important. These questions ‘may be aed in your SESSIONALS as well us| UNIVERSITY EXAMINATION, ou Sytem 2a Managemen See _—_____*AAarreeo) — traints and its types, jain constraints and its types ani oy Rue "mate the aan operations in aia pr a8 Tera 2 relational tuple relational ealeulus and dom qs. Explain wn! caleulus- asx Refer @. 29, function in SQL 6. Explain agerecate - fox Refer Q. 222 46. Define join. Explain dierent types fin wither dar Refer Q.225. i rigs ith (qt. What is trigger 7 Explain diferent eres of * example. ng Refer Q.229. Lindt QS, Explain embedded SQL and dynamic SA as, Rafer Q. 24 vit sorts in yuP BY due Met Oo et em etreen WHERE and TANG ase Beer 225 operation suppor 410, What are the relational aleebrt 7 SQL? Write the Aang, Refer Q. 218 sds? of $a-comm 11, What are the different 9Pe ng, Refer Q. 2.14 e990

You might also like