D Atab Ase Man Age Ment Syste Ms - Mrcet

Transcription

DATABASE MANAGEMENT SYSTEMS[Subject Code: R17A0509]LABORATORY MANUALB.TECH (R-17 Regulation)(II YEAR – II SEM)(2018-19)DEPARTMENT OFCOMPUTER SCIENCE AND ENGINEERINGMALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY(Autonomous Institution – UGC, Govt. of India)Recognized under 2(f) and 12 (B) of UGC ACT 1956(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified)Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERINGVision To acknowledge quality education and instill high patterns of disciplinemaking the students technologically superior and ethically strong whichinvolves the improvement in the quality of life in human race.Mission To achieve and impart holistic technical education using the best ofinfrastructure, outstanding technical and teaching expertise to establishthe students into competent and confident engineers. Evolving the center of excellence through creative and innovativeteaching learning practices for promoting academic achievement toproduce internationally accepted competitive and world classprofessionals.

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)PEO1 – ANALYTICAL SKILLS1. To facilitate the graduates with the ability to visualize, gather information, articulate,analyze, solve complex problems, and make decisions. These are essential toaddress the challenges of complex and computation intensive problems increasingtheir productivity.PEO2 – TECHNICAL SKILLS2. To facilitate the graduates with the technical skills that prepare them for immediateemployment and pursue certification providing a deeper understanding of thetechnology in advanced areas of computer science and related fields, thusencouraging to pursue higher education and research based on their interest.PEO3 – SOFT SKILLS3. To facilitate the graduates with the soft skills that include fulfilling the mission,setting goals, showing self-confidence by communicating effectively, having apositive attitude, get involved in team-work, being a leader, managing their careerand their life.PEO4 – PROFESSIONAL ETHICSTo facilitate the graduates with the knowledge of professional and ethical responsibilities bypaying attention to grooming, being conservative with style, following dress codes, safetycodes,and adapting themselves to technological advancements.

PROGRAM SPECIFIC OUTCOMES (PSOs)After the completion of the course, B. Tech Computer Science and Engineering, thegraduates will have the following Program Specific Outcomes:1. Fundamentals and critical knowledge of the Computer System:- Able to Understandthe working principles of the computer System and its components , Apply theknowledge to build, asses, and analyze the software and hardware aspects of it .2. The comprehensive and Applicative knowledge of Software Development:Comprehensive skills of Programming Languages, Software process models,methodologies, and able to plan, develop, test, analyze, and manage the softwareand hardware intensive systems in heterogeneous platforms individually or workingin teams.3. Applications of Computing Domain & Research: Able to use the professional,managerial, interdisciplinary skill set, and domain specific tools in developmentprocesses, identify the research gaps, and provide innovative solutions to them.

PROGRAM OUTCOMES (POs)Engineering Graduates will be able to:1. Engineering knowledge: Apply the knowledge of mathematics, science,engineering fundamentals, and an engineering specialization to the solution ofcomplex engineering problems.Problem analysis: Identify, formulate, review research literature, and analyzecomplex engineering problems reaching substantiated conclusions using firstprinciples of mathematics, natural sciences, and engineering sciences.3. Design / development of solutions: Design solutions for complex engineeringproblems and design system components or processes that meet the specifiedneeds with appropriate consideration for the public health and safety, and thecultural, societal, and environmental considerations.4. Conduct investigations of complex problems: Use research-based knowledge andresearch methods including design of experiments, analysis and interpretation ofdata, and synthesis of the information to provide valid conclusions.5. Modern tool usage: Create, select, and apply appropriate techniques, resources,and modern engineering and IT tools including prediction and modeling tocomplex engineering activities with an understanding of the limitations.6. The engineer and society: Apply reasoning informed by the contextual knowledgeto assess societal, health, safety, legal and cultural issues and the consequentresponsibilities relevant to the professional engineering practice.7. Environment and sustainability: Understand the impact of the professionalengineering solutions in societal and environmental contexts, and demonstratethe knowledge of, and need for sustainable development.8. Ethics: Apply ethical principles and commit to professional ethics andresponsibilities and norms of the engineering practice.9. Individual and team work: Function effectively as an individual, and as a memberor leader 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 tocomprehend and write effective reports and design documentation, makeeffective presentations, and give and receive clear instructions.11. Project management and finance: Demonstrate knowledge and understanding ofthe engineering and management principles and apply these to one’s own work,as a member and leader in a team, to manage projects and in multi disciplinaryenvironments.12. Life- long learning: Recognize the need for, and have the preparation and abilitytoengage in independent and life-long learning in the broadest context oftechnological change.2.

MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGYMaisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING1. LAB OBJECTIVE1. Introduce ER data model, database design and normalization2. Learn SQL basics for data definition and data manipulation2. LAB OUTCOME1. Design database schema for a given application and applynormalization.2. Acquire skills in using SQL Commands for data Definition and datamanipulation.3. Develop solutions for database applications using procedures,cursorsand triggers.3. INTRODUCTION ABOUT LABThere are 65 systems (Acer) installed in this Lab. Their configurations are as follows: Hardware / Software’s installed: Intel CORE i3-3240 CPU@3.40GHZ RAM:4GB /C, C Compiler Systems are provided for students in the 1:1 ratio. Systems are assigned numbers and same system is allotted for students when they do thelab. All systems are configured in DUAL BOOT mode i.e., Students can boot from WindowsXP or Linux as per their lab requirement. This is very useful for students because they arefamiliar with different Operating Systems so that they can execute their programs indifferent programming environments. Each student has a separate login for database access MySQL client version is installed inall systems. On the server, account for each student has been created. This is very usefulbecause students can save their work (scenarios’, PL / SQL programs, data relatedprojects, etc) in their own accounts. Each student work is safe and secure from otherstudents.4.Guidelines to studentsA. STANDARD OPERATING PROCEDUREa) Explanation on today’s experiment by the concerned faculty using PPT covering thefollowing aspects:1) Name of the experiment2) Aim

3) Software/Hardware requirements4) Commands with suitable Options5) Creating Database1) Altering database2) Querying3) Dropping databaseb) Writing of DDL and DML commands by the studentsc) Querying and executing of the SQL queriesWriting of the experiment in the Observation BookThe students will write the today’s experiment in the Observation book as per thefollowing format:a) Name of the experimentb) Aimc) Software/Hardware requiredd) Commands with suitable Optionse) SQL Queriesf) Creating Databasea. Altering databaseb. Queryingc. Dropping databaseg) Results for different Queriesh) Viva-Voce Questions and Answersi) Errors observed (if any) during compilation/executionj) Signature of the FacultyB. Guide Lines to Students in LabDisciplinary to be maintained by the students in the Lab Students are required to carry their lab observation book and record book withcompleted experiments while entering the lab.Students must use the equipment with care. Any damage is caused student ispunishableStudents are not allowed to use their cell phones/pen drives/ CDs in labs.Students need to be maintain proper dress code along with ID CardStudents are supposed to occupy the computers allotted to them and are not supposedto talk or make noise in the lab.Students, after completion of each experiment they need to be updated in observationnotes and same to be updated in the record.

Lab records need to be submitted after completion of experiment and get it correctedwith the concerned lab faculty.If a student is absent for any lab, they need to be completed the same experiment inthe free time before attending next lab.Steps to perform experiments in the lab by the studentStep1: Students have to write the date, aim, Software & Hardware requirements for thatexperiment in the observation book.Step2: Students have to listen and understand the experiment explained by the faculty andnote down the important points in the observation book.Step3: Students need to write procedure/algorithm in the observation book.Step4: Analyze and Develop/implement the logic of the program by the student in respectiveplatformStep5: after approval of logic of the experiment by the faculty then the experiment has to beexecuted on the system.Step6: After successful execution the results are to be shown to the faculty and noted thesame in the observation book.Step7: Students need to attend the Viva-Voce on that experiment and write the same in theobservation book.Step8: Update the completed experiment in the record and submit to the concerned faculty incharge.Instructions to maintain the record Before start of the first lab they have to buy the record and bring the record to the lab.Regularly (Weekly) update the record after completion of the experiment and get itcorrected with concerned lab in-charge for continuous evaluation.In case the record is lost inform the same day to the faculty in charge and get the newrecord within 2 days the record has to be submitted and get it corrected by the faculty.If record is not submitted in time or record is not written properly, the evaluationmarks (5M) will be deducted.Awarding the marks for day to day evaluationTotal marks for day to day evaluation is 15 Marks as per Autonomous (JNTUH).These 15 Marks are distributed as:Record5 MarksExp setup/program writtenResult and Viva-Voce5 Marks5 MarksAllocation of Marks for Lab InternalTotal marks for lab internal are 25 Marks as per Autonomous (JNTUH.)

These 25 Marks are distributed as:Average of day to day evaluation marks: 15 MarksLab Mid exam: 10 MarksAllocation of Marks for Lab ExternalTotal marks for lab Internal and External are 75 Marks as per Autonomous / (JNTUH.)These 50 External Lab Marks are distributed as:Program WrittenProgram Execution and ResultViva-VoceRecord20 Marks15 Marks10 Marks5 Marks

MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGYMaisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERINGGENERAL LABORATORY INSTRUCTIONS1. Students are advised to come to the laboratory at least 5 minutes before (to the startingtime), those who come after 5 minutes will not be allowed into the lab.2. Plan your task properly much before to the commencement, come prepared to the labwith the synopsis / program / experiment details.3. Student should enter into the laboratory with:a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,Procedure, Program, Expected Output, etc.,) filled in for the lab session.b. Laboratory Record updated up to the last session experiments and other utensils (if any)needed in the lab.c. Proper Dress code and Identity card.4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer systemallotted to you by the faculty.5. Execute your task in the laboratory, and record the results / output in the lab observationnote book, and get certified by the concerned faculty.6. All the students should be polite and cooperative with the laboratory staff, must maintainthe discipline and decency in the laboratory.7. Computer labs are established with sophisticated and high end branded systems, whichshould be utilized properly.8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during thelab sessions.Misuse of the equipment, misbehaviors with the staff and systems etc., willattract severe punishment.9. Students must take the permission of the faculty in case of any urgency to go out ; ifanybody found loitering outside the lab / class without permission during working hourswill be treated seriously and punished appropriately.10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves thelab after completing the task (experiment) in all aspects. He/she must ensure the system /seat is kept properly.Head of the DepartmentPrincipal

INDEXS. NoTopicPage no1Introduction12ER Diagrams for Banking System Using Software Tool73MYSQL INSTALLATION164DDL commands245DML COMMANDS296KEY Constraints347Aggregate Functions, Mathematical Functions378Nested Queries & Correlated Queries459Views5010JOINS5311Triggers5712Stored Procedures- DCL COMMANDS - Revoke, Grant.6113PL/SQL6414DCL- Grant and Revoke.6815Case Studies70

INTRODUCTIONData Base Management SystemThis model is like a hierarchical tree structure, used to construct a hierarchy of records inthe form of nodes and branches. The data elements present in the structure have Parent-Childrelationship. Closely related information in the parent-child structure is stored together as a logicalunit. A parent unit may have many child units, but a child is restricted to have only one parent.The drawbacks of this model are:The hierarchical structure is not flexible to represent all the relationship proportions,which occur in the real world.It cannot demonstrate the overall data model for the enterprise because of the nonavailability of actual data at the time of designing the data model.It cannot represent the Many-to-Many relationship.Network ModelIt supports the One-To-One and One-To-Many types only. The basic objects in this model areData Items, Data Aggregates, Records and Sets.It is an improvement on the Hierarchical Model. Here multiple parent-child relationships areused. Rapid and easy access to data is possible in this model due to multiple access paths to thedata elements.Relational ModelDoes not maintain physical connection between relationsData is organized in terms of rows and columns in a tableThe position of a row and/or column in a table is of no importanceThe intersection of a row and column must give a single valueFeatures of an RDBMSThe ability to create multiple relations and enter data into themAn attractive query languageRetrieval of information stored in more than one tableAn RDBMS product has to satisfy at least Seven of the 12 rules of Codd to be acceptedas a full- fledged RDBMS.1

Relational Database Management SystemRDBMS is acronym for Relation Database Management System. Dr. E. F. Codd firstintroduced the Relational Database Model in 1970. The Relational model allows data to berepresented in a simple row- column. 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 model there is relation between their data elements. Data is stored in tables. Tableshave columns, rows and names. Tables can be related to each other if each has a column with acommon type of information. The most famous RDBMS packages are Oracle, Sybase andInformix.Simple example of Relational model is as follows :Student Details TableRoll noSnameS raStudent Marksheet TableRollnoSub1Sub2Sub3178899425465773237846Here, both tables are based on students details. Common field in both tables is Rollno. So wecan say both tables are related with each other through Rollno column.Degree of RelationshipOne to One (1:1)One to Many or Many to One (1:M / M: 1)Many to Many (M: M)The Degree of Relationship indicates the link between two entities for a specified occurrence ofeach.2

One to One Relationship: (1:1)11Student Has Roll No.One student has only one Rollno. For one occurrence of the first entity, there can be, at the mostone related occurrence of the second entity, and vice-versa.One to Many or Many to One Relationship: (1:M/M: 1)1MCourse Contains StudentsAs per the Institutions Norm, One student can enroll in one course at a time however, in onecourse, there can be more than one student.For one occurrence of the first entity there can exist many related occurrences of the secondentity and for every occurrence of the second entity there exists only one associated occurrenceof the first.Many to Many Relationship: (M:M)MMStudents Appears TestsThe major disadvantage of the relational model is that a clear-cut interface cannot be determined.Reusability of a structure is not possible. The Relational Database now accepted model on whichmajor database system are built.Oracle has introduced added functionality to this by incorporated object-oriented capabilities.Now it is known is as Object Relational Database Management System (ORDBMS). Objectoriented concept is added in Oracle8.Some basic rules have to be followed for a DBMS to be relational. They are known as Codd’srules, designed in such a way that when the database is ready for use it encapsulates therelational theory to its full potential. These twelve rules are as follows.3

E. F. Codd Rules1. The Information RuleAll information must be store in table as data values.2. The Rule of Guaranteed AccessEvery item in a table must be logically addressable with the help of a table name.3. The Systematic Treatment of Null ValuesThe RDBMS must be taken care of null valuesto represent missing orinapplicable information.4. The Database Description RuleA description of database is maintained using the samelogical structures withwhich data was defined by the RDBMS.5. Comprehensive Data Sub LanguageAccording to the rule the system must support data definition, view definition, datamanipulation, integrity constraints, authorization and transaction managementoperations.6. The View Updating RuleAll views that are theoretically updatable are also updatable by the system.7. The Insert and Update RuleThis rule indicates that all the data manipulation commands must be operationalon sets of rows having a relation rather than on a single row.8. The Physical Independence RuleApplication programs must remain unimpaired when any changes are made in storagerepresentation or access methods.9. The Logical Data Independence RuleThe changes that are made should not affect the user’s ability to work with thedata.The change can be splitting table into many more tables.10. The Integrity Independence RuleThe integrity constraints should store in the system catalog or in the database.11. The Distribution RuleThe system must be access or manipulate the data that is distributed in other systems.4

12. The Non-subversion RuleIf a RDBMS supports a lower level language then it should not bypass anyintegrity constraints defined in the higher level.Object Relational Database Management SystemOracle8 and later versions are supported object-oriented concepts. A structure once created can bereused is the fundamental of the OOP’s concept. So we can say Oracle8 is supported ObjectRelational model, Object - oriented model both. Oracle products are based on a concept known asa client-server technology. This concept involves segregating the processing of an applicationbetween two systems. One performs all activities related to the database (server) and the otherperforms activities that help the user to interact with the application (client). A client or front-enddatabase application also interacts with the database by requesting and receiving information fromdatabase server. It acts as an interface between the user and the database.The database server or back end is used to manage the database tables and also respond to clientrequests.Introduction to ORACLEORACLE is a powerful RDBMS product that provides efficient and effective solutions for majordatabase features. This includes:Large databases and space management controlMany concurrent database usersHigh transaction processing performanceHigh availabilityControlled availabilityIndustry accepted standardsManageable securityDatabase enforced integrityClient/Server environmentDistributed database systemsPortability5

CompatibilityConnectivityAn ORACLE database system can easily take advantage of distributed processing by using itsClient/ Server architecture. In this architecture, the database system is divided into two parts:A front-end or a client portionThe client executes the database application that accesses database information and interacts withthe user.A back-end or a server portionThe server executes the ORACLE software and handles the functions required for concurrent,shared data access to ORACLE database.6

ILLUSTRATION: ROADWAY TRAVELS“Roadway Travels” is in business since 1977 with several buses connecting different places inIndia. Its main office is located in Hyderabad.The company wants to computerize its operations in the following ns :Reservations are directly handeled by booking office.reservations can be made 60 daysin advance in either cash or credit. In case the ticket is not available,a wait listed ticket is issuedto the customer. This ticket is confirmed against the cancellation.Cancellation and modification:Cancellations are also directly handed at the booking office. Cancellation chargeswill be charged.Wait listed tickets that do not get confirmed are fully refunded.7

WEEK-1AIM: Analyze the problem and come with the entities in it. Identify what Data has to bepersisted in the databases.The Following are the entities:1 .Bus2. Reservation3. Ticket4. Passenger5. CancellationThe attributes in the Entities:Bus:( Entity)DestinationSourceCouch TypeBus NoBusReservation (Entity)Bus NoContact NoNo-of-SeatsJourney dateAddressPNR NOReservationTicket :(Entity)Dep- TimeSourceAgeSexJourney dateDestinationTicket NoBus NoTicket8

Passenger:Contact NOAgeSexPNR NONameTicket NoPassengerCancellation (Entity)Journey dateSeat NoContact NoPNR NOCancellation9

Concept design with E-R Model:10

CASE STUDY 1:Consider the following information about a university database: Professors have an SSN, a name, an age, a rank, and a research specialty. Projects have a project number, a sponsor name (e.g., NSF), a starting date, anending date, and a budget. Graduate students have an SSN, a name, an age, and a degree program (e.g.,M.S. or Ph.D.). Each project is managed by one professor (known as the project's principalinvestigator). Each project is worked on by one or more professors (known as the project's coinvestigators). Professors can manage and/or work on multiple projects. Each project is worked on by one or more graduate students (known as theproject's research assistants). When graduate students work on a project, a professor must supervise their workon the project. Graduate students can work on multiple projects, in which casethey will have a (potentially di erent) supervisor for each one. Departments have a department number, a department name, and a main office. Departments have a professor (known as the chairman) who runs the department. Professors work in one or more departments, and for each department that theywork in, a time percentage is associated with their job. Graduate students have one major department in which they are working on theirdegree. Each graduate student has another, more senior graduate student (known as astudent advisor) who advises him or her on what courses to take.WORKSHEET

Weekly Evaluation0: Not Done3: Needs improvement1: Incomplete2: Late complete4: CompleteSignature of the instructor5: Well DoneDate:12

What is SQL and SQL*PlusOracle was the first company to release a product that used the English-based Structured QueryLanguage 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. SQL is astandard language common to all relational databases. SQL is database language used for storingand retrieving data from the database. Most Relational Database Management Systems provideextension to SQL to make it easier for application developer. A table is a primary object ofdatabase used to store data. It stores data in form of rows and columns.SQL*Plus is an Oracle tool (specific program ) which accepts SQL commands and PL/SQL blocksand executes them. SQL *Plus enables manipulations of SQL commands and PL/SQL blocks. Italso performs additional tasks such as calculations, store and print query results in the form ofreports, list column definitions of any table, access and copy data between SQL databases andsend messages to and accept responses from the user. SQL *Plus is a character based interactivetool, that runs in a GUI environment. It is loaded on the client machine.To communicate with Oracle, SQL supports the following categories of commands:1. Data Definition LanguageCreate, Alter, Drop and Truncate2. Data Manipulation LanguageInsert, Update, Delete and Select3. Transaction Control LanguageCommit, Rollback and Save point4. Data Control LanguageGrant and Revoke13

Before we take a look on above-mentioned commands we will see the data types available inOracle.Oracle Internal Data typesWhen you create a table in Oracle, a few items should be important, not only do you have to giveeach 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 what type ofinformation thattable will hold to the database. For example, the column Empno holds numericinformation. An Oracle database can hold many different types of data.Data type DescriptionChar(Size) Stores fixed-length character data to store alphanumeric values, with amaximum size of 2000 bytes. Default and minimum size is 1 byte.Varchar2(Size) Stores variable-length character data to store alphanumeric values, withmaximum size of 4000 bytes.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 of bytesrequired storing each character with an upper limit of 2000 bytes. Default and minimum size is 1character or 1 byte, depending on the character set.Nvarchar2(Size) Stores variable-length character string having maximum length sizecharacters or bytes, depending on the choice of national character set. Maximum size isdetermined by the number of bytes required to store each character, with an upper limitof 4000 bytes.Long Stores variable-length character data up to 2GB(Gigabytes). Its lenth would berestricted based on memory space available in the computer.Number [p,s] Number having precision p and scale s. The precision p indicates totalnumber of digit varies from 1 to 38. The scale s indicates number of digit in fraction partvaries from -84 to 127.Date Stores dates from January 1, 4712 B.C. to December 31, 4712 A.D. Oraclepredefine format of Date data type is DD-MON-YYYY.14

Raw (Size) Stores binary data of length size. Maximum size is 2000 bytes. One musthave to specify size with RAW type data, because by default it does not specify any size.Long Raw Store binary data of variable length up to 2GB(Gigabytes).LOBS - LARGE OBJECTSLOB is use to store unstructured information such as sound and video clips, pictures upto 4 GBsize.CLOB A Character Large Object containing fixed-width multi-byte characters.Varyingwidth character sets are not supported. Maximum size is 4GB.NCLOB A National Character Large Object containing fixed-width multi-bytecharacters.Varying-width character sets are not supported. Maximum size is 4GB. Storesnational character set data.BLOB To store a Binary Large Object such a graphics, video clips and sound files.Maximum size is 4GB.BFILE Contains a locator to a large Binary File stored outside the database. Enablesbyte stream I/O access to external LOBs residing on the database server. Maximumsize is 4GB.Apart from oracle internal data types, user can create their own data type, which isused in database and other database object. We will discuss it in the later part.The following are tabular representation of the above entities and relationshipsBUS:COLUMN NAMEDATA TYPE CONSTRAINTBus 2(20)Couch Typevarchar2(20)Primary Key15

Reservation:COLUMN NAMEDATA TYPECONSTRAINTPNRNonumber(9)Primary KeyJourney ntact NoNumber(9)BusNovarchar2(10)Seat noNumberShould be equal to 10numbers and not allowother than numericForeign keyTicket:COLUMN NAMEDATA TYPECONSTRAINTTicket Nonumber(9)Primary KeyJourney 10)varchar2(10)varchar2(10)varchar2(10)Bus NoNumber2(10)16

Passenger:COLUMN NAMEDATA TYPECONSTRAINTPNR NoNumber(9)P

d atab ase man age ment syste ms [subject code: r17a0509 ] laboratory manual b.tech (r -17 regulation) (ii year t ii sem) (2018- 19 ) department of