You are on page 1of 47

MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY

( Approved by AICTE, Affiliated to JNTU, Hyd)


Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

CS407PC: DATABASE MANAGEMENT SYSTEM LAB

B.TECH II Year II Sem. L T PC 0 0 3 1.5


Co-requisites:
 Co-requisite of course “Database Management Systems”
Course Objectives:
 Introduce ER data model, database design and normalization
 Learn SQL basics for data definition and data manipulation
Course Outcomes:
 Design database schema for a given application and apply normalization
 Acquire skills in using SQL commands for data definition and data
manipulation.
 Develop solutions for database applications using procedures, cursors and
triggers

LIST OF EXPERIMENTS:
1. Concept design with E-R Model
2. Relational Model
3. Normalization
4. Practicing DDL commands
5. Practicing DML commands
6. Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION, INTERSECT,
Constraints etc.)
7. Queries using Aggregate functions, GROUP BY, HAVING and Creation and dropping
of Views.
8. Triggers (Creation of insert trigger, delete trigger, update trigger)
9. Procedures
10. Usage of Cursors

DATABASE MANAGEMENT SYSTEM Page 1


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

TEXT BOOKS:
1. Database Management Systems, Raghurama Krishnan, Johannes Gehrke, Tata Mc Graw
Hill, 3rd Edition
2. Database System Concepts, Silberschatz, Korth, McGraw Hill, V edition.

REFERENCES BOOKS:
1. Database Systems design, Implementation, and Management, Peter Rob & Carlos
Coronel 7th Edition.
2. Fundamentals of Database Systems, Elmasri Navrate, Pearson Education
3. Introduction to Database Systems, C.J. Date, Pearson Education
4. Oracle for Professionals, The X Team, S. Shah and V. Shah, SPD.
5. Database Systems Using Oracle: A Simplified guide to SQL and PL/SQL, Shah, PHI.
6. Fundamentals of Database Management Systems, M. L. Gillenson, Wiley Student
Edition.

DATABASE MANAGEMENT SYSTEM Page 2


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

VISION OF THE INSTITUTE:


To be a Centre of Excellence in technical education with research orientation and to
develop Human resources to serve the society and nation building.

MISSION OF THE INSTITUTE:


M1:To provide comprehensive technical education programmes in various disciplines
and to contribute effectively to the profession and the society.
M2: Establishing Centers of Excellence in- inter disciplinary areas which are important
and relevant to Industry and Employment with scope for research
M3: To inculcate human values and ethical practices to the graduates through co- curricular
and Extra-curricular activities.

VISION OF THE DEPARTMENT:


To impart technical education with latest art of technology with scope for research and
development and groom the students with leadership skill to suit the challenging needs
industry and society.

MISSION OF THE DEPARTMENT:


Provide contemporary technical education programs, in the field of IT and prepare for
competitive employment and higher studies.Provide comprehensive in depth knowledge
with research orientation which are important and relevant to industry, society,
environment and global needs.Organize specific programs to inculcate values and ethical
practices to the students through co-curricular and extracurricular activities.

DATABASE MANAGEMENT SYSTEM Page 3


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

PROGRAMME EDUCATIONAL OBJECTIVES (PEO’s)


1. Core Capabilities/Competence: Impart profound knowledge in humanities and
basic sciences along with core engineering concepts for practical understanding &
project development.[PO’s: 1,2,3,4,5,7,8,9,10,11 and 12] [PSO’s: 1 and 2]

2. Career Advancement: Enrich analytical skills and Industry-based modern


technical skills in core and interdisciplinary areas for accomplishing research,
higher education, entrepreneurship and to succeed in various engineering positions
globally. [PO’s: 1,2,3,4,5,6,7,8,9,10 and 12] [PSO’s: 1, 2 and 3]

3. Life-Long Learning: Infuse life-long learning, professional ethics, responsibilities


and adaptation to innovation along with effective communication skills with a sense
of social awareness. [PO’s: 1,2,3,4,5,6,7,8,9,10,11 and 12] [PSO’s: 2 and 3]

II. PROGRAMME OUTCOMES (PO’s)


1. Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems. [PEO’s: 1,2 and 3] [PSO’s: 1,2 and 3]

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. [PEO’s: 1,2
and 3] [PSO’s: 1,2 and 3]

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. [PEO’s: 1,2 and 3] [PSO’s: 1,2 and
3]

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. [PEO’s: 1,2
and 3] [PSO’s: 1,2 and 3]

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. [PEO’s: 1,2 and 3]
[PSO’s: 1,2 and 3]

DATABASE MANAGEMENT SYSTEM Page 4


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

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. [PEO’s: 2 and 3]

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. [PEO’s: 1,2 and 3]

8. Ethics: Apply ethical principles and commit to professional ethics and


responsibilities and norms of the engineering practice. [PEO’s: 1,2 and 3] [PSO’s:
2 and 3]

9. Individual and team work: Function effectively as an individual, and as a member


or leader in diverse teams, and in multidisciplinary settings. [PEO’s: 1,2 and 3]
[PSO’s: 3]

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. [PEO’s: 1,2 and 3] [PSO’s:
2 and 3]

11. Project management and finance: Demonstrate knowledge and understanding of


the engineering and management principles and apply these to one’s own work, as
a memberand leader in a team, to manage projects and in multidisciplinary
environments. [PEO’s: 1 and 3] [PSO’s: 2 and 3]

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. [PEO’s: 1,2 and 3] [PSO’s: 1,2 and 3]

DATABASE MANAGEMENT SYSTEM Page 5


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

III. PROGRAMME SPECIFIC OUTCOMES (PSO’s)

1. Use mathematical abstractions and Algorithmic design along with open source
programming tools to solve complexities involved in efficient
programming.[PO:1,2,3,4 and 5] & [PEO:1 and 2]

2. Ensure programming & documentation skills for each individual student in relevant
su
3. bjects i.e., C, C++, Java, DBMS, Web Technologies (Development), Linux, Data
Warehousing & Data Mining and on Testing Tools.[PO:1,2,3,4,5,10 and 11] &
[PEO:1,2 and 3]

4. Ensure employability and career development skills through Industry oriented mini
& major projects, internship, industry visits, seminars and workshops.
[PO:6,7,8,9,10,11 and 12] & [PEO:1,2 and 3]

DATABASE MANAGEMENT SYSTEM Page 6


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

INTRODUCTION

Database Management System


This model is like a hierarchical tree structure, used to construct a hierarchy
of records in the form of nodes and branches. The data elements present in the
structure have Parent-Child relationship. Closely related information in the parent-
child structure is stored together as a logical unit. A parent unit may have many child
units, but a child is restricted to have only one parent.
The drawbacks of this model are:
 The hierarchical structure is not flexible to represent all the relationship
proportions, which occur in the real world.
 It cannot demonstrate the overall data model for the enterprise because of the
non- availability of actual data at the time of designing the data model.
 It cannot represent the Many-to-Many relationship.
Network Model
It supports the One-To-One and One-To-Many types only. The basic objects in
this model are Data Items, Data Aggregates, Records and Sets.
It is an improvement on the Hierarchical Model. Here multiple parent-child
relationships are used. Rapid and easy access to data is possible in this model
due to multiple access paths to the data elements.
Relational Model
 Does not maintain physical connection between relations
 Data is organized in terms of rows and columns in a table
 The position of a row and/or column in a table is of no importance
 The intersection of a row and column must give a single value
Features of an RDBMS
 The ability to create multiple relations and enter data into them
 An attractive query language
 Retrieval of information stored in more than one table
 An RDBMS product has to satisfy at least Seven of the 12 rules of Codd to be
accepted as a full- fledged RDBMS.
Relational Database Management System
RDBMS is acronym for Relation Database Management System. Dr. E. F. Codd
first introduced the Relational Database Model in 1970. The Relational model allows
data to be represented in a simple row- column. Each data field is considered as a
column and each record is considered as a row. Relational Database is more or less
similar to Database Management System. In relational model there is relation between
their data elements. Data is stored in tables. Tables have columns, rows and names.
Tables can be related to each other if each has a column with a common type of
information. The most famous RDBMS packages are Oracle, Sybase and Informix.
DATABASE MANAGEMENT SYSTEM Page 7
MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

Simple example of Relational model is as follows :


Student Details Table
Roll_no Sname S_Address

1 Rahul Satelite
2 Sachin Ambawad
i
3 Saurav Naranpura
Student Marksheet Table

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 Rollno
column.

Degree of Relationship
 One to One (1:1)
 One to Many or Many to One (1:M / M: 1)
 Many to Many (M: M)
The Degree of Relationship indicates the link between two entities for a specified

occurrence of each.

One to One Relationship :


Student Has Roll No.
One student has only one Rollno. For one occurrence of the first entity, there can
be, at the most one related occurrence of the second entity, and vice-versa.
One to Many or Many to One Relationship:
Course Contains Students

DATABASE MANAGEMENT SYSTEM Page 8


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

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 Relationship:
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.
Oracle has introduced added functionality to this by incorporated object-oriented
capabilities. Now it is known is as Object Relational Database Management System
(ORDBMS). Object- oriented concept is added in Oracle8.
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.
E. F. Codd Rules
1. The Information Rule: All information must be store in table as data values.
2. The Rule of Guaranteed Access: Every item in a table must be logically
addressable with the help of a table name.
3. The Systematic Treatment of Null Values: The RDBMS must be taken care of
null values to represent missing or inapplicable information.
4. The Database Description Rule: A description of database is maintained using
the same logical structures with which data was defined by the RDBMS.
5. Comprehensive Data Sub Language: 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 updateable are also
updateable by the system.
7. The Insert and Update Rule: This rule indicates that all the data manipulation
commands must be operational on sets of rows having a relation rather than on
DATABASE MANAGEMENT SYSTEM Page 9
MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

a single row.
8. The Physical Independence Rule: Application programs must remain
unimpaired 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.
12. The Non-subversion Rule: If a RDBMS supports a lower level language then
it should not bypass 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
 Manageable security
 Database enforced integrity
 Client/Server environment
 Distributed database systems
DATABASE MANAGEMENT SYSTEM Page 10
MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

 Portability
 Compatibility
 Connectivity
An ORACLE database 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:
A front-end or a client portion
The client executes the database application that accesses database information and
interacts with the user.

A back-end or a server portion


The server executes the ORACLE software and handles the functions required

for concurrent, shared data access to ORACLE database.

DATABASE MANAGEMENT SYSTEM Page 11


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT 1
AIM: Concept design with E-R Model
Objectives:

Student will able to learn the Entity-Relationship(ER) modeling to develop a


conceptual model of data. 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


 About business rules, notations and constructs.
 To Construct E-Rdiagrams including: Entities(strong,weak, associative)
Attributes (simple, multi-valued, derived)
Relations (unary, binary, ternary)
 Student gains the ability to describe the data requirements for a new
information system in a direct and easy to understand graphical notation.

Roadway Travels:
Roadway travels is in business since 1997 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.
The company wants to computerize its operations in the following areas:
1. Reservations and Ticketing
2. Cancellations

Reservations & Cancellation:


Reservations are directly handled by booking office. Reservations can be made 30
days in advance and tickets issued to passenger. One passenger/ person can book many
tickets (to his/her family).Cancellations are also directly handed at the booking office.

DATABASE MANAGEMENT SYSTEM Page 12


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

In the process of Computerization of Roadway Travels you have to design and develop
a Database which consists the data of Buses, Passengers, Tickets and Reservation and
cancellation details. You should also develop query‘s using SQL to retrieve the data
from the database.
Following steps are involved in the process:
1. E-R Model
2. Normalised Relational Model
3. Creating the database
4. Querying.
5. Triggers and Stored procedures on the tables.

E-R Model:
An entity-relationship(ER) diagram is a specified graphic that illustrates the
interrelationships between entities and database. We can express the overall logical
structure of database graphically with an E-R diagram.
Analyze the problem carefully and come up with the entities in it. Identify
what data has to be persisted in the database. This contains the entities,
attributes etc. In this we will analyze different types of entities with attributes
of “Roadways Travels”.
Entity: An Entity is an object or concept about which you want to store information
Relationship: A relationship is an association between several entities.
Attributes: An object is characterized by its properties or attributes. In
relational database systems attributes correspond to fields.
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”.
The Road Way Travels Consists of The Following Entities:
 BUS
 Ticket
 Passenger
DATABASE MANAGEMENT SYSTEM Page 13
MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

 Reservation
 Cancellation/modification
These Entities have following attributes

Bus:
 Bus_no
 Bus_source
 Bus_destination
 Bus_totalseats
Ticket:
 Ticket_id
 Ticket_datejourney
 Sex
 Source
 age
 Dep_time
 Destination
Passenger:
 Pnr_no
 Pname
 Pgender
 Page
 Psex
 Ticket_no
Reservation:
 No_of_seats
 PNR_No
 Status
 Contact no
 Journey_date
 Address
Cancellation:
 No_of_seats
 PNR_No
 Status
 Contact no
 Journey_date
 Address

DATABASE MANAGEMENT SYSTEM Page 14


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

ER Diagram

VIVA QUESTIONS:

1) Define Database.
2) What is Data Model?
3) What is E-R model?
4) What is an Entity?
5) What is attribute?
6) What is E-R Diagram?
7) What is row?
8) What are the various kinds of interactions catered by DBMS?
9) What is SQL?
10) What is the difference between primary key and unique constraints?
11) What is composite primary key?
12) What is cardinality?
13) How is weak entity set represented?

DATABASE MANAGEMENT SYSTEM Page 15


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT-2
AIM: Relational Model

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.

RELATIONAL MODEL
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.
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 structure to prevent repeat and redundant data
storage.
Different types of keys:
 A super key is a set of one or more attributes which; taken
collectively, allow us to identify uniquely an entity in the entity
set.
 A primary key is a candidate key(there may be more than one)
chosen by the 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

DATABASE MANAGEMENT SYSTEM Page 16


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

primary key column of another table. The foreign key can be


used to cross-reference tables

The following are tabular representation of the above entities and relationships
Bus:
COLUMN NAME DATA TYPE CONSTRAINT
Bus No varchar2(10) Primary Key
Source varchar2(10)
Destination varchar2(10)
Couch Type varchar2(10)

Reservation:
COLUMN NAME DATA TYPE CONSTRAINT
PNRNo number(9) Primary Key
Journey date Date
No-of-seats integer(8)
Address varchar2(50)
Contact No Number(9)
BusNo varchar2(10) Foreign key
Seat no Number
Ticket:
COLUMN NAME DATA TYPE CONSTRAINT
Ticket_No Number(9) PRIMARY KEY
Journey date Date
Age Int(4)
Sex Char(10)
Source Varchar2(10)
Destination Varchar2(10)
Dep-time Varchar2(10)
Bus No Number(5)

DATABASE MANAGEMENT SYSTEM Page 17


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

Passenger
COLUMN NAME DATA TYPE CONSTRAINT
Pnr no. Number(9) PRIMARY KEY
Ticket no Number(9) FOREIGN KEY
Name varchar2(15)
Age integer(4)
Sex Char(10) Male/ female
Should be to 10 numbers and not
Contact no Number(10)
allow other than numeric

Cancellation
COLUMN NAME DATA TYPE CONSTRAINT
PNR no Number(9) FOREIGN KEY
Journey data Date
Seat no Integer(9)
Should be equal to 10 numbers and
Contact no Number(9)
not allow Other than numeric

VIVA QUESTIONS:
1) What are the data types used in sql?
2) What is varchar used for?
3) What is foreign key? Explain the need of foreign key.
4) What is the difference between char and varchar2 in sql?
5) What are constraints?
6) What is unique key?
7) What is relational model and its importance.
8) Explain the difference between candidate key and primary key.
9) What is a super key.
10) Differentiate among all types of keys with example.

DATABASE MANAGEMENT SYSTEM Page 18


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT- 3
AIM: Normalization

Objectives:
Student will able to learn to avoid problems that are associated with updating redundant
data.

Outcomes:
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 query statistics, where these
statistics are liable to change as time goes by.
For the above table in the First normalization we can remove the multiple valued
attribute Ticket_id and place it in another table along with the primary key of
passenger.
First Normal Form: The above table can have divided into two tables as shown below.
Passenger
Name Age Sex Address Ticket_id Passport ID

Passport ID Ticket_id

DATABASE MANAGEMENT SYSTEM Page 19


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

VIVA QUESTIONS
1. Define Normalization. Enlist the advantages of normalizing database.
2. Enlist the advantages of normalizing database.
3. Explain the need of normalization?
4. What is functional dependency?
5. Explain difference between third normal form and boyce codd normal form?
6. What is PJNF?
7. What is transitivity dependency?
8. Define Denormalization.
9. What is 1 NF (Normal Form)?
10. What is 2NF? What is 4NF?

DATABASE MANAGEMENT SYSTEM Page 20


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT-4
AIM: Practicing DDL commands
Objectives:

Student will able to learn DDL Statements to Create and Manage Tables.
Outcomes:
Student gains the ability to
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
• Create a simple table
• Describe how constraints are created at the time of table creation
• Describe how schema objects work.
Data Definition Language
(DDL)
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 
1) Creating of Tables on ROAD WAY TRAVELS:
Table is a primary object of database, used to store data in form of rows and
columns. It is created using following command:
Create Table<table_name> (column1 datatype(size), column2
datatype(size),column(n) datatype(size));
Where, table_name is a name of the table and coulumn1, column2 _ column n is a
name of the column available in table_name table.
Each column is separated by comma.
Points to be remember while creating a table.
 Table Name must be start with an alphabet.
 Table name and column name should be of maximum 30 character long.
 Column name should not be repeated in same table.
 Reserve words of Oracle cannot be used as a table and column name.
 Two different tables should not have the same name.

DATABASE MANAGEMENT SYSTEM Page 21


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

Underscores, numerals and letters are allowed but not blank space or single
quotes.
Example:
 SQL> create table Bus(Bus_No varchar(5), source varchar(20), destination
varchar(20),CouchType varchar2(10),fair number);
Table Created.
Desc command
Describe command is external command of Oracle. The describe command is used to
view
the structure of a table as follows.
Desc <table name>
SQL> desc bus;
 (PNR_NO Numeric(9), No_of_seats Number(8), Address varchar(50),
Contact_No Numeric(9), Status char(3));
Table created.
 SQL> desc Reservation

Name Null? Type


----------------------------------------- -------- ----------------------------
PNR_NO NUMBER(9)
NO_OF_SEATS NUMBER(8)
ADDRESS VARCHAR2(50)
CONTACT_NO NUMBER(9)
STATUS CHAR(3)
Cancellation Table:
 SQL> create table Cancellation(PNR_NO Numeric(9), No_of_seats
Number(8), Address varchar(50), Contact_No Numeric(9), Status char(3));
Table created.
 SQL> desc Cancellation

Name Null? Type


----------------------------------------- -------- ----------------------------
PNR_NO NUMBER(9)
NO_OF_SEATS NUMBER(8)
ADDRESS VARCHAR2(50)
CONTACT_NO NUMBER(9)
STATUS CHAR(3)
Ticket Table:

DATABASE MANAGEMENT SYSTEM Page 22


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

 SQL> create table Ticket(Ticket_No Numeric(9) primary key, age


number(4), sex char(4) Not null, source varchar(2), destination varchar(20),
dep_time varchar(4));

NAME NULL TYPE


TICKET_NO NOT NULL NUMBER(9)
AGE NUMBER(4)
SEX NOT NULL CHAR(4)
SOURCE VARCHAR2(2)
DESTINATION VARCHAR2(20)
DEP_TIME VARCHAR2(4)

2) Alteration of Table
Once Simple Table is created, if there is a need to change the structure of a table at
that time alter command is used. It is used when a user want to add a new column or
change the width
of datatype or datatype itself or to add or drop integrity constraints or column. (we
will see
about constraints very soon.).i.e. table can be altered in one of three way : by
adding
column, by changing column definition or by dropping column.
i) Addition of Column(s)
Addition of column in table is done using:
Alter table <table_name> add(column1 datatype, column2 datatype);
Add option is used with alter table_ when you want to add a new column in
existing table. If you want to Add more than one column then just write column
name, data type and size in brackets. As usual Comma sign separates each column.
For Example,
suppose you want to add column comm in emp_master, then you have to
perform the following command.
 SQL>ALTER TABLE Passenger ADD FOREIGN KEY (PNR_NO)
REFERENCES Reservation(PNR_NO);
Table altered.
 SQL> ALTER TABLE Cancellation ADD FOREIGN KEY (PNR_NO)
REFERENCES Reservation(PNR_NO);
Table altered.
 SQL> alter table Ticket modify tiketnonumber(10);
Table altered.

DATABASE MANAGEMENT SYSTEM Page 23


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

ii) Deletion of Column


Till Oracle8 it is not possible to remove columns from a table but in Oracle8i,
drop option is used with Alter table_ when you want to drop any existing column.
Alter table <table_name> drop column <column name>;
Using above command you cannot drop more than one column at a time.
For Example, suppose you want to delete just before created column comm from
the emp_master, then you have to apply following command.
SQL>Alter Table Emp_master drop
column comm;
Table altered.
iii) Modification in Column
Modify option is used with Alter table_ when you want to modify any existing
column.If you want to modify data type or size of more than one column then just
write column name, data type and size in brackets and each column is separated by
comma sign as per follows:
Alter table <table name> modify (column1 datatype,・_);
For Example, if you want to change size of salary column of emp_master the
following command is performed.
 SQL> Alter table emp_master modify salary number(9,2);
Table altered.
It will change size of salary column from 7 to (9,2).
When you want to decrease the size of column, table must be empty. If table
has any rows then it will not allow decrement in the column width.
3) Dropping Table
Making a column as Unused_ does not release the space previously used by
the column, until you drop the unused columns. It can be possible using:
Alter table <table_name> drop unused columns;
Once you have marked column as unused_ you cannot access that column
You can drop multiple columns at a time using single command as per
follows
Alter table <table_name> drop (Column1, Column2,_);
The multiple columns name must be enclosed in parentheses.
4) Truncate Table
If there is no further use of records stored in a table and the structure is required
then only data can be deleted using Truncate command. Truncate command will
delete all the records permanently of specified table as follows.
Truncate table <table name> [Reuse Storage];

DATABASE MANAGEMENT SYSTEM Page 24


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

Example
Following command will delete all the records permanently from the table.
SQL>Truncate Table Emp_master;
(Or)
SQL>Truncate Table Emp_master Reuse Storage;
Table truncated.
Alter table <table_name> drop (Column1, Column2,_);
The multiple columns name must be enclosed in parentheses.

VIVA QUESTIONS:
1) What is DDL (Data Definition Language)? Enlist some commands of DDL.
2) What are the different types of statements supported by sql?
3) What are the different clause used in sql?
4) Name any two commands that are used for the purpose of managing the data
present in the database.

DATABASE MANAGEMENT SYSTEM Page 25


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT-5
AIM: Practicing DML commands.

Objectives:
Student will able to learn commands that make changes in relational database and
transaction management.
Outcomes:

Student gains the knowledge to perform transactions like updating, deleting,


inserting and selecting data from a data base.
Data Manipulation Language (DML) :
1) Insert
2) Update
3) Delete

1) Insert
SQL> insert into Passenger
values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex',
'&PPNO');
Enter value for pnr_no: 1
Enter value for ticket_no: 1
Enter value for name: SACHIN
Enter value for age: 12
Enter value for sex: m
Enter value for ppno: sd1234
old 1: insert into Passenger values(&PNR_NO,&TICKET_NO,
'&Name', &Age, '&Sex', '&PPNO')
new1:insert into
Passengervalues(1,1,'SACHIN',12,'m','sd
1234')
1 row created.
SQL> Enter value for pnr_no: 2
Enter value for ticket_no: 2
Enter value for name: rahul

DATABASE MANAGEMENT SYSTEM Page 26


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

Enter value for age: 34


Enter value for sex: m
Enter value for ppno: sd3456

old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name',


&Age, '&Sex', '&PPNO')
new 1: insert into Passenger values(2,2,'rahul',34,'m','sd3456')
1 row created.
SQL> /
Enter value for pnr_no: 3
Enter value for ticket_no: 3
Enter value for name: swetha
Enter value for age: 24
Enter value for sex: f
Enter value for ppno: sdqw34
old 1: insert into Passenger values(&PNR_NO,&TICKET_NO,
'&Name', &Age, '&Sex', '&PPNO')
new 1: insert into Passenger
values(3,3,'swetha',24,'f','sdqw34') 1
row created.
SQL> /
Enter value for pnr_no: 4
Enter value for ticket_no: 4
Enter value for name: ravi
Enter value for age: 56 Enter
value for sex: m
Enter value for ppno: sdqazx
old 1: insert into Passenger values(&PNR_NO,&TICKET_NO,
'&Name', &Age, '&Sex', '&PPNO')
new 1: insert into Passenger values(4,4,'ravi',56,'m','sdqazx')
1 row created.
SQL> /
Enter value for pnr_no: 4
Enter value for ticket_no: 5
Enter value for name: asif
Enter value for age: 33 Enter
value for sex: m Enter value
for ppno: iuyhjk

DATABASE MANAGEMENT SYSTEM Page 27


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

old 1: insert into Passenger values(&PNR_NO,&TICKET_NO,


'&Name', &Age, '&Sex', '&PPNO')
new 1: insert into Passenger values(4,5,'asif',33,'m','iuyhjk')
insert into Passenger values(4,5,'asif',33,'m','iuyhjk')

SQL> select * from Passenger;

PNR_NO TICKET_NO NAME AGE SEX PPNO


---------- ---------- -------------------- ---------- ---------- ---------------
1 1 SACHIN 12 m sd1234
2 2 rahul 34 m sd3456
3 3 swetha 24 f sdqw34
4 4 ravi 56 m sdqazx

2) UPDATE

 SQL> update Passenger set age='43' where PNR_NO='2';


1 row updated.
 SQL>select * from
Passenger;
PNR_NO TICKET_NO NAME AGE SEX PPNO
---------- ---------- -------------------- ---------- ---------- ---------------
1 1 SACHIN 12 m sd1234
2 2 rahul 43 m sd3456
3 3 swetha 24 f sdqw34
4 4 ravi 56 m Sdqazx

3) DELETE
 SQL> delete from Passenger where PNR_NO='4';
1 row deleted.
 SQL> select * from
Passenger;
PNR_NO TICKET_NO NAME AGE SEX PPNO
---------- - --------- -------------------- ---------- ---------- ---------------
1 1 SACHIN 12 m sd1234
2 2 rahul 43 m sd3456
3 3 swetha 24 f sdqw34

DATABASE MANAGEMENT SYSTEM Page 28


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

VIVA QUESTIONS
1. What is the syntax for insert command?
2. Define Key constraint?
3. What is the difference between NULL Values and NOT NULL Values?
4. What is the command to display table?

DATABASE MANAGEMENT SYSTEM Page 29


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT-6
AIM:Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION,
INTERSECT, Constraints etc.)
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.

Display unique PNR_NO of all passengers.


Query
select distinct(pnr_no) from reservation;
Output

PNR_NO
1
3
5
2
4

Display all the names of male passengers.


Query
select name from passenger where sex='MALE'
Output
NAME
TIRUMALAY
NAGARAJU
AVS.RAVI

DATABASE MANAGEMENT SYSTEM Page 30


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

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
Output
NAME TICKET_NO
TIRUMALAY 1203
SUPRIYA 1213
AMULYA 1201
NAGARAJU 1202
AVS.RAVI 1205

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

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

DATABASE MANAGEMENT SYSTEM Page 31


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

Display all the passengers names beginning with ‘A’.


Query
select name from passenger where name like 'A%';
Output
NAME
AMULYA
AVS.RAVI

Display the sorted list of passengers names.


Query
select name from passenger order by name;
Output

NAME
AMULYA
AVS.RAVI
NAGARAJU
SUPRIYA
TIRUMALAY

VIVA QUESTIONS :
1) What are the differences between DDL, DML and DCL in SQL?
2) What is difference between DELETE & TRUNCATE commands?
3) What is ordered by clause?
4) What is a query?
5) When is WHERE condition used?
6) When do having clause used?

DATABASE MANAGEMENT SYSTEM Page 32


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT-7
AIM: Querying Using Aggregate functions, 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
that column. 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.
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)
DATABASE MANAGEMENT SYSTEM Page 33
MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

Example: SELECT MAX (Sal) FROM emp; SQL> select deptno,max(sal) from
emp group by deptno;

DEPTNO MAX(SAL)
------ --------
10 5000

20 3000

30 2850
SQL> select deptno,max(sal) from emp group by deptno having max(sal)<3000;
DEPTNOMAX(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 by deptno having min(sal)>1000;
DEPTNO MIN(SAL)
----- --------
10 1300

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)
Example:

SQL>CREATE VIEW employee AS SELECT empno,ename,job FROM EMP WHERE


job = ‘clerk’;
View created.
SQL> SELECT * FROM EMPLOYEE;

DATABASE MANAGEMENT SYSTEM Page 34


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EMPNO ENAME JOB


---- ------ -------
7369 SMITH CLERK
7876 ADAMS CLERK
7900 JAMES CLERK
7934 MILLER CLERK
Example:
CREATE VIEW [Current Product List] AS SELECT 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)

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.
SQL>SELECT TO_DATE('January 15, 1989, 11:00 A.M.')FROM DUAL;
TO_DATE
---------
15-JAN-89

String functions:

Concat: CONCAT returns char1 concatenated with char2. Both char1 and char2 can be
any of the datatypes
SQL>SELECT CONCAT(‘ORACLE’,’CORPORATION’)FROM DUAL;
ORACLECORPORATION

DATABASE MANAGEMENT SYSTEM Page 35


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

Lpad: LPAD returns expr1, left-padded to length n characters with the sequence of
characters in expr2.
SQL>SELECT LPAD(‘ORACLE’,15,’*’)FROM DUAL;**********ORACLE

Rpad: RPAD returns expr1, right-padded to length n characters with expr2, replicated as
many 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

Lower: Returns a character expression after converting uppercase character data to


lowercase.
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 the given
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

Date functions:
DATABASE MANAGEMENT SYSTEM Page 36
MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

Sysdate: SQL>SELECT SYSDATE FROM DUAL;


29-DEC-08
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
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-05.

DATABASE MANAGEMENT SYSTEM Page 37


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

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?

DATABASE MANAGEMENT SYSTEM Page 38


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT-8
AIM: TRIGGERS(Creation of insert trigger, delete trigger, update
trigger)
Objectives:

Student will able to learn to monitor a database and take initiate action when a
condition occurs.
Outcomes:

Student gains the ability to change database manager from a passive system to
an active one.
a) CREATE OR RELPLACE TRIGGER trig1 before insert on Bus
for each row
DECLARE a number;
BEGIN
if(:new.Bus_No is Null) then raise_application_error(-
20001,'error:: Bus_No cannot be null'); else
select count(*) into a from Bus where Bus_No =:new.
Bus_No; if(a=1) then
raise_application_error(-20002,'error:: cannot
have duplicate Bus_No '); end if;
end if;
END;
RESULT:
SQL> @trigger
Trigger created.
SQL> select * from Bus;
BUS_NO SOURCE DESTINATION
110 hyd ban
221 hyd chn

DATABASE MANAGEMENT SYSTEM Page 39


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

412 hyd mum


501 hyd kol
SQL> insert into Bus values(&Bus_No,'&source','&destination');
Enter value for Bus_No: null
Enter value for source: Chen
Enter value for destination: hyd

old 1: insert into Bus values(&Bus_No, '&source', '&destination')


new 1: insert into Bus values(null,Chen','hyd')

insert into Bus values(null,‟Chen','hyd')

*
ERROR at line 1:

ORA-20001: error::Bus_No cannot be null


35

ORA-06512: at "SYSTEM.TRIG1", line


5 ORA-04088: error during
execution of trigger
'SYSTEM.TRIG1'
SQL> /
Enter value for Bus_No: 110 Enter
value for source:KOL Enter value
for destination: hyd
old 1: insert into Bus values(&Bus_No, '&source', '&destination')

new 1: insert into Bus values(110,KOL','hyd')


insert into Bus values(110,‟KOL','hyd')
*
ERROR at line 1:
ORA-20002: error:: cannot have duplicate Bus_No

DATABASE MANAGEMENT SYSTEM Page 40


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

ORA-06512: at "SYSTEM.TRIG1", line 9


ORA-04088: error during execution of trigger 'SYSTEM.TRIG1'

b) Create Trigger update check before update on Ticket For Each Row
Begin
If New.Ticket_No>60 Then
Set New.Ticket_No=Ticket_No;
Else
Set New.Ticket_No=0;

End If
End.

VIVA QUESTIONS:
1) Explain trigger and trigger types?
2) What are dml triggers?
3) What is clr ddl trigger?
4) What is after dml trigger?
5) Is it possible to create trigger on views?
6) What are the levels of triggers supported by MYSQL?
7) How can we obtain metadata about triggers in MYSQL?

DATABASE MANAGEMENT SYSTEM Page 41


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT-9
AIM: 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.
Syntax:
CREATE [OR REPLACE] PROCEDURE <procedure_name> [parameter(s)] AS
[Variable declaration section]
BEGIN
<Statements>
END [<procedure_name>];

CREATE OR REPLACE PROCEDURE sampleproc


IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World!');
END;
/

Procedure created.

SQL> exec sampleproc;


Hello World!

PL/SQL procedure successfully completed.

CREATE OR REPLACE PROCEDURE samprocparam(name VARCHAR2)


IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World ' || name);
END;
/
DATABASE MANAGEMENT SYSTEM Page 42
MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

CREATE OR REPLACE PROCEDURE sumtwonum(a number, b number)


IS
c number;
BEGIN
c:=a+b;
DBMS_OUTPUT.PUT_LINE('Sum of given two numbers ' || c);
END;
/

Procedure created.

SQL> exec samprocparam('mist');


Hello World mist

VIVA QUESTIONS:
1) What is the difference between anonymous block and stored procedures?
2) What are the different types of stored procedures?
3) Can procedures called inside the function.
4) What is recursive stored procedure?
5) What are external procedures and when they are used?
6) What are the advantages of stored procedures?
7) Can procedure contain return value?
8) How to delete procedure?
9) Explain different modes of procedures?

DATABASE MANAGEMENT SYSTEM Page 43


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT-10
AIM: Cursors

Objectives:

Student will able to learn about cursors that enable traversal over
the records in a database.

Outcomes:

Student gains the ability to implement cursors on the database.

We use a cursor when we have a SELECT statement that returns more than
one row from the database. A cursor is basically a set of rows that we can
access one at a time.
We retrieve the rows into the cursor using our SELECT statement and then
fetch the rows from the cursor.
We may follow five steps when using a cursor.

Declare variables to store the column values from the SELECT statements.

1. Declare the cursor specifying our SELECT statement.


2. Open the cursor.
3. Fetch the rows from the cursor.
4. Close the cursor
a) To write a Cursor to display the list of Male and FemalePassengersAnalyst.
DECLARE

cursor c(jb varchar2) is select Name from


Passenger where Sex=m;
pr Passenger.Sex%type;
BEGIN
Open c('m');
dbms_RESULT.put_line(' Name
of Male Passenger are:');

DATABASE MANAGEMENT SYSTEM Page 44


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

loop
fetch c into pr;
exit when c%notfound;
dbms_RESULT.put_line(pr);
end loop;
close c;
open c('f');
dbms_RESULT.put_line(' Name of female
Passengers are:');
loop
fetch c into em;
exit when c%notfound;
dbms_RESULT.put_line(em);
end loop;
close c;
END;

RESULT:
Name of Male
Passenger are: SACHIN
rahul
rafi
salim
riyaz

Name of female Passengers


are: swetha
neha
PL/SQL procedure successfully completed.

DATABASE MANAGEMENT SYSTEM Page 45


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

b) To write a Cursor todisplayListofPassengerfrom Passenger Table.


DECLARE
cursor c is select PNR_NO, Name, Age, Sex from Passenger ;
i Passenger.PNR_NO%type;

j Passenger.Name%type;
k Passenger.Age%type;
l Passenger.Sex%type;
BEGIN
open c;

dbms_RESULT.put_line('PNR_NO,
Name, Age, Sex of Passengers are:= ');
loop
fetch c into i, j, k, l;
exit
when c%notfound;
dbms_RESULT.put_line(i||' '||j||'
'||k||' '||l);
end loop;
close c;
END;
RESULT:
SQL>@Passenger
PNR_NO NAME AGE SEX
---------- -------------------- ---------- ----------
1 SACHIN 12 m
2 rahul 43 m
3 swetha 24 f
4 rafi 22 m
PL/SQL procedure successfully completed

DATABASE MANAGEMENT SYSTEM Page 46


MAHAVEER INSTITUTE OF SCIENCE & TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd)
Vyasapuri, Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
DEPARTMENT OF INFORMATION TECHNOLOGY

VIVA QUESTIONS:
1) What is cursor?
2) What are the uses of cursors?
3) What are the types of cursors?
4) Explain explicit cursor?
5) What are the properties of cursors?
6) What is implicit cursor?
7) Explain explicit cursor.

DATABASE MANAGEMENT SYSTEM Page 47

You might also like