0% found this document useful (0 votes)
18 views

CSIT_(R22)_3-1_DATABASE MANAGEMENT SYSTEMS_LAB MANUAL

The document is a laboratory manual for a Database Management Systems course at Mallareddy College of Engineering & Technology, detailing the curriculum and educational objectives for B.Tech students. It outlines the vision, mission, program educational objectives, and program specific outcomes, along with an index of topics covered in the lab sessions. Key topics include various database models, normalization, SQL commands, and the introduction to Oracle as a relational database management system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

CSIT_(R22)_3-1_DATABASE MANAGEMENT SYSTEMS_LAB MANUAL

The document is a laboratory manual for a Database Management Systems course at Mallareddy College of Engineering & Technology, detailing the curriculum and educational objectives for B.Tech students. It outlines the vision, mission, program educational objectives, and program specific outcomes, along with an index of topics covered in the lab sessions. Key topics include various database models, normalization, SQL commands, and the introduction to Oracle as a relational database management system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

DEPARTMENT OF COMPUTER SCIENCE &

INFORMATION TECHNOLOGY
DATABASE MANAGEMENT SYSTEMS
(R22A0584)
LABORATORY MANUAL & RECORD

B.TECH

( III YEAR–I SEM) (2024-25)

PREPARED BY
K.SHANTHI

MALLAREDDY COLLEGE OF ENGINEERING &


TECHNOLOGY
(AutonomousInstitution–UGC,Govt.ofIndia)
Recognizedunder2(f)and12(B) of UGCACT1956
(AffiliatedtoJNTUH,Hyderabad,ApprovedbyAICTE-AccreditedbyNBA&NAAC–‘A’Grade-ISO9001:2015Certified)
Maisammaguda,Dhulapally(PostVia.Hakimpet),Secunderabad–500100,TelanganaState,India
DEPARTMENT OF COMPUTER SCIENCE & INFORMATION TECHNOLOGY

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.

Concept design with E-R Model: Apply cardinalities for each 17


relationship, identify strong entities and weak entities for relationships
like generalization, aggregation, specialization.

Relation Model: Represent attributes as columns in tables and


3 19
different types of attributes like Composite, Multi-valued, and Derived.

Normalization
4 23

Installation of My Sql and MONGO DB.


5 26&34

Practicing DML commands


6 39
SELECT, INSERT, UPDATE, DELETE.
Querying
7 52
Queries using ANY, ALL, IN, INTERSECT, UNION
Querying
8 69
Using aggregate functions COUNT, SUM using
GROUPBYand HAVING.
Querying
9 69
Using aggregate functions AVERAGE using GROUP
BY and HAVING
TRIGGER
10 77

Procedures
11 82
Creation, Execution and Modification of stored Procedure

Stored Procedures &Pl/SQL


12 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-

Childrelationship. Closely related information in the parent-child structure is stored together as a

logicalunit.Aparentunitmayhavemanychildunits,butachildisrestrictedtohaveonlyoneparent.

The draw back softhismodelare:


The hierarchical structure is not flexible to represent all the relationship

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.

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
thedataelements.

RelationalModel

Does not maintain physical connection between


relationsDataisorganizedintermsofrowsandcolumnsinatable

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)

One to Many or Many to One (1:M / M:


1) Many to Many(M:M)

TheDegreeofRelationshipindicatesthelinkbetweentwoentitiesforaspecifiedoccurrenceofeach.

DEPARTMENT--CSE Page 2
DBMS LAB AY-2024-25

One to One Relationship:


(1:1)11

StudentHasRollNo.
One studenthasonlyone Rollno. Forone occurrenceofthefirstentity,
therecanbe,atthemostonerelatedoccurrenceof thesecondentity,andvice-versa.

One to Many or Many to One Relationship: (1:M/M:

1)1M

Course Contains Students


As per the Institutions Norm, One student can enroll in one course at a time however, in one
course, there can be more than one student.

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.

Many to Many Relationships:


(M:M)MM

Students Appears Tests

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.

Oraclehas introduced added functionality to this by incorporated object-oriented capabilities. Now


it is known is as Object Relational Database Management System (ORDBMS). Object-
orientedconceptisaddedinOracle8.

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.

3. The Systematic Treatment of NullValues


The RDBMS must be taken care of null values to represent missing or in
applicable information.

4. The Database Description Rule


A description of database is maintained using the same logical structures withwhich

data was defined by the RDBMS.


5. Comprehensive Data Sublanguage

According to the rule the system must support data definition, view definition, data
manipulation, integrity constraints, authorization and transaction management
operations.

6. The View Updating Rule


All views that are theoretically updatable are also updatable by the system.

7. The Insert and Update Rule


This rule indicates that all the data manipulation commands must beoperational on

sets of rows having a relation rather than on a single row.

8. The Physical Independence Rule


Application programs must remain un impaired when any changes are made in
storage representation or access methods.

9. The Logical Data Independence Rule

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.

10. The Integrity Independence Rule


The integrity constraints should store in the system catalog or in the database.
11. The Distribution Rule
The system must be access or manipulate the data that is distributed in other systems.

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

any integrity constraints defined in the higher level.

Object Relational Database Management System


Oracle8 and later versions are supported object-oriented concepts. A structure once created can be

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

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 client
requests.

Introduction to ORACLE
ORACLE is a powerful RDBMS product that provides efficient and effective solutions for major
database features. This includes:

Large databases and space management


control Many concurrent database
users

High transaction processing performance High


availability

Controlled availability

Industry accepted standards


Manage able security

Database enforced integrity


Client/Server environment

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:

Afront-end oraclient portion


The client executes the database application that accesses data base in formation and interacts with the user.

Aback-end oraserver portion

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

ILLUSTRATION:ROAD WAY TRAVELS


“Roadway Travels” is in business since 1977 with several buses connecting different places in India. Its main
office is located in Hyderabad. The company wants to computerize its operations in the following areas:

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.

Cancellation and modification:

Cancellations are also directly handed at the booking office. Cancellationcharges


will be charged.
Waitlisted tickets that do not get confirmedarefullyrefunded.

DEPARTMENT--CSE Page 7
DBMS LAB AY-2024-25

WEEK-1

AIM:Analyze the problemandcome withthe entitiesinit.


IdentifywhatDatahastobepersistedinthedatabases.
The Followingare theentities:

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

What is SQL and SQL*Plus


Oracle 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
ofdatabaseusedtostoredata.Itstoresdatainformofrowsandcolumns.

SQL*Plusisan Oracletool (specificprogram) whichacceptsSQLcommandsandPL/SQLblocksand


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 o
reports,list columndefinitionsofanytable,accessandcopydatabetweenSQLdatabasesandsend
messages to and accept responses from the user. SQL *Plus is a character based
interactivetool,thatrunsinaGUIenvironment.Itisloadedontheclientmachine.
Tocommunicate withOracle,SQL supportsthefollowingcategoriesofcommands:

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.

DateStores dates fromJanuary1,4712B.C.toDecember31,4712A.D.Oracle


predefineformatofDatedatatypeisDD-MON-YYYY.

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.

CLOB A Character Large Object containing fixed-width multi-byte

characters.Varying-
widthcharactersetsarenotsupported.Maximumsizeis4GB.

NCLOB A National Character Large Object containing fixed-width multi-


bytecharacters.

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

BusNo varchar2(10) PrimaryKey

Source varchar2(20)

Destination varchar2(20)

CouchType varchar2(20)

DBMS Page 14
DBMS LAB AY-2024-25

Reservation:
COLUMNNAME DATATYPE CONSTRAINT

PNRNo number(9) PrimaryKey

Journeydate Date

No-of-seats integer(8)

Address varchar2(50)

ContactNo Number(9) Shouldbeequalto10


numbersandnotallow
otherthannumeric
BusNo varchar2(10) Foreignkey
Seatno Number

Ticket:
COLUMNNAME DATATYPE CONSTRAINT

Ticket_No number(9) PrimaryKey


Journeydate Date
Age int(4)
Sex Char(10)
Source varchar2(10)
Destination varchar2(10)
Dep-time varchar2(10)
BusNo Number2(10)

DBMS Page 15
DBMS LAB AY-2024-25

Passenger:

COLUMNNAME DATATYPE CONSTRAINT

PNRNo Number(9) PrimaryKey

TicketNo Number(9) Foreignkey

Name varchar2(15)
Age integer(4)
Sex char(10) (Male/Female)
Contactno Number(9) Shouldbeequalto10numbers
andnotallowotherthan
numeric

Cancellation:
COLUMNNAME DATATYPE CONSTRAINT

PNRNo Number(9) Foriegn-key

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

Date of journey Reservation

Sex

Ticket no Ticket Source

Departure time Age

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:

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 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

Name Age Sex Address Passport


ID

Note: The student is required to submit a document byRepresent relationships in a tabular fashion to
the lab teacher.

2. Concept design with E-R model

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”.

E-R diagram: An entity-relationship(ER) diagram is a specified graphic that illustrates the


interrelationships between entities and database. W e can express the overall logical structure of
database graphically with an E-R diagram.

3. Relational Model and Normalization

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.

Different types of keys:

➢ 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.”

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 the same data in more
than one table) and ensuring data dependencies make sense(only storing related data in a tablet). Both of
these are worthy goals as they reduce the amt of space a database consumes and ensure that data is
logically stores.
The Normal Form: the database community has developed a series of guidelines for ensuring that
databases are normalized. These are referred to as normal forms and are numbered from one ( the lowest
form to normalization, referred to as first form or INF) through five(fifth normal form of SNF). In practical
applications, you’ll often see INF, 2NF, and 3NF along with occasional 4NF. Fifth normal form is very
rarely seen and won’t be discussed in this article. It’s important to point out that they are guidelines and
guidelines only. Occasionally, it becomes necessary to stray from them to meet practical business
requirements. However, when variations take place, it’s extremely important to evaluate any possible
requirements they could have on your system and account for possible inconsistencies. That said, let’s
explore the normal form.

DBMS Page 21
DBMS LAB AY-2024-25

VIVA QUESTIONS

1. What is relational model and its importance.


2. Explain the difference between candidate keyand primary key.
3. What is a super key.
4. Differentiate among all types of keys with example.
5. Explain the need of foreign key.

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

Tr. ID Date Amount


12907 15-Oct-2003 −18
Stevens
14920 20-Nov-2003 −70
15003 27-Nov-2003 −60

DBMS Page 23
DBMS LAB AY-2024-25

To each customer corresponds a repeating group of transactions. The automated evaluation


of any queryrelating to customers' transactions therefore would broadly involve two stages:

1. Unpacking one or more customers' groups of transactions allowing the individual


transactions ina group to be examined, and
2. Deriving a queryresult based on the results of the first stage

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:

Customer Tr. ID Date Amount


Jones 12890 14-Oct-2003 −87
Jones 12904 15-Oct-2003 −50
Wilkins 12898 14-Oct-2003 −21
Stevens 12907 15-Oct-2003 −18
Stevens 14920 20-Nov-2003 −70
Stevens 15003 27-Nov-2003 −60

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

1. Explain the need of normalization?


2. What is functional dependency?
3. Explain difference between third normal form and boyce codd normal form?
4. What is PJNF?
5. What is transitivity dependency?

DBMS Page 25
DBMS LAB AY-2024-25

WEEK-5(a)

AIM:Installation of My SQL and practicing DDL & DMLcommands.

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

This wizard is ready to begin installation. Destination folder will be in


C:\ProgramFiles\MySQL\MySQLServer5.0\.Tocontinue,clicknext.

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

Navigate to the download site:

Navigate to the official MongoDB website https://www.mongodb.com/

Cross-check the Specifications and Download MongoDB

Under the Software section, click on the Community server version.

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.

Create an Environment Variable:

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

Execute the Mongo App:

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

The mongo server is then generated and is up and running.

Verify the Setup

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:

• Create table command


• Alter table command
• Truncate table command
• Drop table command

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:

SYNTAX: ALTER TABLE <TABLE NAME>ADD (<NEW


COLUMNNAME><DATATYPE>(<SIZE>),<NEWCOLUMNNAME><
DATATYPE>(<SIZE>) ............ );
EX:(WriteyourownQuery)

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;

An expression consists of either a constant (new value), an arithmetic or


stringoperation oranSQL query. Note that the new valueto assign to
<column>mustmatchingdatatype.

An update statement used without a where clause results in changing


respectiveattributesofalltuplesin thespecifiedtable.

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

TICKET TICKET_NO Number - 9 0 1 - - -

JOURNEY_DATE Date 7 - - - - -

AGE Number - 4 0 - - -

SEX Char 10 - - - - -

SOURCE Varchar2 50 - - - - -

DEP_TIME Varchar2 50 - - - - -

Inserting records into “TICKET” table

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');

insert into TICKET values(1213,'10/FEB/11',19,'FEMALE','HYDERABAD','10.30AM');

insert into TICKET values(1201,'13/FEB/11',20,'FEMALE','HYDERABAD','11.30AM');

insert into TICKET values(1202,'14/FEB/11',20,'MALE','TIRUPATHI','11.00 AM'); insert into TICKET

values(1205,'14/FEB/11',20,'MALE','HYDERABAD','11.00 AM');

Display table

Syntax

Select <select list> from <table name>

Query

DBMS Page 53
DBMS LAB AY-2024-25

select * from TICKET;

Output

TICKET_NO JOURNEY_DATE AGE SEX SOURCE DEP_TIME


1203 10-FEB-11 19 MALE HYDERABAD 10.30 AM
1
1
1
1

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

213 10-FEB-11 19 FEMALE HYDERABAD 10.30 AM


201 13-FEB-11 20 FEMALE HYDERABAD 11.30 AM
202 14-FEB-11 20 MALE TIRUPATHI 11.00 AM
205 14-FEB-11 20 MALE HYDERABAD 11.00 AM

DBMS Page 55
DBMS LAB AY-2024-25
Com me

Table Column Data Type Length Precision Scale Primary Nullabl Defau
Key e lt

PASSENGER_TICKE PPNO Varchar2 15 - - 1 - - -


TS

TICKET_NO Number - 9 0 - - -

DBMS Page 55
DBMS LAB AY-2024-25

Inserting records into “PASSENGER_TICKETS” table

Syntax
Insert into <table name> values (val 1,val2,val3)

Query
insert into PASSENGER_TICKETS values(1,1203); insert into

PASSENGER_TICKETS values(2,1213); insert into


PASSENGER_TICKETS values(3,1201); insert into
PASSENGER_TICKETS values(4,1202); insert into

PASSENGER_TICKETS values(5,1205);Display table

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

➔ FOREIGN KEY(PNR_NO ) REFERENCES PASSENGER_TICKECTS(PPNO);

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 - - -

Inserting records into “reservation” table

Syntax
Insert into <table name> values (val 1,val2,val3)

57

DBMS Page 57
DBMS LAB AY-2024-25

➔ FOREIGN KEY(PNR_NO ) REFERENCES PASSENGER_TICKECTS(PPNO);

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

Inserting records into “reservation” table

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

reservation values(1,'11/feb/11',8,'amberpet','7416944004','yes'); insert into reservation

values(2,'11/feb/11',8,'b.b nagar','7207204221','yes'); insert into reservation

values(2,'14/feb/11',2,'b.b nagar','7207204221','yes'); insert into reservation

values(3,'14/feb/11',3,'ecil','00000000','yes');

insert into reservation values(4,'14/feb/11',4,'nagaram','9700135300','yes'); insert into

reservation values(5,'16/feb/11',1,'b.b nagar','8143528258','yes'); insert into reservation

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

PNR_NO JOURNEY_DATE NO_OF_SEATS ADDRESS CONTACT_NO STATUS


1 10-FEB-11 5 amberpet 7416944004 yes
1 11-FEB-11 8 amberpet 7416944004 yes
2 11-FEB-11 8 b.b nagar 7207204221 yes
2 14-FEB-11 2 b.b nagar 7207204221 yes
3 14-FEB-11 3 ecil 0 yes
4 14-FEB-11 4 nagaram 9700135300 yes
5 16-FEB-11 1 b.b nagar 8143528258 yes
5 15-FEB-11 7 b.b nagar 8143528258 yes

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)

➔ FOREIGN KEY(PNR_NO ) REFERENCES PASSENGER_TICKECTS(PPNO);

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

Inserting records into “CANCELLATION” table

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

cancellation values(1,'11/feb/11',8,'amberpet','7416944004','yes'); insert into cancellation

values(2,'11/feb/11',8,'b.b nagar','7207204221','yes'); insert into cancellation


values(2,'14/feb/11',2,'b.b nagar','7207204221','yes'); insert into cancellation

values(3,'14/feb/11',3,'ecil','00000000','yes');

insert into cancellation values(4,'14/feb/11',4,'nagaram','9700135300','yes'); insert into

cancellation values(5,'16/feb/11',1,'b.b nagar','8143528258','yes'); insert into cancellation

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

PNR_NO JOURNEY_DATE NO_OF_SEATS ADDRESS CONTACT_NO STATUS


1 10-FEB-11 5 amberpet 7416944004 yes
1 11-FEB-11 8 amberpet 7416944004 yes
2 11-FEB-11 8 b.b nagar 7207204221 yes
2 14-FEB-11 2 b.b nagar 7207204221 yes
3 14-FEB-11 3 ecil 0 yes

DBMS Page 62
DBMS LAB AY-2024-25

4 14-FEB-11 4 nagaram 9700135300 yes


5 16-FEB-11 1 b.b nagar 8143528258 yes
5 15-FEB-11 7 b.b nagar 8143528258 yes

26. Write a trigger on passenger to display messages ‘1 Record is inserted’, ‘1 record is


deleted’, ‘1 record is updated’ when insertion, deletion and updation are done on
passenger respectively.

27. Display unique PNR_NO of all passengers.

Query
select distinct(pnr_no) from reservation;

Output

PNR_NO

28. Display all the names of male passengers.

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

32. Display all the passengers names beginning with ‘A’.

Query
select name from passenger where name like 'A%';

Output

NAME
AMULY
A
AVS.RAV
I

33. Display the sorted list of passengers names.

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

select * from passenger p1,cancellation c1 where p1.ppno=c1.pnr_no

DBMS Page 65
DBMS LAB AY-2024-25

Output

PP NAME A SEX ADDR PNR_ JO U R NE Y _ NO_OF_S ADDR CONTAC STAT


NO GE ESS NO DATE EATS ESS T_NO US
1 TIRUMA 19 MAL AMBER 1 10-FEB-11 5 amberpe 7416944004 yes
LAY E PET t
1 TIRUMA 19 MAL AMBER 1 11-FEB-11 8 amberpe 7416944004 yes
LAY E PET t
2 SUPRIY 20 FEMA B.B 2 11-FEB-11 8 b.b 7207204221 yes
A LE NAGAR nagar
2 SUPRIY 20 FEMA B.B 2 14-FEB-11 2 b.b 7207204221 yes
A LE NAGAR nagar
3 AMULY 20 FEMA ECIL 3 14-FEB-11 3 ecil 0 yes
A LE
NAGAR 20 MAL NAGAR 4 14-FEB-11 4 nagaram 9700135300 yes
AJU E AM
5 AVS.RA 20 MAL B.B 5 15-FEB-11 7 b.b 8143528258 yes
VI E NAGAR nagar
5 AVS.RA 20 MAL B.B 5 16-FEB-11 1 b.b 8143528258 yes
VI E NAGAR nagar

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

36. Find the distinct PNR numbers that are present.

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

38. Find the total number of cancelled seats.

Query
select sum(no_of_seats) from cancellation;

Output

SUM(NO_OF_SEATS)
38

DBMS Page 67
DBMS LAB AY-2024-25

VIVA QUESTIONS

1. What is the syntax for create command?

2. What is the difference between primary key and foreign key?

3. What is the command to display data from a table?

4. What are the types of clause used in mysql ?

DBMS Page 68
DBMS LAB AY-2024-25

WEEK 8 & 9:

Querying Using Aggregate functions (COUNT, SUM, AVERAGE using GROUPBY


and HAVING) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and
MIN), GROUP BY, HAVING and Creation and dropping of Views.
Objectives:

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.

Syntax: COUNT (Column name)

Example: SELECT COUNT (Sal) FROM emp;

2. SUM: SUM followed by a column name returns the sum of all the values in that
column.

Syntax: SUM (Column name)

Example: SELECT SUM (Sal) From emp;

3. AVG: AVG followed by a column name returns the average value of that column
values.

DBMS Page 69
DBMS LAB AY-2024-25

Syntax: AVG (n1,n2..)

Example: Select AVG(10, 15, 30) FROM DUAL;

4. MAX: MAX followed by a column name returns the maximum value of that column.

Syntax: MAX (Column name)

Example: SELECT MAX (Sal) FROM emp; SQL> select

deptno,max(sal) from emp group bydeptno;

DEPTNO MAX(SAL)

10 5000
20 3000
30 2850

SQL> select deptno,max(sal) from emp group by deptno having max(sal)<3000;DEPTNO


MAX(SAL)

30 2850

5. MIN: MIN followed by column name returns the minimum value of that column.

Syntax: MIN (Column name)

Example: SELECT MIN (Sal) FROM emp;

SQL>select deptno,min(sal) from emp group bydeptno having min(sal)>1000;DEPTNO

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.

Syntax: CREATE VIEW view_name AS SELECT set of fields FROM


relation_name WHERE (Condition)

1. Example:
SQL>CREATE VIEW employee AS SELECT empno,ename,job FROM EMPWHERE job =

‘clerk’;

View created.

SQL> SELECT * FROM EMPLOYEE; EMPNO

ENAME JOB

7369 SMITH CLERK

7876 ADAMS CLERK


7900 JAMES CLERK
7934 MILLER CLERK

DBMS Page 71
DBMS LAB AY-2024-25

2. Example:

CREATE VIEW [Current Product List] ASSELECT


ProductID,ProductName
FROM Products
WHERE Discontinued=No

DROP VIEW: This query is used to delete a view , which has been already created.

Syntax: DROP VIEW View_name;

Example : SQL> DROP VIEW EMPLOYEE;

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)

1. Conversion functions:To_char: TO_CHAR (number) converts n to a value


of VARCHAR2 data type, using the optional number format fmt. The value n can
be of type NUMBER, BINARY_FLOAT, or BINARY_DOUBLE.

SQL>select to_char(65,'RN')from dual;

To_number : TO_NUMBER converts expr to a value of NUMBER data type.

SQL> Select to_number('1234.64') from Dual;1234.64

To_date:TO_DATE converts char of CHAR, VARCHAR2, NCHAR,or


NVARCHAR2 data type to a value of DATE data type.

DBMS Page 72
DBMS LAB AY-2024-25

SQL>SELECT TO_DATE('January 15, 1989, 11:00 A.M.')FROM DUAL;TO_DATE('

15-JAN-89

2. String functions:

Concat: CONCAT returns char1 concatenated with char2. Both char1 and char2 can beany of the datatypes

SQL>SELECT CONCAT(‘ORACLE’,’CORPORATION’)FROM DUAL;

ORACLECORPORATION

Lpad: LPAD returns expr1, left-padded to length n characters with the sequence ofcharacters in expr2.

SQL>SELECT LPAD(‘ORACLE’,15,’*’)FROM DUAL;**********ORACLE

Rpad: RPAD returns expr1, right-padded to length n characters with expr2, replicated asmany times as
necessary.

SQL>SELECT RPAD (‘ORACLE’,15,’*’)FROM DUAL;

ORACLE*********

Ltrim: Returns a character expression after removing leading blanks.

SQL>SELECT LTRIM(‘SSMITHSS’,’S’)FROM DUAL;MITHSS

Rtrim: Returns a character string after truncating all trailing blanks

SQL>SELECT RTRIM(‘SSMITHSS’,’S’)FROM DUAL;SSMITH

DBMS Page 73
DBMS LAB AY-2024-25

Lower: Returns a character expression after converting uppercase character data tolowercase.

SQL>SELECT LOWER(‘DBMS’)FROM DUAL;

dbms

Upper: Returns a character expression with lowercase character data converted to uppercase

SQL>SELECT UPPER(‘dbms’)FROM DUAL;DBMS

Length: Returns the number of characters, rather than the number of bytes, of thegiven string
expression, excluding trailing blanks.

SQL>SELECT LENGTH(‘DATABASE’)FROM DUAL;8

Substr: Returns part of a character, binary, text, or image expression.

SQL>SELECT SUBSTR(‘ABCDEFGHIJ’3,4)FROM DUAL;CDEF

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.

SQL>SELECT INSTR('CORPORATE FLOOR','OR',3,2)FROM DUAL;14

3. Date functions:
Sysdate: SQL>SELECT SYSDATE FROM DUAL;29-DEC-08

DBMS Page 74
DBMS LAB AY-2024-25

next_day:

SQL>SELECT NEXT_DAY(SYSDATE,’WED’)FROM DUAL;05-JAN-09

add_months:

SQL>SELECT ADD_MONTHS(SYSDATE,2)FROM DUAL;28-FEB-09

last_day:

SQL>SELECT LAST_DAY(SYSDATE)FROM DUAL;31-DEC-08

months_between:

SQL>SELECT MONTHS_BETWEEN(SYSDATE,HIREDATE)FROM EMP; 4

Least:

SQL>SELECT LEAST('10-JAN-07','12-OCT-07')FROM DUAL;10-JAN-07

Greatest:

SQL>SELECT GREATEST('10-JAN-07','12-OCT-07')FROM DUAL;10-JAN-07

Trunc:

SQL>SELECT TRUNC(SYSDATE,'DAY')FROM DUAL;28-DEC-08

DBMS Page 75
DBMS LAB AY-2024-25

Round:

SQL>SELECT ROUND(SYSDATE,'DAY')FROM

DUAL;28-DEC-08

to_char:

SQL> select to_char(sysdate, "dd\mm\yy") from

dual;24-mar-05.

to_date:

SQL> select to_date(sysdate, "dd\mm\yy") from


dual;24-mar-o5.

VIVA QUESTIONS

1. What are aggregate functions?

2. What is the difference between LPAD and RPAD?

3. Define View?

4. What is the difference between group by and order by clause?

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.

A database trigger is procedural code that is automatically executed in response to certainevents


on a particular table orview in a database. The trigger is mostly used for maintainingtheintegrity
oftheinformationon thedatabase.

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

CREATE TRIGGER sal_sum after insert ON


empFOREACHROWSET@sal=@sal+NEW.sal;
TESTOUTPUT

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

Procedures: Creation of stored procedures, Execution of procedure and modification of


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.

CREATE PROCEDURE myProc()BEGIN

SELECT COUNT (Tickets) FROM Ticket WHERE age>=40;End;

Procedures created

SQL>CREATE PROCEDURE myproc(in_customer_id INT)BEGIN

DECLARE v_id INT;

DECLARE v_name VARCHAR(30);

DECLARE c1 CURSOR FOR SELECT stdId,stdFirstnameFROM students

WHERE stdId=in_customer_id;

OPEN c1;

FETCH c1 into v_id, v_name;Close


c1;

End;

PL/SQL procedure successfully completed.

DBMS Page 82
DBMS LAB AY-2024-25

PL/SQL

PL/SQLprogramsarewrittenaslinesoftextusingaspecificsetofcharacters:

• Upper-andlower-caselettersA..Zanda..z
• Numerals0..9
• Symbols()+-*/<>=!~^;:. '@%, "#$&_|{}?[]
• Tabs,spaces,andcarriagereturns

PL/SQL keywords arenotcase-sensitive,so lower-caseletters areequivalent tocorrespondingupper-


caselettersexceptwithinstringandcharacterliterals.

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;

1) WRITEA PROGRAM TOPRINTHELLO


WORLDBEGIN
DBMS_OUTPUT.PUT_LINE('HELLOWORLD');EN
D;

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?

2. Write theSQLstatementsrequired tocreate the above relations,including

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

rts(pid: integer, pname: string, color:

string)Catalog(sid: integer, pid: integer, cost:

real)Relational AlgebraandCalculus117

The key fields are underlined, and the domain of each field is listed after the field

name.Thussidisthekeyfor Suppliers,pidisthekeyfor Parts,andsidandpidtogetherformthekey

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.

Write thefollowingqueriesin relational algebra, tuple relationalcalculus, anddomainrelational

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.

11. Istherea sequenceofflightsfromMadisontoTimbuktu?Eachflight


inthesequenceisrequiredtodepartfromthecitythatisthedestinationofthepreviousflight;thefirst

flightmustleaveMadison,thelastflightmustreachTimbuktu,andthereis

norestrictiononthenumberofintermediateflights.Yourquerymustdeterminewhetherasequence

DBMS Page 93

You might also like