CSIT_(R22)_3-1_DATABASE MANAGEMENT SYSTEMS_LAB MANUAL
CSIT_(R22)_3-1_DATABASE MANAGEMENT SYSTEMS_LAB MANUAL
INFORMATION TECHNOLOGY
DATABASE MANAGEMENT SYSTEMS
(R22A0584)
LABORATORY MANUAL & RECORD
B.TECH
PREPARED BY
K.SHANTHI
Vision
➢ To acknowledge quality education and instill high patterns of discipline making the
student’s technologically superior and ethically strong which involves the improvement
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 and
confident engineers.
➢ Evolving the center of excellence through creative and innovative teaching learning practices
for promoting academic achievement to produce international competitive and world class
professionals.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
PEO1–ANALYTICALSKILLS
1. To facilitate the graduates with the ability to visualize, gather information, articulate,
analyze, solve complex problems, and make decisions. These are essential to address the
challenges of complex and computation intensive problems increasing the irproductivity.
PEO2–TECHNICALSKILLS
2. To facilitate the graduates with the technical skills that prepare them for
immediate employment and pursue certification providing a deeper
understandingof the technology in advanced areas of computer science and related
fields ,thus encouraging to pursue higher education and research based on their
interest.
PEO3–SOFTSKILLS
3. To facilitate the graduates with the soft skills that include fulfilling the mission, setting
goals, showing self-confidence by communicating effectively, having a positive attitude,
get involved in team-work, being a leader, managing their career and their life.
PEO4–PROFESSIONALETHICS
4. Tofacilitatethegraduateswiththeknowledgeofprofessionalandethicalresponsibilitiesby
paying attention to grooming, being conservative with style, following dress codes,
safety codes, and adapting themselves to technological advancements.
PROGRAM SPECIFIC OUTCOMES (PSOs)
Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of
Complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and Analyze complex
engineering problems reaching substantiated conclusions using first Principles of
mathematics, natural sciences, and engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the Specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of Data 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 to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities With
the engineering community and with society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of th
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 disciplinary Environments.
12. Life- long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
INDEX
S. Page
Topic
No no
E-R Model: Analyze the problem with the entities which identify data 8
1
persisted in the database which contains entities, attributes.
Normalization
4 23
Procedures
11 82
Creation, Execution and Modification of stored Procedure
13 DCL Commands 87
CASESTUDY1 92
DBMS LAB AY-2024-25
INTRODUCTION
HierarchicalModel
This 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-
logicalunit.Aparentunitmayhavemanychildunits,butachildisrestrictedtohaveonlyoneparent.
proportions,whichoccur intherealworld.
Itcannot demonstrate the overall data modelfor the enterprise because of the non-
availabilityof actualdataatthetimeofdesigningthedatamodel.
ItcannotrepresenttheMany-to-Manyrelationship.
NetworkModel
It supports the One-To-One and One-To-Many types only. The basic objects in this model
areDataItems,DataAggregates,RecordsandSets.
RelationalModel
Thepositionofarowand/or columninatableisof
noimportanceTheintersectionofarowandcolumnmustgiveasingleva
lue
FeaturesofanRDBMS
The ability to create multiple relations and enter data into
themAnattractivequerylanguage
Retrievalofinformationstoredinmorethanonetable
AnRDBMSproducthastosatisfyatleastSevenof the12rulesofCoddtobeacceptedasafull-
fledgedRDBMS.
DEPARTMENT--CSE Page 1
DBMS LAB AY-2024-25
RelationalDatabaseManagementSystem
RDBMSisacronymforRelationDatabaseManagementSystem.Dr.E.F.CoddfirstintroducedtheRel
ationalDatabaseModelin 1970.TheRelationalmodelallows data toberepresented 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
acommontypeofinformation.ThemostfamousRDBMSpackagesareOracle,SybaseandInformix.
Simple exampleofRelationalmodelisasfollows:
StudentDetailsTable
Roll_no Sname S_Address
1 Rahul Satelite
2 Sachin Ambawadi
3 Saurav Naranpura
StudentMarksheetTable
Rollno Sub1 Sub2 Sub3
1 78 89 94
2 54 65 77
3 23 78 46
Here, both tables are based on students’ details. Common field in both tables is Rollno.So we can say both tables
are related with each other through Roll no column.
Degree of Relationship
OnetoOne(1:1)
TheDegreeofRelationshipindicatesthelinkbetweentwoentitiesforaspecifiedoccurrenceofeach.
DEPARTMENT--CSE Page 2
DBMS LAB AY-2024-25
StudentHasRollNo.
One studenthasonlyone Rollno. Forone occurrenceofthefirstentity,
therecanbe,atthemostonerelatedoccurrenceof thesecondentity,andvice-versa.
1)1M
For one occurrence of the first entity there can exist many related occurrences of the second entity
and for every occurrence of the second entity there exists only one associated occurrence of the
first.
The 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 which
major database system are built.
Some basic rules have to be followed for a DBMS to be relational. They are known as Codd’s
rules, designed in such a way that when the database is ready for use it encapsulates the relational
theory to its full potential. These twelve rules are as follows.
DEPARTMENT--CSE Page 3
DBMS LAB AY-2024-25
E.F.Codd Rules
1. The Information Rule
All in formation must be store in table as data values.
2. The Rule of Guaranteed Access
Every item in a table must be logically address able with the help of a table name.
According to the rule the system must support data definition, view definition, data
manipulation, integrity constraints, authorization and transaction management
operations.
The changes that are made should not affect the user’s ability to work with the data. The change
can be splitting table into many more tables.
DEPARTMENT--CSE Page 4
DBMS LAB AY-2024-25
12. TheNon-subversionRule
Ifa RDBMS supports a lower-level language then it should not by pass
reused is the fundamental of the OOP’s concept. So, we can say Oracle8 is supported Object
Relational model, Object-oriented model both. Oracle products are based on a concept known as a
client-server technology. This concept involves segregating the processing of an application between
two systems. One performs all activities related to the database (server) and the other performs
activities that help the user to interact with the application (client). A client or front-end database
application also interacts with the database by requesting and receiving information from database
The database server or back end is used to manage the database tables and also respond to client
requests.
Introduction to ORACLE
ORACLE is a powerful RDBMS product that provides efficient and effective solutions for major
database features. This includes:
Controlled availability
Distributed database
systems Portability
DEPARTMENT--CSE Page 5
DBMS LAB AY-2024-25
Compatibility
Connectivity
An ORACLE data base system can easily take advantage of distributed processing by using its Client/Server
architecture. In this architecture, the database system is divided into two parts:
The server executes the ORACLE software and handles the functions required for concurrent, shared data access
to ORACLE database.
DEPARTMENT--CSE Page 6
DBMS LAB AY-2024-25
Reservations
Ticketing
Cancellations
Reservations:
Reservations are directly handled by booking office. Reservations can be made 60
days in advancein either cash or credit. In case the ticket is not available, a wait listed ticket is
issued to the customer. This ticket is confirmed against the cancellation.
DEPARTMENT--CSE Page 7
DBMS LAB AY-2024-25
WEEK-1
1. Bus
2. Reservation
3. Ticket
4. Passenger
5. Cancellation
TheattributesintheEntities:B
us:(Entity)
Destination
Source
CouchType
BusNo
Bus
Reservation(Entity)
ContactNo BusNo
No-of-Seats
Journeydate
Address
PNRNO
Reservation
Ticket:(Entity)
Dep-Time
Source
Age
Journeydate Sex
Destination
TicketNo
BusNo
Ticket
DEPARTMENT--CSE Page 8
DBMS LAB AY-2024-25
Passenger:
ContactNO
Age
Sex
PNRNO
Name
TicketNo
Passenger
Cancellation(Entity)
Journeydate SeatNo
ContactNo
PNRNO
Cancellation
DEPARTMENT--CSE Page 9
DBMS LAB AY-2024-25
ConceptdesignwithE-R Model:
10
DEPARTMENT--CSE Page 10
DBMS LAB AY-2024-25
CASESTUDY1:
➢ Considerthefollowinginformationaboutauniversitydatabase:
➢ ProfessorshaveanSSN,aname,anage,arank,andaresearchspecialty.
➢ Projectshaveaprojectnumber,asponsorname(e.g.,NSF),astartingdate,anendingdate,and abudget.
➢ GraduatestudentshaveanSSN,aname,anage,andadegreeprogram(e.g.,
➢ M.S.orPh.D.).
➢ Eachprojectismanagedbyoneprofessor(knownastheproject'sprincipalinvestigator).
➢ Eachproject isworkedonbyoneormoreprofessors(knownastheproject'sco-investigators).
➢ Professors canmanage and/orworkonmultipleprojects.
➢ Each project is worked on by one or more graduate students (known as theproject'sresearchassistants).
➢ Whengraduatestudentsworkonaproject,aprofessormustsupervisetheir workon the project. Graduate
students can work on multiple projects, in which casetheywill
havea(potentiallydi_erent)supervisorforeachone.
➢ Departmentshaveadepartmentnumber,adepartmentname,andamainoffice.
➢ Departmentshaveaprofessor(knownasthechairman)whorunsthedepartment.
➢ Professorsworkinoneormoredepartments,andforeachdepartmentthattheyworkin,atimepercentageisassoci
atedwiththeirjob.
➢ Graduatestudentshaveonemajordepartmentinwhichtheyareworkingontheirdegree.
• Eachgraduatestudenthasanother,moreseniorgraduatestudent(knownasastude
ntadvisor)whoadviseshimorheronwhatcoursestotake.
DEPARTMENT--CSE Page 11
DBMS LAB AY-2024-25
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
ofdatabaseusedtostoredata.Itstoresdatainformofrowsandcolumns.
1. DataDefinitionLanguage
Create, Alter,DropandTruncate
2. DataManipulationLanguage
Insert,Update,DeleteandSelect
3. TransactionControlLanguage
Commit, RollbackandSavepoint
4. DataControlLanguage
GrantandRevoke
DEPARTMENT--CSE Page 12
DBMS LAB AY-2024-25
Before we take a look on above-mentioned commands we will see the data types available
inOracle.
OracleInternalDatatypes
When 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.AnOracledatabasecanholdmanydifferenttypesofdata.
Datatype Description
Char(Size)Storesfixed-lengthcharacterdatatostore
alphanumericvalues,withamaximumsizeof2000bytes.Defaultandminimumsizeis1byte.
Varchar2(Size)Storesvariable-lengthcharacterdatatostore alphanumeric
values,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 of bytesrequired
storing each character with an upper limit of 2000 bytes. Default and minimum size is
1characteror1byte,dependingonthecharacter set.
Nvarchar2(Size) Storesvariable-
lengthcharacterstringhavingmaximumlengthsizecharacters or bytes, depending on the
choice of national character set. Maximum size
isdeterminedbythenumberofbytesrequiredtostoreeachcharacter,withanupperlimit
of4000bytes.
LongStores variable-lengthcharacterdataupto2GB(Gigabytes).Itslenthwouldbe
restrictedbasedonmemoryspace availableinthecomputer.
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
partvariesfrom-84to127.
DBMS Page 13
DBMS LAB AY-2024-25
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.LongRawStorebinarydataof variablelengthup to2GB(Gigabytes).
LOBS-LARGEOBJECTS
LOB is use to store unstructured information such as sound and video clips, pictures upto 4
GBsize.
characters.Varying-
widthcharactersetsarenotsupported.Maximumsizeis4GB.
Varying-
widthcharactersetsarenotsupported.Maximumsizeis4GB.Storesnationalcharacter
setdata.
BLOBTostoreaBinaryLargeObjectsuchagraphics,videoclipsandsoundfiles.
Maximumsizeis4GB.
BFILEContainsalocatortoalarge BinaryFilestoredoutsidethedatabase.
EnablesbytestreamI/OaccesstoexternalLOBsresidingonthedatabaseserver.Maximum
sizeis4GB.Apartfromoracleinternaldatatypes,usercancreatetheirowndatatype,whichisusedindata
baseandotherdatabaseobject.Wewilldiscussitinthelater part.
Thefollowingaretabularrepresentationoftheaboveentitiesandrelationships
BUS:
COLUMNNAME DATATYPE CONSTRAINT
Source varchar2(20)
Destination varchar2(20)
CouchType varchar2(20)
DBMS Page 14
DBMS LAB AY-2024-25
Reservation:
COLUMNNAME DATATYPE CONSTRAINT
Journeydate Date
No-of-seats integer(8)
Address varchar2(50)
Ticket:
COLUMNNAME DATATYPE CONSTRAINT
DBMS Page 15
DBMS LAB AY-2024-25
Passenger:
Name varchar2(15)
Age integer(4)
Sex char(10) (Male/Female)
Contactno Number(9) Shouldbeequalto10numbers
andnotallowotherthan
numeric
Cancellation:
COLUMNNAME DATATYPE CONSTRAINT
Journey-date Date
Seatno Integer(9)
Contact_No Number(9) Shouldbeequalto10numbers
andnotallowotherthan
numeric
DBMS LAB AY-2024-25
WEEK 2
Concept design with E-R Model and apply cardinalities for each relationship. Identify strong
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 or
classes, associations and attributes.
Outcomes:
Student gains the ability to describe the data requirements for a new information system in a direct and
easy to understand graphical notation.
E_R diagram:
Bus No
Source
BUS
Destination
Departure Time
Sex
DBMS Page 20
DBMS LAB AY-2024-25
VIVA QUESTIONS
1. Draw an E-R Diagram For an ATM System.
2. Draw an E-R Diagram For school mgmt system.
3. Draw an E-R Diagram For Roadways Travels Systems.
4. Draw an E-R Diagram For Bank Mgmt System.
5. Explain manyto many and many to one relationship.
DBMS Page 18
DBMS LAB AY-2024-25
WEEK 3
AIM
Relation Model represents attributes as columns in tables and different types of
attributes 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:
Example: The passenger tables look as below. This is an example. You can add more attributes based
on your E-R model. This is not a normalized table. Passenger
Bus passenger
Passenger-
#bus_no Tickets
#ppno
source #ppno
name
destination
#ticket_no
age
#jrny_date
sex
address
phone-no
DBMS Page 19
DBMS LAB AY-2024-25
Tickets
#tickets_no
no of tkts
From_place
T0_place
#Bus_no
#jrny_date
Note: The student is required to submit a document byRepresent relationships in a tabular fashion to
the lab teacher.
Relate 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 for
different entities and also the whole “Roadway Travels”.
Represent 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. Represent
attributes as columns in tables or as tables based on the requirement. In this we will represent the
different entities, attributes of different keys in a tabular fashion or manner.
DBMS Page 20
DBMS LAB AY-2024-25
Relational Model:
The relational model is a depiction of how each piece of stored information relates to the other stored
information. It shows how tables are linked, what type of the links are between tables, what keys are
used, what information is referenced between tables. It’s an essential part of developing a normalized
database structureto prevent repeat and redundant data storage.
➢ A super key is a set of one or more attributes which; taken collectively, allow us to identify
uniquely an entity in the entity set.
➢ A primarykey is a candidate key(there may be more than one) chosen bythe DB designer to
identify entities in an entity set.
➢ A super key may contain extraneous attributes, and we are often interested in the smallest super
key. 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 another
table. The foreign keycan be used to cross-reference tables.
Normalization
Database normalization is a technique for designing relational database tables to minimize duplication of
information and, in so doing, to safeguard the database against certain types of logical or structural
problems, namely data anomalies. In this we will write the normalization tables that is entities of
“Roadway Travels.”
DBMS Page 21
DBMS LAB AY-2024-25
VIVA QUESTIONS
DBMS Page 22
DBMS LAB AY-2024-25
WEEK 4
AIM
Normalization of tables
Objectives:
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 permit
data to be queried and manipulated using a "universal data sub-language" grounded in first-order
logic.(SQL is an example of such a data sub-language, albeit one that Codd regarded as seriously
flawed.)
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 deletion
dependencies;
2. To reduce the need for restructuring the collection of relations, as new types of data are
introduced, 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 querystatistics, where these statistics
are liable to change as time goes by.
Querying and manipulating the data within a data structure which is not normalized, such as the
following non-1NF representation of customers' credit card transactions, involves more complexity than
is really necessary:
Customer Transactions
Tr. ID Date Amount
Jones 12890 14-Oct-2003 −87
12904 15-Oct-2003 −50
r. ID Date Amount
Wilkinso
12898 14-Oct-2003 −21
DBMS Page 23
DBMS LAB AY-2024-25
For example, in order to find out the monetary sum of all transactions that occurred in
October 2003 forall customers, the system would have to know that it must first unpack
the Transactions group of each customer, then sum the Amounts of all transactions thus
obtained where the Date ofthe transaction fallsin October 2003.
One of Codd's important insights was that this structural complexity could always be
removed completely, leading to much greater power and flexibility in the way queries
could be formulated (by users and applications) and evaluated (by the DBMS). The
normalized equivalent of the structure abovewould look like this:
Now each row represents an individual credit card transaction, and the DBMS can obtain
the answer of interest, simply by finding all rows with a Date falling in October, and
summing 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 structures
that had to be handled specially. Accordingly, the normalized designlends itself to general-
purpose queryprocessing, whereas the unnormalized design does not.
DBMS Page 24
DBMS LAB AY-2024-25
VIVA QUESTIONS
DBMS Page 25
DBMS LAB AY-2024-25
WEEK-5(a)
1.StepsforinstallingMySQL
Step1
Make sure you already downloaded the MySQL essential 5.0.45 win32.msi file. Doubleclick
on the .msifile.
Step2
This is MySQL Server 5.0 setup wizard. The setup wizard will install MySQL Server5.0 release 5.0.45 on your
computer. To continue, click next.
26
DBMS Page 26
DBMS LAB AY-2024-25
Step3
Choose these tup type that best suits your needs. For common program features select
Typicaland it’s recommended for general use. To continue, click next.
Step4
29
DBMS Page 27
DBMS LAB AY-2024-25
Step5
Theprogramfeaturesyouselectedarebeinginstalled.PleasewaitwhilethesetupwizardinstallsMySQ
L5.0.Thismaytakeseveralminutes.
30
DBMS Page 34
DBMS LAB AY-2024-25
Step6
Tocontinue,clicknext.
Step7
Tocontinue,clicknext.
Step8
Wizard Completed. Setup has finished installing MySQL 5.0. Check the configure the
MySQL server now to continue. Click Finish to exit the wizard
31
DBMS Page 35
DBMS LAB AY-2024-25
d.
Step9
The configuration wizard will allow you to configure the
MySQL Server5.0 server instance.To continue,click next.
Step10
Select a standard configuration and this will use a general purpose configurationfor the server that can be tuned
manually.To continue,click next.
32
DBMS Page 36
DBMS LAB AY-2024-25
Step11
Check on the install as windows service and include bin directory in windows path.
Tocontinue,clicknext.
Step12
Pleasesetthesecurityoptionsbyenteringtherootpasswordandconfirmretypethepassword.
33
DBMS Page 37
DBMS LAB AY-2024-25
continue,clicknext.
Step13
Readytoexecute?Clicksexecutetocontinue.
Step14
Processingconfigurationinprogress.
32
DBMS Page 38
DBMS LAB AY-2024-25
Step15
Configuration file created. Windows service MySQL5 installed. Press finish to close
thewizard.
33
DBMS Page 39
DBMS LAB AY-2024-25
WEEK-5
(b)
MongoDB
At the time of writing, the latest version is 4.4.5. Ensure that the platform is Windows, and the package
is MSI. Go ahead and click on download.
DBMS Page 34
DBMS LAB AY-2024-25
Mongo DB Installation:
You can find the downloaded file in the downloads directory. You can follow the steps
mentioned there and install the software.
DBMS Page 35
DBMS LAB AY-2024-25
On completing the installation successfully, you will find the software package in your C
drive. C:\Program Files\MongoDB\Server\4.4\bin.
You can see that there are mongo and mongod executable files. The mongod file is the daemon
process that does the background jobs like accessing, retrieving, and updating the database.
It’s best practice to create an environment variable for the executable file so that you
don’t have to change the directory structure every time you want to execute the file.
DBMS Page 36
DBMS LAB AY-2024-25
After creating an environment path, you can open the command prompt and just
type in mongo and press enter.
DBMS Page 37
DBMS LAB AY-2024-25
To verify if it did the setup correctly, type in the command show DBS.
With that, you have successfully installed and set up MongoDB on your Windows system.
DBMS Page 38
DBMS LAB AY-2024-25
WEEK-6
PRACTISING DDL&DMLCOMMANDS
Data Definition Language
The data definition language is used to create an object, alter the structure of an object and also drop
already created object. The Data Definition Languages used for table definition can be classified into
following:
DBMS Page 39
DBMS LAB AY-2024-25
1. CREATION OF TABLES:
SQL-CREATETABLE:
Table is a primary object of database, used to store data in form of rows and columns. It is created
using following command:
Syntax:CREATETABLEtablename(column_namedata_typeconstraints,…)
SQL>CREATETABLESAILORS((SIDint(10)PRIMARYKEY,SNAMEVARCHAR(
10),RATINGint(10),AGEint(10));
Table
Created.Descc
Command
The DESCRIBE command is used to view the structure of at able as follows
.SQL>DESC SAILORS;
TESTRESULT
Example1:Create an RESERVEStablewithfields(SID,BID
,DAY)and display using DESCRIBE command.
DBMS Page 40
DBMS LAB AY-2024-25
Example2:CreateaBOATStablewithFields(BID,BNAME,COLOR)anddisplayusingDESCRIBEcommand
2. ALTERTABLE:
ToADDacolumn:
TESTOUTPUT
ToDROPacolumn:
SYNTAX:ALTERTABLE<TABLENAME>DROPCOLUMN<COLUMNNAME>;.
EX:(WriteyourownQuery)
TESTOUTPUT
ToMODIFYacolumn:
SYNTAX:ALTERTABLE<TABLENAME>MODIFY(<COLUMNNAME>
<NEWDATATYPE>(<NEWSIZE>));
EX:(WriteyourownQuery)
TESTOUTPUT
DBMS Page 41
DBMS LAB AY-2024-25
Example1:
SQL>ALTERTABLESAILORADD(SNONUMBER(10));
TESTOUTPUT
3. RENAMEATABLE
Renamecommandisusedtogivenewnamesforexistingtables.
SQL>RENAMEoldtablename
TOnewtablename;EX:(Writeyourown Query)
TESTOUTPUT
4. TRUNCATEATABLE
Truncatecommandisusedtodeleteallrecordsfromatable.
SQL>TRUNCATETABLEtablename;EX:(
WriteyourownQuery)
TESTOUTPUT
5. DROPATABLE
Dropcommandisusedtoremoveanexistingtablepermanentlyfromdatabase.
SQL>
DROPTABLEtablename;EX:(Wri
teyourownQuery)
TESTOUTPUT
DBMS Page 42
DBMS LAB AY-2024-25
VIVAQUESTIONS
1. Definedataand information.
2. DefineDatabasemanagementsystem.
3. WhatisSQL?
4. Whatisthesyntaxforcreatingatable?
5. ListthecomponentsofSQL.
6. DefineDDL?WhataretheDDLcommands?
7. Listouttheusesofaltercommand.
8. WhatisSyntaxfortruncateatable?
9. Whatistheusedroptablecommand?
DBMS Page 43
DBMS LAB AY-2024-25
DMLCOMMANDS
1. ToRetrieve/DisplayDatafromTables:
a. SelectcommandisusedtoselectvaluesordatafromtableSYNT
AX
SELECT*FROMTABLENAME;
Example:
SQL>SELECT*FROMSAILORS;TE
STOUTPUT:
b. Theretrievingofspecificcolumnsfromatable
SQL>SELECTcolumnname1,columnname2,….columnnamenFROMtablename;EX:(Writey
ourown Query)
TESTOUTPUT
c. Eliminationofduplicatesfromtheselectstatement
DBMS Page 44
DBMS LAB AY-2024-25
SQL>SELECTDISTINCTcolumnname1,columnname2,….columnnamenFROMtablename;
EX:(WriteyourownQuery)
TESTOUTPUT
d. Selectingadatasetfromtabledata
SQL>SELECTcolumnname1,columnname2,….columnnamenFROMtablenameWHEREsearc
hcondition;
EX:(WriteyourownQuery)
TESTOUTPUT
Example1:DisplayDataFromRESERVESTable
Example2:DisplayDataFromBOATSTable
DBMS Page 45
DBMS LAB AY-2024-25
2. INSERTINGDATAINTOTABLE
Insertcommandisusedtoinsertrowsintothetable.SYNT
AX:
INSERTINTOtablename(columnname1,columnname2,….columnnamen)
Example:
SQL>INSERTINTOSAILORSVALUES(22,’DUSTIN’,7,45.0);
1rowcreated
SQL>INSERTINTOSAILORSVALUES(29,’BRUTUS’,1,33.0);
1rowcreated
INSERTIONofDatacanalsobedonebythefollowingSyntax:
SYNTAX
INSERTINTOtablename(columnname1,columnname2,….columnnamen)VALUES(Value1,Value2,..V
aluen);
Example:
SQL>INSERTINTOSAILORS(SID,SNAME,RATING,AGE)VALUES(31,’LUBBER
’,8,55.5);
1rowcreated
Example1:INSERTdataintoRESERVEStable:T
ESTOUTPUT:
Example2:INSERTdataintoBOATStable:TE
STOUTPUT:
DBMS Page 46
DBMS LAB AY-2024-25
UPDATE
ThisSQLcommandisusedtomodifythevaluesinanexistingtable.
SQL>UPDATEtablename
SETcolumn1=expression1,column2=expression2,...
WHEREsomecolumn=somevalue;
Example1:UPDATESAILORSS
SETS.age=S.age+1,S.rating=S.rating-
1WhereS.sid=34546;
TESTOUTPUT
Example2:(WriteyourownQuery)
TESTOUTPUT
DELETE
Inordertodeleterowsfroma
tableweusethiscommandSQL>DELETE
FROMtablenameWHEREcondition;
Basedontheconditionspecifiedtherows
getsfetchedfromthetableandgetsdeletedintable.HeretheWHEREclauseisoptional.
Example1:DELETES.AGEFROMSAILORSSwhereS.Sname=’Smith’;
DBMS Page 47
DBMS LAB AY-2024-25
TESTOUTPUT
Example2:DELETEFROMSAILORS;TE
STOUTPUT
VIVAQUESTIONS
1. WhataretheDMLcommands?
2. Howthedataorvaluestobeenteredintoatable?
3. WhatistheuseofDELETEcommand?
4. Howthedataorvaluestobeupdatedonatable?
5. ListouttheusesofSELECTcommand?
6. Howthedata orvaluesareretrievedfromatable?
7. DefineDML?WhataretheDML commands?
DBMS Page 48
DBMS LAB AY-2024-25
KEYCONSTRAINTS
Domain Integrity
constraintsEntity Integrity
constraintsReferentialIntegrityc
onstraints
1. PRIMARY KEY&NOTNULL
Example:
CREATETABLEsailors(sidinteger,
sname varchar(32)
,rating integer NOT
NULL,agereal,
PRIMARYKEY(sid));
Tablecreated.
TestOutput:
Example:PracticewithyourownQuery:
TestOutput
ImposingICusingALTER
Example:AlterTableSailorsMODIFYsname varchar(32)NOTNULL;
TestOutput
Example:PracticewithyourownQuery:
TestOutput
2. DEFAULT
CREATETABLEsailors(sidinteger,
sname varchar(32)
,rating integer NOT
NULL,age real DEFAULT
25,PRIMARYKEY(sid));
Example:PracticewithyourownQuery:
DBMS Page 49
DBMS LAB AY-2024-25
TestOutput
3. UNIQUE
CREATETABLEsailors(sidinteger,
sname varchar(32) UNIQUE
,ratinginteger,
age real DEFAULT
25,PRIMARY
KEY(sid));
TestOutput
Example:PracticewithyourownQuery:
TestOutput
4. FOREIGNKEY
CREATE TABLE reserves ( sid integer not null, bid integer not null, day datetime not null, PRIMARY
KEY(sid,bid,day),FOREIGN KEY(sid)REFERENCESsailors(sid));
Example:PracticewithyourownQuery:
TestOutput
AddingForeignKeytoanexistingTable
AltertablereservesADDForeignKey(sidREFERENCESSailors(sid));
Example:PracticewithyourownQuery:
TestOutput
DBMS Page 50
DBMS LAB AY-2024-25
VIVAQUESTIONS
1) DifferencebetweenUNIQUEandPRIMARY KEY
2) WhendoyouuseCompositePrimarykey?
3) DifferencebetweenCandidateKey&PrimaryKey
4) WhatisthePrerequisiteforakeytobeusedasaForeignKey
5) WhatisaReferentialIntegrity?
6) GiveTwopracticalexamplesforReferentialIntegrity?
DBMS Page 51
DBMS LAB AY-2024-25
WEEK 7
AIM
QUERYING
QUERIES USING ANY, ALL, IN, INTERSECT, UNION
Objectives:
Student will able to learn to operate on multiple result sets to return a single result set.
Student will able to learn to perform nested Queries.
Outcomes:
Student gains the knowledge to implement queries using ANY, ALL, IN, INTERSECT, UNION.
6. Create the table using following attributes TICKET (TICKET_NO: NUMERIC (9): PK,
JOURNEY_DATE: DATE, AGE: INT (4), SEX: CHAR (10): MALE/FEMALE, SOURCE: VARCHAR2
(50), DEP_TIME: VARCHAR2 (50))
Creating table
Syntax
Create table <table name> (col1 datatype,col2 datatype,col3 datatype)
Query
CREATE TABLE TICKET (TICKET_NO NUMBER (9) PRIMARY KEY , JOURNEY_DATE DATE,
AGE NUMBER (4), SEX CHAR (10), SOURCE VARCHAR2 (50), DEP_TIME VARCHAR2 (50))
Describing table
Query
Desc TICKET
DBMS Page 52
DBMS LAB AY-2024-25
Output
Table Column Data Type Length Precision Scale Primary Key Nullable Default Comment
JOURNEY_DATE Date 7 - - - - -
AGE Number - 4 0 - - -
SEX Char 10 - - - - -
SOURCE Varchar2 50 - - - - -
DEP_TIME Varchar2 50 - - - - -
Syntax
Insert into <table name> values (val 1,val2,val3)
Query
insert into TICKET values(1203,'10/FEB/11',19,'MALE','HYDERABAD','10.30 AM');
values(1205,'14/FEB/11',20,'MALE','HYDERABAD','11.00 AM');
Display table
Syntax
Query
DBMS Page 53
DBMS LAB AY-2024-25
Output
7. Create
e table using following attributes PASSENGER_TICKETS (PPNO:
VARCHAR2 (15): PK, TICKET_NO: NUMERIC (9))
Creating table
Syntax
Create tab e <table name> (col1 datatype,col2 datatype,col3 datatype)
Query
CREATE TABLE PASSENGER_TICKETS (PPNO VARCHAR2 (15) PRIMARYKEY,
TICKET_ NUMBER (9))
Describing tableQuery
Desc PASSENGER_TICKETS
Output
DBMS Page 54
DBMS LAB AY-2024-25
DBMS Page 55
DBMS LAB AY-2024-25
Com me
Table Column Data Type Length Precision Scale Primary Nullabl Defau
Key e lt
TICKET_NO Number - 9 0 - - -
DBMS Page 55
DBMS LAB AY-2024-25
Syntax
Insert into <table name> values (val 1,val2,val3)
Query
insert into PASSENGER_TICKETS values(1,1203); insert into
Syntax
Select <select list> from <table name>
Query
select * from TICKET;
Output
PPNO TICKET_NO
1 1203
2 1213
3 1201
4 1202
5 1205
8. Create the table using following attributes RESERVATION (PNR_NO: NUMERIC (9): FK,
JOURNEY_DATE: DATE, NO_OF_SEATS: INT (8), ADDRESS: VARCHAR2 (50), CONTACT_NO:
NUMERIC (10), STATUS: CHAR (3): YES/NO)
DBMS Page 56
DBMS LAB AY-2024-25
Creating table
Syntax
Create table <table name> (col1 datatype,col2 datatype,col3 datatype)
Query
create table reservation (pnr_no varchar2(15),journey_date date,no_of_seats
number(8),address varchar2(50),contact_no number(10),status char(3),foreign
key(pnr_no)references passenger_tickets(ppno));
Describing table
Query
Desc reservation
Output
Table Column Data Type Length Precision Scale Primary Key Nullable Default Comment
RESERV
PNR_NO Varchar2 15 - - - - -
ATION
JOURNEY_DATE Date 7 - - - - -
NO_OF_SEATS Number - 8 0 - - -
ADDRESS Varchar2 50 - - - - -
CONTACT_NO Number - 10 0 - - -
STATUS Char 3 - - -
Syntax
Insert into <table name> values (val 1,val2,val3)
57
DBMS Page 57
DBMS LAB AY-2024-25
Creating table
Syntax
Create table <table name> (col1 datatype,col2 datatype,col3 datatype)
Query
create table reservation (pnr_no varchar2(15),journey_date date,no_of_seats
number(8),address varchar2(50),contact_no number(10),status char(3),foreign
key(pnr_no)references passenger_tickets(ppno));
Describing table
Query
Desc reservation
Output
Table Column Data Type Length Precision Scale Primary Key Nullable Default Comment
RESERV
PNR_NO Varchar2 15 - - - - -
ATION
JOURNEY_DATE Date 7 - - - - -
NO_OF_SEATS Number - 8 0 - - -
ADDRESS Varchar2 50 - - - - -
CONTACT_NO Number - 10 0 - - -
STATUS Char 3 - - -
DBMS Page 58
DBMS LAB AY-2024-25
Syntax
Insert into <table name> values (val 1,val2,val3)
DBMS Page 59
DBMS LAB AY-2024-25
Query
insert into reservation values(1,'10/feb/11',5,'amberpet','7416944004','yes'); insert into
values(3,'14/feb/11',3,'ecil','00000000','yes');
values(5,'15/feb/11',7,'b.b nagar','8143528258','yes');
Display table
Syntax
Select <select list> from <table name>
Query
select * from reservation;
Output
DBMS Page 60
DBMS LAB AY-2024-25
Create the table using following attributes CANCELLATION (PNR_NO: NUMERIC (9): FK,
JOURNEY_DATE: DATE, NO_OF_SEATS: INT (8), ADDRESS: VARCHAR2 (50),
CONTACT_NO: NUMERIC (9), STATUS: CHAR (3): YES/NO)
Creating table
Syntax
Create table <table name> (col1 datatype,col2 datatype,col3 datatype)
Query
create table cancellation (pnr_no varchar2(15),journey_date date,no_of_seats number(8),address
varchar2(50),contact_no number(10),status char(3),foreignkey(pnr_no)references
passenger_tickets(ppno));
Describing table
Query
Desc reservation
Output
Com men
Table Column Data Type Length Precision Scale Primary Key Nullable Default
CANCELLAT
PNR_NO Varchar2 15 - - - - -
ION
JOURNEY_DATE Date 7 - - - - -
NO_OF_SEATS Number - 8 0 - - -
ADDRESS Varchar2 50 - - - - -
CONTACT_NO Number - 10 0 - - -
STATUS Char 3 - - - - -
DBMS Page 61
DBMS LAB AY-2024-25
Syntax
Insert into <table name> values (val 1,val2,val3)
Query
insert into cancellation values(1,'10/feb/11',5,'amberpet','7416944004','yes'); insert into
values(3,'14/feb/11',3,'ecil','00000000','yes');
values(5,'15/feb/11',7,'b.b nagar','8143528258','yes');
Display table
Syntax
Select <select list> from <table name>
Query
select * from cancellation
Output
DBMS Page 62
DBMS LAB AY-2024-25
Query
select distinct(pnr_no) from reservation;
Output
PNR_NO
Query
select name from passenger where sex='MALE'
Output
NAME
TIRUMALAY
NAGARAJU
AVS.RAVI
DBMS Page 63
DBMS LAB AY-2024-25
29. Display the ticket numbers and names of all the passengers.
Query
select p.name,t.ticket_no from passenger p,passenger_tickets t where
t.ppno=p.ppno
NAME TICKET_NO
TIRUMALAY 1203 Output
SUPRIYA 1213
AMULYA 1201
NAGARAJU 1202
AVS.RAVI 1205
30. Find the ticket numbers of the passengers whose name start with ‘t’ and ends with ‘y’.
Query
select t.ticket_no from passenger p,passenger_tickets t where p.name like'T%Y'and
t.ppno=p.ppno;
Output
TICKET_NO
1203
31. Find the names of passengers whose age is between 15 and 20.
Query
select name from passenger where age between 15 and 20
Output
NAME
TIRUMALAY
SUPRIYA
AMULYA
NAGARAJU
AVS.RAVI
DBMS Page 64
DBMS LAB AY-2024-25
Query
select name from passenger where name like 'A%';
Output
NAME
AMULY
A
AVS.RAV
I
Query
select name from passenger order by name;
Output
NAME
AMULYA
AVS.RAVI
NAGARAJU
SUPRIYA
TIRUMALAY
34. Write a query to display the information present in the PASSENGER and
CANCELLATION tables. (Use UNION Operator).
Query
select * from passenger p,cancellation c where p.ppno=c.pnr_nounion
DBMS Page 65
DBMS LAB AY-2024-25
Output
35. Display the number of tickets booked for each PNR_NO using GROUP BY clause.
(Use GROUP BY on PNR_NO).
Query
select pnr_no,sum(no_of_seats) from reservation group bypnr_no;
Output
PNR_NO SUM(NO_OF_SEATS)
1 13
3 3
5 8
2 10
4 4
DBMS Page 66
DBMS LAB AY-2024-25
Query
Select distict (pnr_no) from reservation;
Output
PNR_NO
37. Find the number of tickets booked by a passenger where the number of seats is
greater than 5. (Use GROUP BY, WHERE and HAVING clauses).
Query
select pnr_no,sum(no_of_seats) from reservation group bypnr_no havingsum(no_of_seats) > 5
Output
PNR_NO SUM(NO_OF_SEATS)
1 13
5 8
2 10
Query
select sum(no_of_seats) from cancellation;
Output
SUM(NO_OF_SEATS)
38
DBMS Page 67
DBMS LAB AY-2024-25
VIVA QUESTIONS
DBMS Page 68
DBMS LAB AY-2024-25
WEEK 8 & 9:
Student will able to learn to perform mathematical operations that return a single value, calculated from
values in a column.
Outcomes:
Student gains the knowledge to perform aggregate operations on the database appropriately.
Aggregate operators: In addition to simply retrieving data, we often want to perform some computation or
summarization. SQL allows the use of arithmetic expressions. We now consider a powerful class of constructs
for computing aggregate values such as MIN and SUM.
1. Count: COUNT following by a column name returns the count of tuple in thatcolumn.
If DISTINCT keyword is used then it will return only the count of unique tuple in the
column. Otherwise, it will return count of all the tuples (including duplicates) count(*)
indicates all the tuples of the column.
2. SUM: SUM followed by a column name returns the sum of all the values in that
column.
3. AVG: AVG followed by a column name returns the average value of that column
values.
DBMS Page 69
DBMS LAB AY-2024-25
4. MAX: MAX followed by a column name returns the maximum value of that column.
DEPTNO MAX(SAL)
10 5000
20 3000
30 2850
30 2850
5. MIN: MIN followed by column name returns the minimum value of that column.
MIN(SAL)
10 1300
DBMS Page 70
DBMS LAB AY-2024-25
VIEW: In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the
data were coming from one single table.
A view is a virtual table, which consists of a set of columns from one or more tables. It is similar to
a table but it doest not store in the database. View is a query stored as an object.
1. Example:
SQL>CREATE VIEW employee AS SELECT empno,ename,job FROM EMPWHERE job =
‘clerk’;
View created.
ENAME JOB
DBMS Page 71
DBMS LAB AY-2024-25
2. Example:
DROP VIEW: This query is used to delete a view , which has been already created.
View dropped
Queries using Conversion functions (to_char, to_number and to_date), string functions
(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date
functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc,
round, to_char, to_date)
DBMS Page 72
DBMS LAB AY-2024-25
15-JAN-89
2. String functions:
Concat: CONCAT returns char1 concatenated with char2. Both char1 and char2 can beany of the datatypes
ORACLECORPORATION
Lpad: LPAD returns expr1, left-padded to length n characters with the sequence ofcharacters in expr2.
Rpad: RPAD returns expr1, right-padded to length n characters with expr2, replicated asmany times as
necessary.
ORACLE*********
DBMS Page 73
DBMS LAB AY-2024-25
Lower: Returns a character expression after converting uppercase character data tolowercase.
dbms
Upper: Returns a character expression with lowercase character data converted to uppercase
Length: Returns the number of characters, rather than the number of bytes, of thegiven string
expression, excluding trailing blanks.
Instr: The INSTR functions search string for substring. The function returns an integer indicating the
position of the character in string that is the first character of this occurrence.
3. Date functions:
Sysdate: SQL>SELECT SYSDATE FROM DUAL;29-DEC-08
DBMS Page 74
DBMS LAB AY-2024-25
next_day:
add_months:
last_day:
months_between:
Least:
Greatest:
Trunc:
DBMS Page 75
DBMS LAB AY-2024-25
Round:
SQL>SELECT ROUND(SYSDATE,'DAY')FROM
DUAL;28-DEC-08
to_char:
dual;24-mar-05.
to_date:
VIVA QUESTIONS
3. Define View?
DBMS Page 76
DBMS LAB AY-2024-25
Week-10
TRIGGERS
In MySQL, a trigger is a set of SQL statements that is invoked automatically when a change
ismadetothedataontheassociatedtable.Atriggercanbedefinedtobeinvokedeitherbeforeorafterthedatai
schangedbyINSERT, UPDATEorDELETEstatement.
• BEFOREINSERT –activatedbeforedataisinsertedintothetable.
• AFTERINSERT – activatedafterdataisinsertedintothetable.
• BEFOREUPDATE –activatedbeforedatainthetableisupdated.
AFTERUPDAT
• –activatedafterdatainthetableisupdated.
BEFOREDELETE
• AFTERDELETE –activatedbeforedataisremovedfromthetable.
• –activatedafterdataisremovedfromthetable.
Theeventsthatfireatriggerincludethefollowing:
1)DMLstatementsthatmodifydatainatable(INSERT,UPDATE,orDELETE)2)DDLstateme
nts.
3) Systemeventssuchasstartup,shutdown,anderrormessages.
4) Usereventssuchaslogonandlogoff.Note:OracleFormscandefine,store,andruntriggersofadiffe
rentsort.
ToViewlistoftriggers;
Showtriggers;
ToremoveatriggerforDatabase
droptriggertrigger_name;ex:
droptriggerins_sal;
TypesofTriggers:-
1. Row Triggers :-A row trigger is fired each time the table is affected by the triggeringstatement.
For example, if an UPDATE statement updates multiple rows of a table, a rowtrigger is fired once
for each row affected by the UPDATE statement. If a triggering
statementaffectsnorows,arowtriggerisnotexecutedatall.
DBMS Page 77
DBMS LAB AY-2024-25
Rowtriggersareusefulifthecodeinthetriggeractiondependsondata
providedbythetriggering statement or rows that are affected. For example, Figure 15 - 3
illustrates a rowtriggerthatusesthevaluesofeachrowaffectedbythetriggeringstatement.
2. Statement Triggers :A statement trigger is fired once on behalf of the triggering
statement,regardless of the number of rows in the table that the triggering statement affects
(even if norows are affected). For example, if a DELETE statement deletes several rows
from a table, astatement-level DELETE trigger is fired only once, regardless of how many
rows are deletedfromthetable.
Statement triggers are useful if the code in the trigger action does not depend on
thedata provided by the triggering statement or the rows affected. For example, if a trigger
makesa complex security check on the current time or user, or if a trigger generates a single
auditrecordbasedonthetypeoftriggeringstatement,astatementtriggerisused.
When defining a trigger, specify the trigger timing. That is, specify whether the
triggeraction is to be executed before or after the triggering statement. BEFORE and AFTER
apply tobothstatementandrowtriggers
Sample:
CREATETRIGGERtrigger_name trigger_time
trigger_eventONtable_name
FOREACHROW
BEGIN
...END
;
trigger_time=before/aftertrigger_event=insert/delete/
update
Example:
CREATE TRIGGER sal_sum after insert ON
empFOREACHROWSET@sal=@sal+NEW.sal;
Firingatrigger:
Question:Findthesumofsalariesofallemployees1)Firs
tcreateatableempwithfollowingcolumns
Field Type
DBMS Page 78
DBMS LAB AY-2024-25
empid int(11)
ename varchar(50)
sal int(11)
WriteaQuery:
TESTOUTPUT
DBMS Page 79
DBMS LAB AY-2024-25
2) createvariable/parametersalasbelowatmysqlpromptmysql
>set@sal=0;
3) nowcreatetriggeronemp
4) insertthevaluesintotableemp;
mysql> insert into emp
values(1001,'suhaas',10000);mysql> insert into emp
values(1002,'Dilraj',15000);mysql>insertintoempvalues(1
003,'Riyanshi',25000);
Note:triggerisfiredonafterinsert5)
checkvaluesinthetableemp;
mysql>select*fromemp;
TESTOUTPUT
6) checkingvalueintheparametersalm
ysql>select@salasTotalSalary;
TESTOUTPUT
Note:wheneverthereisinsertoperationthatvalueinthesalvariableincreases
DBMS Page 80
DBMS LAB AY-2024-25
VIVAQUESTIONS
1. Definedatabasetriggers.
2. Listouttheusesofdatabasetriggers.
3. Whataretheparsoftriggersand ituses?
4. Listoutthetypesoftrigger.
5. Whatistheuseofrowtrigger?
6. Whatistheuseofstatementtrigger?
7. Whatdoyoumeantbytriggertime?
8. Comparebeforetriggerandaftertrigger.
9. WhatisthesyntaxforDROPatrigger?
10. Listoutthesomesituationstoapplybeforeandaftertriggers.
DBMS Page 81
DBMS LAB AY-2024-25
WEEK-11, 12
PROCEDURES
Objectives:
Student will able to learn the features like reusability, maintainability and modularity.
Student will able to learn to develop procedures and function for various operation.
Outcomes:
Student gains the knowledge to implement procedures and function for various operations.
Procedures created
WHERE stdId=in_customer_id;
OPEN c1;
End;
DBMS Page 82
DBMS LAB AY-2024-25
PL/SQL
PL/SQLprogramsarewrittenaslinesoftextusingaspecificsetofcharacters:
• Upper-andlower-caselettersA..Zanda..z
• Numerals0..9
• Symbols()+-*/<>=!~^;:. '@%, "#$&_|{}?[]
• Tabs,spaces,andcarriagereturns
AlineofPL/SQLtextcontainsgroupsofcharactersknownaslexicalunits:
• Delimiters(simpleandcompoundsymbols)
• Identifiers,whichincludereservedwords
• Literals
• Comments
To improve readability, you can separate lexical units by spaces. In fact, you must
separateadjacentidentifiersbyaspaceorpunctuation.Thefollowinglineisnotallowedbecausethereserve
dwordsENDandIFarejoined:
IFx>yTHENhigh:=x;ENDIF;--notallowed,mustbeENDIF
You cannot embed spaces inside lexical units except for string literals and comments.
Forexample,thefollowinglineisnotallowedbecausethecompoundsymbolforassignment(:=)issplit:
count:=count+1;--notallowed,mustbe:=
Toshowstructure,youcansplitlinesusingcarriagereturns,andindentlinesusingspacesortabs.Thisf
ormattingmakesthefirstIF statementmorereadable.
IFx>yTHENmax:=x;ELSEmax:=y;ENDIF;
TESTOUTPUT
DBMS Page 83
DBMS LAB AY-2024-25
2) WRITEAPROGRAMTOPRINTEVENNUMBERSFROM1TO100DECLA
RE
NNUMBER(3):=0;
BEGIN
WHILE
N<=100LOOP
N
:=N+2;DBMS_OUTPUT.PUT_LINE
(N);ENDLOOP;
END;
TESTOUTPUT
3) WRITEAPROGRAMTOACCEPTANUMBERANDFINDSUMOFTHEDIGITSDECLAR
E
NNUMBER(5):=&N;S
NUMBER:=0;
RNUMBER(2):=0;BEGIN
WHILE N
!=0LOOPR:=MOD
(N,10);S:=S+R;
Page 1 of
7N:=TRUNC(N/10
);ENDLOOP;
DBMS_OUTPUT.PUT_LINE('SUM OF DIGITSOFGIVENNUMBERIS'||S);END;
TESTOUTPUT
DBMS Page 84
DBMS LAB AY-2024-25
4) WriteaprogramtoacceptanumberandprintitinreverseorderDECLA
RE
N
NUMBER(5):=&N;RE
VNUMBER(5):=0;R
NUMBER(5):=0;BEGI
N
WHILE N
!=0LOOPR:=MO
D(N,10);REV:=RE
V*10+R;N:=TRUN
C(N/10);ENDLOO
P;
DBMS_OUTPUT.PUT_LINE('THEREVERSEOFAGIVENNUMBERIS'||REV);END;
TESTOUTPUT
5) WriteaprogramacceptthevalueofA,B&Cdisplay
whichisgreaterDECLARE
ANUMBER(4,2):=&A;
B
NUMBER(4,2):=&B;C
NUMBER(4,2):=&C;B
EGIN
IF(A>BANDA>C)THENDBMS_OUTPUT.PUT_LINE('
AISGREATER'||''||A);ELSIFB>CTHEN
DBMS_OUTPUT.PUT_LINE('BISGREATE'||''||B);EL
SE
DBMS_OUTPUT.PUT_LINE('CISGREATER'||''||C);END
IF;
END;
DBMS Page 85
DBMS LAB AY-2024-25
VIVAQUESTIONS
1. What is PL/SQL?
2. What is the basic structure of PL/SQL?
3. How is a process of PL/SQL compiled?
4. Mention what PL/SQL package consists of?
5. What are the benefits of PL/SQL packages?
6. What is the difference between FUNCTION,PROCEDURE AND PACKAGE inPL/SQL
7. Show how functions and procedures are called in a PL/SQL block?
8. What is Stored Procedure?
9. What is difference between Function and Stored Procedure?
DBMS Page 86
DBMS LAB AY-2024-25
WEEK 13
DCL (DATA CONTROL LANGUAGE): Data Control Language statements are used tocreate
roles, permissions, and referential integrity as wellit is used tocontrol
accesstodatabasebysecuringit.DCLCommandsareGrantandRevoke
GRANT -givesuser'saccessprivilegestodatabase
REVOKE -
withdrawaccessprivilegesgivenwiththeGR
ANTcommand
CheckingofUserPrivileges,Grantsetcm
ysql>createusermrcet_cse;
QueryOK,0rowsaffected(0.30sec)
*ToCheckwhereisthecreateduseri.elocationinourdatabase
mysql>selectuser();
TESTOUTPUT
*Tocheckwhatarethegrantsthatthelocationishaving/mysq
l>showgrants;
TESTOUTPUT
*ToCheckwhataretheGRANTShavingforcreatedusermys
ql>showgrantsformrcet_cse;
TESTOUTPUT
DBMS Page 87
DBMS LAB AY-2024-25
mysql>showtables;
TESTOUTPUT
*ToFlush(RE-
FRESH)theprivilegesmysql>flushprivile
ges;
QueryOK,0rowsaffected(0.08sec)
*Explanation:Tocheckwhereistheuseri.eincaseifwecreateduser(Ex:mrcet_cse)itwillbedisplayed
as“%”. Rootuserisbydefaultsoit will beavailablein“Localhost”
mysql>selecthost,userfrommysql.user;
TESTOUTPUT
VIVAQUESTIONS
1. WhatareDCLcommands?
2. ListouttheusesofvariousDCLcommands?
3. WhatarethedifferenttypesofCommands inSQL.
4. Whatis thedifferencebetweenTCL &DCLcommands.
5. Whohastheprivilegetoaccess theDCLcommands.
DBMS Page 88
DBMS LAB AY-2024-25
CASESTUDY1
Emp(eid:integer,ename:string,age:integer,salary:real)Works(
eid:integer,did:integer,pcttime:integer)
Dept(did:integer,dname:string,budget:real,managerid:integer)
1. GiveanexampleofaforeignkeyconstraintthatinvolvestheDeptrelation.Whataretheoptions
forenforcingthisconstraintwhenauserattemptstodeleteaDepttuple?
appropriateversionsofallprimaryandforeignkeyintegrityconstraints.
3. DefinetheDeptrelationinSQLsothateverydepartmentisguaranteedtohaveamanage
r.
4. WriteanSQLstatementtoadd`JohnDoe'asanemployeewitheid=101,age=32and
salary=15;000.
5. WriteanSQLstatementtogiveeveryemployeea10%raise.
6. WriteanSQLstatementtodeletethe`Toy'department.Giventhereferentialintegrityconstraint
s you chose for this schema, explain what happens when this statement isexecuted.
DBMS Page 89
DBMS LAB AY-2024-25
CASESTUDY2
Suppliers(sid:integer,sname:string,address:string)Pa
real)Relational AlgebraandCalculus117
The key fields are underlined, and the domain of each field is listed after the field
for Catalog. The Catalog relation lists the prices charged for parts by Suppliers.
Writethefollowingqueriesinrelationalalgebra,tuplerelationalcalculus,anddomainrelationalc
alculus:
1. Findthenamesofsupplierswhosupplysomeredpart.
2. Findthesidsofsupplierswhosupplysomeredorgreenpart.
3. Findthenumberofpartswhosenamehas5letters.
4. Findthesidsofsupplierswhosupplyatleast3parts.
5. Findthesidsofsupplierswhosupplyeverypart.
DBMS Page 90
DBMS LAB AY-2024-25
6. Findthesidsofsupplierswhosupplyeveryredpart.
7. Findthesidsofsupplierswhosupplyeveryredorgreenpart.
8. Findthesidsofsupplierswhosupplyeveryredpartorsupplyeverygreenpart.
9. Findpairsofsidssuchthatthesupplierwiththefirstsid
chargesmoreforsomepartthanthesupplierwiththesecondsid.
10. Findthepidsofpartsthataresuppliedbyatleasttwodifferentsuppliers.
11. Findthesidofsupplierwhosupplycostliestpart.
12. Findthepidsofpartssuppliedbyeverysupplieratlessthan$200.(Ifanysuppliereitherdoesnotsuppl
ythepartorchargesmorethan$200forit,thepartisnotselected.)
DBMS Page 91
DBMS LAB AY-2024-25
CASESTUDY3
Considerthefollowingrelationscontainingairlineflightinformation:Flig
hts(flno:integer,from:string,to:string,
distance:integer,departs:time,arrives:time)
Aircraft(aid:integer,aname:string,cruisingrange:integer)Certified(eid:int
eger,aid:integer)
Employees(eid:integer,ename:string,salary:integer)
Note that the Employees relation describes pilots and other kinds of employees as well; everypilot
is certified for some aircraft (otherwise, he or she would not qualify as a pilot), and
onlypilotsarecertified tofly.
calculus.
1. FindtheeidsofpilotscertifiedforsomeBoeing aircraft.
2. FindthenamesofpilotscertifiedforsomeBoeingaircraft.
3. Findtheaidsofallaircraftthatcanbeusedonnon-stopflightsfromBonntoMadras.
4. Identifytheflightsthatcanbepilotedbyeverypilotwhosesalaryismorethan$100,000.
DBMS Page 92
DBMS LAB AY-2024-25
(Hint:Thepilotmustbecertifiedforatleastoneplanewithasufficientlylargecruisingrange.)
5. Findthenamesofpilotswhocanoperatesomeplanewitharangegreaterthan3,000milesbutare
notcertifiedonanyBoeingaircraft.
6. Findtheeidsofemployeeswhomakethehighestsalary.
7. Findtheeidsofemployeeswhomakethesecondhighestsalary.
8. Findtheeidsofpilotswhoarecertifiedforthelargestnumberofaircraft.
9. Findtheeidsofemployeeswhoarecertifiedforexactlythreeaircraft.
10. Findthetotalamountpaidtoemployeesassalaries.
flightmustleaveMadison,thelastflightmustreachTimbuktu,andthereis
norestrictiononthenumberofintermediateflights.Yourquerymustdeterminewhetherasequence
DBMS Page 93