DATABASE MANAGEMENT SYSTEMS - MRCET

Transcription

DATABASEMANAGEMENTSYSTEMSLABORATORY MANUAL & RECORDB.TECH(IIYEAR–IISEM)(2021-22)DEPARTMENT OFCOMPUTERSCIENCEANDENGINEERINGMALLAREDDY COLLEGE OF ENGINEERING ia)Recognizedunder2(f)and12(B) of pet),Secunderabad–500100,TelanganaState,India

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERINGVision To acknowledge quality education and instill high patterns of discipline making thestudent’s technologically superior and ethically strong which involves theimprovement in the quality of life inhuman race.Mission To achieve and impart holistic technical education using the best of infrastructure,outstanding technical and teaching expertise to establish the students to competent andconfident engineers. Evolving the center of excellence through creative and innovative teaching learningpractices for promoting academic achievement to produce international competitive andworld class professionals.

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)PEO1–ANALYTICALSKILLS1. To facilitate the graduates with the ability to visualize, gather information, articulate,analyze, solve complex problems, and make decisions. These are essential to addressthe challenges of complex and computation intensive problems increasing theirproductivity.PEO2–TECHNICALSKILLS2. To facilitate the graduates with the technical skills that prepare them forimmediate employment and pursue certification providing adeeper 3–SOFTSKILLS3. To facilitate the graduates with the soft skills that include fulfilling the mission,setting goals, showing self confidence by communicating effectively, havingapositiveattitude, get involved in team-work, being a leader, managing their careerandtheirlife.PEO4–PROFESSIONALETHICS4. onalandethicalresponsibilitiesbypaying attention to grooming, being conservative with style, following dress codes,safetycodes, andadaptingthemselvestotechnologicaladvancements.

PROGRAM SPECIFIC OUTCOMES (PSOs)Engineering Graduates will be able to:1. Engineering knowledge: Apply the knowledge of mathematics, science, engineeringfundamentals, and an engineering specialization to the solution ofComplex engineering problems.2. Problem analysis: Identify, formulate, review research literature, and Analyzecomplex engineering problems reaching substantiated conclusions using first Principles ofmathematics, natural sciences, and engineering sciences.3. Design / development of solutions: Design solutions for complex engineeringproblems and design system components or processes that meet the Specified needs withappropriate consideration for the public health and safety, and the cultural, societal, andenvironmental considerations.4. Conduct investigations of complex problems: Use research-based knowledge andresearch methods including design of experiments, analysis and interpretation of Data andsynthesis of the information to provide valid conclusions.5. Modern tool usage: Create, select, and apply appropriate techniques, resources, andmodern engineering and IT tools including prediction and modeling to complexengineering activities with an understanding of the limitations.6. The engineer and society: Apply reasoning informed by the contextual knowledge toassess societal, health, safety, legal and cultural issues and the consequent responsibilitiesrelevant to the professional engineering practice.7. Environment and sustainability: Understand the impact of the professionalengineering solutions in societal and environmental contexts, and demonstrate theknowledge of, and need for sustainable development.8. Ethics: Apply ethical principles and commit to professional ethics and responsibilitiesand norms of the engineering practice.9. Individual and team work: Function effectively as an individual, and as a member orleader in diverse teams, and in multidisciplinary settings.10. Communication: Communicate effectively on complex engineering activities Withthe engineering community and with society at large, such as, being able to comprehendand write effective reports and design documentation, make effective presentations, andgive and receive clear instructions.11. Project management and finance: Demonstrate knowledge and understanding of thengineering and management principles and apply these to one’s own work, as a memberand leader in a team, to manage projects and in multi disciplinary Environments.

12. Life- long learning: Recognize the need for, and have the preparation and ability toengage in independent and life-long learning in the broadest context of technologicalchange.

INDEXS.No12345TopicE-R Model: Analyze the problem with the entitieswhich identify datapersisted in the database which contains entities,attributes.Concept design with E-R Model: Applycardinalities for each relationship, identify strongentities and weak entities for relationshipslike generalization, aggregation, specialization.Relation Model: Represent attributes as columns intables anddifferent types of attributes like Composite, Multivalued, and Derived.NormalizationInstallation of MySql and MONGO DB.Pageno817192326&346Practicing DML commandsSELECT, INSERT, UPDATE, DELETE.397QueryingQueries using ANY, ALL, IN, INTERSECT, UNION528910111213QueryingUsing aggregate functions COUNT, SUMusing GROUPBY andHAVING.QueryingUsing aggregate functions AVERAGEusing GROUPBY andHAVINGTRIGGERProceduresCreation, Execution and Modification of storedProcedureStored Procedures&Pl/SQLCreation, Execution and Modification of storedProcedureDCL CommandsCASESTUDY169697782828792DateSign

INTRODUCTIONHierarchicalModelThis model is like a hierarchical tree structure, used to construct a hierarchy of recordsinthe form of nodes and branches. The data elements present in the structure have ParentChildrelationship. Closely related information in the parent-child structure is stored together as childisrestrictedtohaveonlyoneparent.The draw back softhismodelare:The hierarchical structure is not flexible to represent all the relationshipproportions,whichoccur intherealworld.Itcannot demonstrate the overall data modelfor the enterprise because of the nonavailabilityof It supports the One-To-One and One-To-Many types only. The basic objects in this modelareDataItems,DataAggregates,RecordsandSets.It is an improvement on the Hierarchical Model. Here multiple parent-child relationshipsareused. Rapid and easy access to data is possible in this model due to multiple access paths tothedataelements.RelationalModelDoes not maintain physical connection umnsinatableThepositionofarowand/or wandcolumnmustgiveasinglevalueFeaturesofanRDBMSThe ability to create multiple relations and enter data tisfyatleastSevenof the12rulesofCoddtobeacceptedasafullfledgedRDBMS.1

introducedtheRelationalDatabaseModelin 1970.TheRelationalmodelallows data toberepresented in a simple rowcolumn. Each data field is considered as a column and each record isconsidered as a row.Relational Database is more or less similar to Database Management S ystem.In relational modelthere is relation between their data elements. Data is stored in tables. Tableshave columns, rowsand names.Tablescan be related to eachotherifeach hasacolumn kagesareOracle,SybaseandInformix.Simple TableRoll noSnameS greeofRelationshipOnetoOne(1:1)One to Many or Many to One (1:M / feach.2

One to One Relationship:(1:1)11StudentHasRollNo.One studenthasonlyone Rollno. Forone relatedoccurrenceof thesecondentity,andvice-versa.One to Many or Many to One Relationship: (1:M/M:1)1MCourseContainsStudentsAs per the Institutions Norm, One student can enroll in one course at a time however, inonecourse,therecanbemorethanonestudent.For one occurrence of the first entity there can exist many related occurrences of thesecondentity and for every occurrence of the second entity there exists only one hip:(M:M)MMStudentsAppearsTestsThe major disadvantage of the relational model is that a clear-cut interface cannot bedetermined.Reusability of a structure is not possible. The Relational Database now acceptedmodel on whichmajordatabasesystemarebuilt.Oraclehas introducedaddedfunctionalitytothis by incorporatedobject-orientedcapabilities.Now it isknown is as Object Relational Database Management System (ORDBMS). ObjectorientedconceptisaddedinOracle8.Some basic rules have to be followed for a DBMS to be relational. They are known asCodd’srules,designedin such away thatwhen the databaseis ready for useit Thesetwelverulesareasfollows.3

E.F.Codd Rules1. TheInformationRuleAllinformationmustbe store intableasdata values.2. TheRule ofGuaranteed iththehelpofatablename.3. kencare ofnull 4. tawasdefinedbytheRDBMS.5. ComprehensiveDataSubLanguageAccording to the rule the system must support data definition, view uthorizationandtransactionmanagementoperations.6. TheViewUpdatingRuleAll viewsthat aretheoreticallyupdatablearealsoupdatable bythe system.7. TheInsertandUpdateRuleThis rule indicates that all the data manipulation commands must beoperationalonsetsof rowshavingarelationratherthanonasinglerow.8. esentationor accessmethods.9. TheLogicalDataIndependenceRuleThe changes that are made should not affect the user’s ability to work retables.10. sshouldstoreinthesystemcatalogorinthedatabase.11. tethedatathatisdistributedinothersystems.4

12. definedinthehigherlevel.ObjectRelationalDatabase ManagementSystemOracle8 and later versions are supported object-oriented concepts. A structure once created canbereused is the fundamental of the OOP’s concept. So we can say Oracle8 is asaprocessingofanapplicationbetween two systems. One performs all activities related to the database (server) andthe otherperforms activities that help the user to interact with the application (client). A client orfront-enddatabase application also interacts with the database by requesting and receivinginformation er andthedatabase.The database server or back end is used to manage the database tables and also respond toclientrequests.IntroductiontoORACLEORACLE is a powerful RDBMS product that provides efficient and effective solutions formajordatabasefeatures.Thisincludes:Large databases and space rolledavailabilityIndustry acceptedstandardsManageablesecurityDatabase ed databasesystemsPortability5

databasesystemisdividedintotwoparts:Afront-end oraclient portionThe clientexecutesthedatabase e.6

rvations:Reservationsare ade60daysinadvance in either cash or credit. In case the ticket is not available,a wait listed ticket thecancellation.Cancellationand modification:Cancellations are also directly handed at the booking office. thatdonotgetconfirmedarefullyrefunded.7

WEEK-1AIM:Analyze the problemandcome withthe databases.The Followingare theentities:1.Bus2. Reservation3. Ticket4. Passenger5. urneydateDestinationTicketNoBusNoTicket8

NOCancellation9

ConceptdesignwithE-R Model:10

CASESTUDY1: abase: specialty. astartingdate,anendingdate,and abudget. ogram(e.g., M.S.orPh.D.). ct'sprincipalinvestigator). Eachproject sco-investigators). Professors canmanage and/orworkonmultipleprojects. Each project is worked on by one or more graduate students (known as theproject'sresearchassistants). upervisetheir workon the project. asetheywillhavea(potentiallydi erent)supervisorforeachone. ndamainoffice. nsthedepartment. iththeirjob. reworkingontheirdegree. hatcoursestotake.

What is SQL and SQL*PlusOracle was the first company to release a product that used the English-based StructuredQueryLanguage or SQL. This language allows end users to manipulate information of table(primarydatabase object). To use SQL you need not to require any programming experience. SQLis astandard language common to all relational databases. SQL is database language used forstoringand retrieving data from the database. Most Relational Database Management Systemsprovideextension to SQL to make it easier for application developer. A table is a primary ofrowsandcolumns.SQL*Plusisan Oracletool (specificprogram) whichacceptsSQLcommandsandPL/SQLblocksandexecutes them. SQL *Plus enables manipulations of SQL commands and PL/SQL blocks. Italsoperforms additional tasks such as calculations, store and print query results in the form oreports,list enSQLdatabasesandsendmessages to and accept responses from the user. SQL *Plus is a character sloadedontheclientmachine.Tocommunicate withOracle,SQL supportsthefollowingcategoriesofcommands:1. DataDefinitionLanguageCreate, Alter,DropandTruncate2. ect3. TransactionControlLanguageCommit, RollbackandSavepoint4. DataControlLanguageGrantandRevoke12

Before we take a look on above-mentioned commands we will see the data types availableinOracle.OracleInternalDatatypesWhen you create a table in Oracle, a few items should be important, not only do you have togiveeach table a name(e.g. employee, customer), you must also list all the columns or fields(e.g.First name, Mname, Last name) associated with the table. You also have to specify whattype ofinformation thattable will hold to the database. For example, the column Empno ydifferenttypesofdata.Datatype toresvariable-lengthcharacterdatatostore alphanumericvalues,withmaximumsizeof 4000bytes.char(Size) Stores fixed-length character data of length size characters or bytes,dependingon the choice of national character set. Maximum size if determined by the number ofbytesrequired storing each character with an upper limit of 2000 bytes. Default and minimum sizeis 1characteror1byte,dependingonthecharacter set.Nvarchar2(Size) ngthsizecharacters or bytes, depending on thechoice of national character set. Maximum s lenthwouldberestrictedbasedonmemoryspace availableinthecomputer.Number [p,s] Number having precision p and scale s. The precision p indicatestotalnumber of digit varies from 1 to 38. The scale s indicates number of digit infraction partvariesfrom-84to127.DateStores dates edefineformatofDatedatatypeisDD-MON-YYYY.13

Raw (Size) Stores binary data of length size. Maximum size is 2000 bytes. Onemusthave to specify size with RAW type data, because by default it does not specify anysize.LongRawStorebinarydataof variablelengthup to2GB(Gigabytes).LOBS-LARGEOBJECTSLOB is use to store unstructured information such as sound and video clips, pictures upto 4GBsize.CLOB A Character Large Object containing fixed-width otsupported.Maximumsizeis4GB.NCLOB A National Character Large Object containing fixed-width ntainsalocatortoalarge er ionvarchar2(20)CouchTypevarchar2(20)PrimaryKey14

PECONSTRAINTTicket rchar2(10)varchar2(10)Number2(10)15

ontact tallowotherthannumeric16

WEEK 2Concept design with E-R Model and apply cardinalities for each relationship. Identifystrong entities and weak entities for relationships like generalization, aggregation,specialization.Objectives:Student will able to learn data structures in terms of entity types, relationship types and attributes orclasses, associations and attributes.Outcomes:Student gains the ability to describe the data requirements for a new information system in a direct andeasy to understand graphical notation.E R diagram:Bus NoSourceBUSDestinationDeparture TimeDate of journeyReservationSexTicket noTicket SourceDeparture timeAge17

VIVA QUESTIONS1.2.3.4.5.Draw an E-R Diagram For an ATM System.Draw an E-R Diagram For school mgmt system.Draw an E-R Diagram For Roadways Travels Systems.Draw an E-R Diagram For Bank Mgmt System.Explain many to many and many to one relationship.18

WEEK 3AIMRelation Model represents attributes as columns in tables and different types ofattributes like composite, Multi-valued and Derived.Objectives:Student will able to learn the structural components of the relational data model.Student will able to learn to map ER models into relational models.Outcomes:Student gains the ability To describe the Model Structure. To define Properties of Relations. To define Domains. To implement Notation to Describe the Relational Schema To Represent an ER Model as a Relational Model.Example: The passenger tables look as below. This is an example. You can add more attributes basedon your E-R model. This is not a normalized table. PassengerpassengerBusPassengerTickets#bus nosourcedestination#ppno#ppnoname#ticket noage#jrny datesexaddressphone-no19

Tickets#tickets nono of tktsFrom placeT0 place#Bus no#jrny dateNameAgeSexAddressPassportIDNote: The student is required to submit a document by Represent relationships in a tabular fashion tothe lab teacher.2. Concept design with E-R modelRelate the entities appropriate for each relationship. Identify strong entities and week entities (if any).Indicate the type of relationships (total/partial). In this we will design the different E-R diagram fordifferent entities and also the whole “Roadway Travels”.E-R diagram: An entity-relationship(ER) diagram is a specified graphic that illustrates theinterrelationships between entities and database. W e can express the overall logical structure ofdatabase graphically with an E-R diagram.3. Relational Model and NormalizationRepresent all the entities (Strong, Weak) in tabular fashion. Represent relationships in a tabular fashion.There are different ways of representing relationships as tables based on the cardinality. Representattributes as columns in tables or as tables based on the requirement. In this we will represent thedifferent entities, attributes of different keys in a tabular fashion or manner.20

Relational Model:The relational model is a depiction of how each piece of stored information relates to the other storedinformation. It shows how tables are linked, what type of the links are between tables, what keys areused, what information is referenced between tables. It’s an essential part of developing a normalizeddatabase structure to prevent repeat and redundant data storage.Different types of keys: A super key is a set of one or more attributes which; taken collectively, allow us to identifyuniquely an entity in the entity set. A primary key is a candidate key(there may be more than one) chosen by the DB designer toidentify entities in an entity set. A super key may contain extraneous attributes, and we are often interested in the smallest superkey. A super key for which no subset is a super key is called a candidate key. An entity does not posses sufficient attributes to form a primary ket is called a weak entity set.One that does have a primary key is called a strong entity set. A foreign key is a field in a relational table that matches the primary key column of anothertable. The foreign key can be used to cross-reference tables.NormalizationDatabase normalization is a technique for designing relational database tables to minimize duplicationof information and, in so doing, to safeguard the database against certain types of logical or structuralproblems, namely data anomalies. In this we will write the normalization tables that is entities of“Roadway Travels.”Normalization: In relational databases, normalization is a process that eliminates redundancy,organizes data efficiently; Normalization is the process of efficiently organizing data in a database.There are two goals of the normalization process: eliminating redundant data(for example, storing thesame data in more than one table) and ensuring data dependencies make sense(only storing related datain a tablet). Both of these are worthy goals as they reduce the amt of space a database consumes andensure that data is logically stores.The Normal Form: the database community has developed a series of guidelines for ensuring thatdatabases are normalized. These are referred to as normal forms and are numbered from one ( the lowestform to normalization, referred to as first form or INF) through five(fifth normal form of SNF). Inpractical applications, you’ll often see INF, 2NF, and 3NF along with occasional 4NF. Fifth normalform is very rarely seen and won’t be discussed in this article. It’s important to point out that they areguidelines and guidelines only. Occasionally, it becomes necessary to stray from them to meet practicalbusiness requirements. However, when variations take place, it’s extremely important to evaluate anypossible requirements they could have on your system and account for possible inconsistencies. Thatsaid, let’s explore the normal form.21

VIVA QUESTIONS1.2.3.4.5.What is relational model and its importance.Explain the difference between candidate key and primary key.What is a super key.Differentiate among all types of keys with example.Explain the need of foreign key.22

WEEK 4AIMNormalization of tablesObjectives:Student will able to learn to avoid problems that are associated with updating redundant data.Outcomes:Student gains the knowledge to build The database that does not have redundant data.A basic objective of the first normal form defined by Edgar Frank "Ted" Codd in 1970 was to permitdata to be queried and manipulated using a "universal data sub-language" grounded in first-orderlogic.(SQL is an example of such a data sub-language, albeit one that Codd regarded as seriouslyflawed.)The objectives of normalization beyond 1NF (First Normal Form) were stated as follows by Codd:1. To free the collection of relations from undesirable insertion, update and deletiondependencies;2. To reduce the need for restructuring the collection of relations, as new types of data areintroduced, and thus increase the life span of application programs;3. To make the relational model more informative to users;4. To make the collection of relations neutral to the query statistics, where these statisticsare liable to change as time goes by.Querying and manipulating the data within a data structure which is not normalized, such as thefollowing non-1NF representation of customers' credit card transactions, involves more complexity thanis really necessary:CustomerTransactionsJonesTr. IDDateAmount12890 14-Oct-2003 8712904 15-Oct-2003 50Wilkinso nr. IDDateAmount12898 14-Oct-2003 21StevensTr. IDDateAmount12907 15-Oct-2003 1814920 20-Nov-2003 7015003 27-Nov-2003 6023

To each customer corresponds a repeating group of transactions. The automated evaluationof any queryrelating to customers' transactions therefore would broadly involve two stages:1. Unpacking one or more customers' groups of transactions allowing the individualtransactions ina group to be examined, and2. Deriving a query result based on the results of the first stageFor example, in order to find out the monetary sum of all transactions that occurred inOctober 2003 for all customers, the system would have to know that it must first unpackthe Transactions group of each customer, then sum the Amounts of all transactions thusobtained where the Date of the transaction falls in October 2003.One of Codd's important insights was that this structural complexity could always beremoved completely, leading to much greater power and flexibility in the way queriescould be formulated (by users and applications) and evaluated (by the DBMS). Thenormalized equivalent of the structure above would look like this:Customer Tr. IDDateAmountJones12890 14-Oct-2003 87Jones12904 15-Oct-2003 50Wilkins 12898 14-Oct-2003 21Stevens 12907 15-Oct-2003 18Stevens 14920 20-Nov-2003 70Stevens 15003 27-Nov-2003 60Now each row represents an individual credit card transaction, and the DBMS can obtainthe answer of interest, simply by finding all rows with a Date falling in October, andsumming their Amounts. The data structure places all of the values on an equal footing,exposing each to the DBMS directly, so each can potentially participate directly in queries;whereas in the previous situation some values were embedded in lower-level structuresthat had to be handled specially. Accordingly, the normalized designlends itself to generalpurpose qu

Relational Database Management System RDBMS is acronym for Relation Database Management System. Dr. E. F. Codd first introduced the Relational Database Model in 1970. The Relational model allows data to be represented in a simple row- column. Each data field is consi