Dbms Lab PDF
Dbms Lab PDF
Dbms Lab PDF
Cheeryal (V), Keesara (M), Ranga Reddy District – 501 301 (T.S)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
-1-
Geethanjali College of Engineering and Technology
Department of COMPUTER SCIENCE & ENGINEERING
Prepared by : Modified by :
2) Sign : 2) Sign :
4) Date : 4) Date :
Approved by : (HOD )
1) Name :
2) Sign :
3) Date :
-2-
List of Lab Exercises
11 Cursors
A cursor on the given data
-3-
ADDITIONAL PROGRAMS
-4-
Vision of the Department
To produce globally competent and socially responsible computer science engineers
contributing to the advancement of engineering and technology which involves creativity and
innovation by providing excellent learning environment with world class facilities.
2. To prepare graduates to enter a rapidly changing field as a competent computer science engineer.
3. To prepare graduate capable in all phases of software development, possess a firm understanding of
hardware technologies, have the strong mathematical background necessary for scientific
computing, and be sufficiently well versed in general theory to allow growth within the discipline
as it advances.
4. To prepare graduates to assume leadership roles by possessing good communication skills, the
ability to work effectively as team members, and an appreciation for their social and ethical
responsibility in a global setting.
2. To provide graduates with analytical and problem solving skills to design algorithms, other
hardware / software systems, and inculcate professional ethics, inter-personal skills to work in a
multi-cultural team.
3. To facilitate graduates to get familiarized with the art software / hardware tools, imbibing
creativity and innovation that would enable them to develop cutting-edge technologies of multi-
disciplinary nature for societal development.
-5-
PROGRAM OUTCOMES
Professional
1 DBMS II √ √
core
-6-
Mapping of Lab Course outcomes with Programme outcomes:
Pos 1 2 3 4 5 6 7 8 9 10 11 12 13 14
DBMS Exp no.
CO1: Student 1 H H L H H L
gains the
ability to
Construct E-R
diagrams.
CO 2: Student 2,3 H H L H H L
gains the
ability to
describe the
data
requirements
for a new
information
system in a
direct and easy
to understand
graphical
notation.
CO 3: Student 2,3 H H L H H L
gains the
ability to
implement
Notation to
Describe the
Relational
Schema and to
Represent an
ER Model as a
Relational
Model.
CO 4: Students 4 L L H L L
are able to
build the
database that
does not have
Professional core
redundant data.
CO 5: Students 5,6,7,8 L H H H L H
have the ability
to Categorize
the main
-7-
database
objects,
Review and
create the table
structure with
constraints.
CO 6: Students 6,7,8 HH H L H
are able to
perform
transactions
like updating,
deleting,
inserting and
selecting data
from a data
base.
CO 7: Student 6,7,8,9 L L H H L H
are able to
implement
queries using
ANY, ALL,
IN,
INTERSECT,
UNION and
aggregate
operators.
CO 8: Students 10 L L H H
have the ability
to change
database
manager from
a passive
system to an
active one.
CO 9: Students 10,11,12 L L H H
are able to
implement
procedures ,
cursors and
triggers.
-8-
DBMS
Lab Manual
-9-
INTRODUCTION
What is Oracle?
Oracle is the name of the database management system that comes from Oracle
Corporation.
Oracle9i is the latest product released by Oracle Corporation. Unlike Oracle8i, which is
only a database management system, Oracle9i is a collection of following software:
In simple words Oracle9i is a platform and not a simple database management system.
Oracle9iDB is the database management system that is used to store and access data.
Oracle is by far the most widely used relational database management system (RDBMS).
This book is about Oracle Database Server. It doesn’t discuss about other products in
Oracle9i.
Oracle Corporation is also into Enterprise Resource Planning (ERP). It has Oracle
Applications that includes Oracle Financials etc.
Oracle database server is one of the databases that are widely used in client/server
computing as back-end. Front-end programs that are written using application
development tools such as Visual basic access Oracle and submit SQL commands for
execution. Oracle8i onwards oracle is trying to provide extra facilities that are required to
be an internet database.
- 10 -
Figure 1: Oracle Server as Server in Client/Server computing model.
Oracle8i provides special features to support various types of data that is to be stored in
web sites. Oracle supports both OLTP (online transaction processing) applications as well
data warehouse applications, which contain a very large database (VLDB).
One of the biggest advantages of Oracle has been its presence on around 100 different
platforms. Oracle is quite scalable, which means it can scale up and down very easily as
the requirements change.
Oracle also provides Java Virtual Machine (JVM) as part of database. This enables oracle
to run java programs. In fact, starting from Oracle8i, oracle can run programs written
either in PL/SQL or Java.
Oracle Instance
Oracle instance is a collection of memory structures and processed that are used to
manage oracle database. Each oracle database is to be accessed by one or more Oracle
instances. If two or more instances are accessing the same database, it is called as parallel
server architecture. In order to start using an oracle database, we must first start Oracle
instance. Oracle instance will them open the database and make it available to users. It is
beyond the scope of this book to discuss what Oracle instance actually contains. Please
read “Oracle Concepts” manual for complete information about oracle instance. In
nutshell every oracle installation contains at least one Oracle Instance and one oracle
database.
- 11 -
Primary Memory (RAM)
Oracle Instance
Oracle Database
Hard disk
Client
Oracle Instance
Oracle Database
- 12 -
Starting up Database
Before we access oracle database, we must start oracle database. Starting up oracle
database means starting oracle instance and associating oracle instance with an oracle
database so that oracle instance can access the database. The process is very length and
complicated. Several steps are involved in it. But fortunately we do not have to know all
that happens when a database starts. We just need to select an option or two to startup
database. Generally you do not have to startup database in case of Oracle Server running
on Windows NT/Windows 2000 as oracle server automatically starts in this case.
However, if you ever have to start oracle database on Windows NT/Windows 2000,
follow the steps given below:
Note: Starting and shutting down the database is the job of Database Administrator. As
this books assumes that you are an application developer, it doesn’t get into those details.
2. When a dialog box is displayed wait until the message Oracle Instance Started
appears.
3. Click on Close button to close the dialog box.
- 13 -
Starting SQL*PLUS
Sql*plus is a tool that comes along with Oracle. It is used to issue SQL and SQL*PLUS
commands. It provides command line interface through which we can enter SQL and
SQL*PLUS command.
To start SQL*PLUS, take the steps given below:
1. Select start->programs->Oracle - Oracle8i.
Oracle8i is the name of the instance. It may be different on your system.
2. Then select Application Development -> SQL Plus.
3. When Log On dialog box is displayed, enter username, password and Host string. Use
tab key to move from one field to another. For more information about each of these
fields, see next section.
4. Click on OK.
5. If the information supplied is valid then you enter into Oracle and SQL*PLUS
will display SQL> prompt.
- 14 -
sys change_on_install
Scott tiger
Demo demo
Note: when you enter into oracle using either system or sys then you become
DBA. That means you get special privileges to perform major operations such as
creating users etc.
Host String
Host string is a name that is used to access oracle server that is running on a different
machine from client. This is required only when you are trying to access oracle server
that is not on the current machine. That means, you never need to use host string for
Personal Oracle as client and oracle always run on the same machine in Personal Oracle.
Host string is required when you are trying to connect to Oracle Server running on
remote machine. Host string is actually called as net service name. Net service name is
a name that is stored in TNSNAMES.ORA file on the client to provide the following
information.
Host Name of the machine or IP address of the machine on
Which oracle server is running?
Instance Name of the Oracle Instance running on the remote
machine.
Port Number Port number of the listener, a program that takes
Requests from clients. Port number is an integer that
Uniquely identifies the program on the server.
- 15 -
SQL> select ccode, name
2 from courses
3 where fee > 5000;
In the above command, we entered the command in three lines. When you enter
semicolon and press enter key then SQL*PLUS will take it as the end of the command.
Also note that you have to press enter key at the end of each line.
Note: Both SQL and SQL*PLUS commands are NOT case sensitive.
Or it can be abbreviated to
SQL>clrscr
Common Errors
The following are the common errors that you get while you are trying to log on to
Oracle.
Ora-01017: invalid username/password; login denied
- 16 -
WEEK 1
AIM
E-R Model
Analyze the problem with the entities which identify data persisted in the database which
contains entities and attributes.
Objectives:
Student will able to learn the Entity-Relationship(ER) modeling to develop a conceptual model of data.
Outcomes:
Requirements Analysis
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.
- 17 -
Following steps are involved in the process:
1. Analyzing the problem and identifying the Entities and Relationships
2. E-R Model
3. Normalised Relational Model
4. Creating the database
5. Querying.
6. Triggers and Stored procedures on the tables.
1) E-R Model:
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 wqill 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.
The Road Way Travels Consists Of The Following Entities:
BUS
Ticket
Passenger
Reservation
Cancellation/modification
These Entities have following attributes
Bus:
Bus_id
Bus_name
Bus_type
Bus_totalseats
Ticket:
Ticket_booking
Ticket_datejourney
Ticket_to
Ticket_from
Ticket_id
Ticket_no of tickets
Passenger:
Pid
Pname
Pgender
- 18 -
Page
precancel
VIVA QUESTIONS
- 19 -
WEEK 2
Concept design with E-R Model and apply cardinalities for each relationship.
Identify strong entities and weak entities for relationships like generalization,
aggregation, specialization.
Objectives:
Student will able to learn data structures in terms of entity types, relationship types and attributes or
classes, associations and attributes.
Outcomes:
Student gains the ability to describe the data requirements for a new information system in a direct and
easy to understand graphical notation.
E_R diagram:
Bus No
Source
BUS
Destination
Departure Time
Sex
- 20 -
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 many to many and many to one relationship.
- 21 -
WEEK 3
AIM
Relation Model represents attributes as columns in tables and different types of
attributes like composite, Multi-valued and Derived.
Objectives:
Student will able to learn the structural components of the relational data model.
Student will able to learn to map ER models into relational models.
Outcomes:
Example: The passenger tables look as below. This is an example. You can add more attributes based
on your E-R model. This is not a normalized table. Passenger
Bus passenger
Passenger-
#bus_no Tickets
#ppno
source #ppno
name
destination #ticket_no
age
#jrny_date
sex
address
phone-no
- 22 -
Tickets
#tickets_no
no of tkts
From_place
T0_place
#Bus_no
#jrny_date
Note: The student is required to submit a document by Represent relationships in a tabular fashion to
the lab teacher.
Relate the entities appropriate for each relationship. Identify strong entities and week entities (if any).
Indicate the type of relationships (total/partial). In this we will design the different E-R diagram for
different entities and also the whole “Roadway Travels”.
Represent all the entities (Strong, Weak) in tabular fashion. Represent relationships in a tabular fashion.
There are different ways of representing relationships as tables based on the cardinality. Represent
attributes as columns in tables or as tables based on the requirement. In this we will represent the
different entities, attributes of different keys in a tabular fashion or manner.
- 23 -
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 structure to prevent repeat and redundant data storage.
A super key is a set of one or more attributes which; taken collectively, allow us to identify
uniquely an entity in the entity set.
A 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 primary key column of another
table. The foreign key can 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.
- 24 -
VIVA QUESTIONS
- 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 query statistics, 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
Wilkinson
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
- 26 -
To each customer corresponds a repeating group of transactions. The automated evaluation of any query
relating to customers' transactions therefore would broadly involve two stages:
1. Unpacking one or more customers' groups of transactions allowing the individual transactions in
a group to be examined, and
2. Deriving a query result 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 for
all 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 of the transaction falls
in 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 above
would look like this:
Now each row represents an individual credit card transaction, and the DBMS can obtain the answer of
interest, simply by finding all rows with a Date falling in October, and summing their Amounts. The
data structure places all of the values on an equal footing, exposing each to the DBMS directly, so each
can potentially participate directly in queries; whereas in the previous situation some values were
embedded in lower-level structures that had to be handled specially. Accordingly, the normalized design
lends itself to general-purpose query processing, whereas the unnormalized design does not.
VIVA QUESTIONS
- 27 -
WEEK 5
AIM
INSTALLATION OF MYSQL and Practicing DDL commands
Objectives:
Student will able to learn DDL Statements to Create and Manage Tables.
Outcomes:
Requirements:
MYSQL, software for database that is “MYSQL.exe” required space for installing MYSQL server.
Description: In this we will install the MYSQL server and also practice the “DDL” commands.
Installation of MySQL:
Why MySQl:MySQL is undoubtedly the most popular and widely-used open source database:
Installing MySQL on your development PC allows you to safely create and test a web application
without affecting the data or systems on your live website.
- 28 -
Installing MySQL on Windows: In this section you will learn how to install MySQL 5.0 on windows
system the MySQl 3.21 was first version for the windows. Windows installer of MySQL includes auto
installer with configuration Wizard that support for easy installation.
Creating a table:
To store data into the database we must create a table with same structure as the data we have to
store into the database. To create a table use the create table Command that has the following syntax.
Syntax: SQL>Create table <tablE name> (<colname>< datatype>[constraints],<colname>
[constraints]……. colname>< datatype>[constraints],[table level constraints])
student table:
Sid int pK
Create table student (Sid int constraint sid_PK Primary Key, Sname varchar(30) not null. Course
varchar(30) constraint default-course default’CPP’)
After creating table we may want to add or remove columns and constraints or change the data type of a
column to perform all these operations, we have to use alter table that has the following syntax,
1. Alter column: this option is used to change the datatype of a column or add or remove not null
constraint.
Q: Sp_help’student’ //Execute
EX: The following example changes the data types of sname column of student table to char with
maximum length 40 removes the not Null Column constraint available on it.
Q: sp_help’student //Execute
3. Drop Column: this option is used to delete columns from the table
- 29 -
Ex: The following example deletes the columns Fname and address from the table student.
VIVA QUESTIONS
1. Write the syntax for all DDL commands?
- 30 -
WEEK 6
AIM
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.
SELECT INSERT,UPDATE,DELETE.
1) Inserting rows into the table: To insert rows into the table we have to use insert Command that
has the following syntax
While using thei syntax of insert command we must provide value for every column. Whenever we
want to insert null into a column then use the keyword null and to insert default value for a column use
the keyword default.
Insert Marks Values (1001, 77, 54, 67, null, null, null)
- 31 -
Insert Marks Values (1002, 70, 45, 56, null, null, null)
Insert Marks Values (1005, 78, 65, 89, null, null, null)
2) Creating a table from another table: When we have to create a new table from existing table then
use the following Syntax of Select statement.
Ex: the following example creates a table with name student3 from the table student.
3) Updating Rows in the table: When we have to modify the existing data in the table then we have to
use update Command that has the following syntax
Ex:The following examples updates name and course of the student with id 1004 to S and DOTNET
EX: The following example updates marks table by calculating total and average for all rows.
Ex:the following example updates marks table by calculating the grade on average marks.
Case
- 32 -
Else’Fail’
End
4) Deleting Rows from the table:To delete rows from table use the delete Command that has the
following syntax:
Ex: The following example deletes the student record with si4-1004 from marks table
EX: The following example deletes all rows from the marks.
Q: Delete marks
Output
RATING MINAGE
8 25.5
7 35
3 25.5
4. Create the table using following attributes BUS (BUSNO: VARCHAR2 (10): PK,
SOURCE: VARCHAR2 (50), DESTINATION: VARCHAR2 (50))
Creating table
Syntax
Query
Create table create table BUS (BUSNO VARCHAR2(10) Primary Key, SOURCE
VARCHAR2 (50), DESTINATION VARCHAR2 (50));
Describing table
Query
Desc bus
- 33 -
Output
Table Col umn Data Type Length Preci si on Scal e Primar y Key Null abl e Defaul t Comment
SOURCE Varchar2 50 - - - - -
DESTINATION Varchar2 50 - - - - -
1-3
Syntax
Query
Display table
Syntax
Query
Output
- 34 -
45 tirupathi banglore
34 hyderabad chennai
5. Create the table using following attributes PASSENGER (PPNO: VARCHAR2 (15):
PK, NAME: VARCHAR2 (15), AGE: INT (4), SEX: CHAR (10): MALE/FEMALE,
ADDRESS: VARCHAR2 (50))
Creating table
Syntax
Query
Describing table
Query
Desc PASSENGER
Output
Table Col umn Data Type Length Preci si on Scal e Primar y Key Null abl e Defaul t Comment
PASSENGER PPNO Varchar2 15 - - 1 - - -
NAME Varchar2 15 - - - - -
AGE Number - 4 0 - - -
SEX Char 10 - - - - -
ADDRESS Varchar2 50 - - - - -
1-5
Syntax
- 35 -
Insert into <table name> values (val 1,val2,val3)
Query
Display table
Syntax
Query
Output
VIVA QUESTIONS
3. What is the difference between NULL Values and NOT NULL Values?
- 36 -
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
Query
Describing table
Query
Desc TICKET
- 37 -
Output
Table Col umn Data Type Length Preci si on Scal e Primar y Key Null abl e Defaul t Comment
JOURNEY_DATE Date 7 - - - - -
AGE Number - 4 0 - - -
SEX Char 10 - - - - -
SOURCE Varchar2 50 - - - - -
DEP_TIME Varchar2 50 - - - - -
Syntax
Query
Display table
Syntax
Query
- 38 -
select * from TICKET;
Output
Creating table
Syntax
Query
Describing table
Query
Desc PASSENGER_TICKETS
Output
Com
Table Col umn Data Type Length Preci si on Scal e Primar y Key Null abl e Defaul t ment
PASSENGER_TICKE
PPNO Varchar2 15 - - 1 - - -
TS
TICKET_NO Number - 9 0 - - -
- 39 -
Inserting records into “PASSENGER_TICKETS” table
Syntax
Query
Display table
Syntax
Query
Output
PPNO TICKET_NO
1 1203
2 1213
3 1201
4 1202
5 1205
- 40 -
FOREIGN KEY(PNR_NO ) REFERENCES PASSENGER_TICKECTS(PPNO);
Creating table
Syntax
Query
Describing table
Query
Desc reservation
Output
Table Col umn Data Type Length Preci si on Scal e Primar y Key Null abl e Defaul t Comment
RESERV
PNR_NO Varchar2 15 - - - - -
ATION
JOURNEY_DATE Date 7 - - - - -
NO_OF_SEATS Number - 8 0 - - -
ADDRESS Varchar2 50 - - - - -
CONTACT_NO Number - 10 0 - - -
STATUS Char 3 - - -
Syntax
- 41 -
Query
Display table
Syntax
Query
Output
- 42 -
Create the table using following attributes CANCELLATION (PNR_NO: NUMERIC
(9): FK, JOURNEY_DATE: DATE, NO_OF_SEATS: INT (8), ADDRESS:
VARCHAR2 (50), CONTACT_NO: NUMERIC (9), STATUS: CHAR (3): YES/NO)
Creating table
Syntax
Query
Describing table
Query
Desc reservation
Output
Com
Table Col umn Data Type Length Preci si on Scal e Primar y Key Null abl e Defaul t ment
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 - - - - -
- 43 -
Inserting records into “CANCELLATION” table
Syntax
Query
Display table
Syntax
Query
Output
- 44 -
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
Query
Output
PNR_NO
1
3
5
2
4
Query
Output
NAME
TIRUMALAY
NAGARAJU
AVS.RAVI
- 45 -
29. Display the ticket numbers and names of all the passengers.
Query
30. Find the ticket numbers of the passengers whose name start with ‘t’ and ends with ‘y’.
Query
Output
TICKET_NO
1203
31. Find the names of passengers whose age is between 15 and 20.
Query
Output
NAME
TIRUMALAY
SUPRIYA
AMULYA
NAGARAJU
AVS.RAVI
- 46 -
32. Display all the passengers names beginning with ‘A’.
Query
Output
NAME
AMULYA
AVS.RAVI
Query
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
union
- 47 -
Output
35. Display the number of tickets booked for each PNR_NO using GROUP BY clause.
(Use GROUP BY on PNR_NO).
Query
Output
PNR_NO SUM(NO_OF_SEATS)
1 13
3 3
5 8
2 10
4 4
- 48 -
36. Find the distinct PNR numbers that are present.
Query
Output
PNR_NO
1
3
5
2
4
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
Output
PNR_NO SUM(NO_OF_SEATS)
1 13
5 8
2 10
Query
Output
SUM(NO_OF_SEATS)
38
- 49 -
VIVA QUESTIONS
- 50 -
WEEK 8 & 9:
Student will able to learn to perform mathematical operations that return a single value, calculated from
values in a column.
Outcomes:
Student gains the knowledge to perform aggregate operations on the database appropriately.
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.
2. SUM: SUM followed by a column name returns the sum of all the values in that
column.
3. AVG: AVG followed by a column name returns the average value of that column
values.
- 51 -
Syntax: AVG (n1,n2..)
4. MAX: MAX followed by a column name returns the maximum value of that column.
DEPTNO MAX(SAL)
------ --------
10 5000
20 3000
30 2850
DEPTNO MAX(SAL)
----- --------
30 2850
5. MIN: MIN followed by column name returns the minimum value of that column.
DEPTNO MIN(SAL)
----- --------
10 1300
- 52 -
VIEW: In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present
the data as if the data were coming from one single table.
A view is a virtual table, which consists of a set of columns from one or more
tables. It is similar to a table but it doest not store in the database. View is a query stored
as an object.
1. Example:
View created.
- 53 -
2.Example:
DROP VIEW: This query is used to delete a view , which has been already created.
View dropped
- 54 -
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 be
any of the datatypes
ORACLECORPORATION
Lpad: LPAD returns expr1, left-padded to length n characters with the sequence of
characters in expr2.
Rpad: RPAD returns expr1, right-padded to length n characters with expr2, replicated as
many times as necessary.
ORACLE*********
MITHSS
SSMITH
- 55 -
Lower: Returns a character expression after converting uppercase character data to
lowercase.
dbms
DBMS
Length: Returns the number of characters, rather than the number of bytes, of the
given string expression, excluding trailing blanks.
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.
14
3. Date functions:
29-DEC-08
- 56 -
next_day:
05-JAN-09
add_months:
28-FEB-09
last_day:
31-DEC-08
months_between:
Least:
10-JAN-07
Greatest:
10-JAN-07
Trunc:
28-DEC-08
- 57 -
Round:
28-DEC-08
to_char:
24-mar-05.
to_date:
24-mar-o5.
VIVA QUESTIONS
3. Define View?
- 58 -
WEEK 10
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.
1)Write a trigger which ill check if the passenger is greater than 40 before a row is
inserted into a passenger table.
- 59 -
VIVA QUESTIONS
1. What is Trigger?
2. What is Nested Trigger?
3. What are the types on Triggers?
4. What is the difference between For Trigger and After trigger?
- 60 -
WEEK 11:
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.
BEGIN
End;
Procedures created
BEGIN
OPEN c1;
Close c1;
End;
- 61 -
VIVA QUESTIONS
- 62 -
WEEK 12
Objectives:
Student will able to learn about cursors that enable traversal over the records in a
database.
Outcomes:
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.
declare
v_sno student.sno%TYPE;
v_snname student.sname%TYPE;
v_branch student.branch%TYPE;
v_age student.age%TYPE;
cursor MyCursor (c_sno number) is select sno,sname,branch,age from student
where sno=c_sno;--c_record MyCursor%rowtype;
begin
if (NOT MyCursor%ISOPEN)then
Open MyCursor (1201);
end if;
loop
- 63 -
fetch MyCursor into v_sno,v_sname,v_branch,v_age;
exit when MyCursor%NOTFOUND;
dbms_output_line
(“Record’||MyCursor%ROWCOUNT||’:’||v_sno||’’||v_sname||’’||v_branch||’’||v_age)
;
endloop;
if(MyCursor%ISOPEN)then
close MyCursor;
endif;
if(NOT MyCursor%ISOPEN)then
oprn MyCursor(1202);
endif;
loop
fetch MyCursor into v_sno,v_sname,v_branch,v_age;
exit when MyCursor%NOTFOUND;
dbms_output.put_line (‘Record’||MyCursor%ROWCOUNT||’:’||v_sno||’’||v_snam
e||’’||v_branch||’’||v_age);
endloop;
if (MyCursor%ISOPEN)then
Close Mycursor;
endif;
end;
VIVA QUESTIONS
- 64 -
ADDITIONAL PROGRAMS
- 65 -
1) Queries on employee, department tables
syntax
SQL>Create table <table name> (col1 datatype,col2 datatype,col3 datatype)
Query
SQL> create table employee1(empsid
number,empname varchar(20),empjob
varchar(20),empsalary number,empjoindate
varchar(20));
Describing table
SQL> desc employee1;
EMPSID NUMBER
EMPNAME VARCHAR2(20)
EMPJOB VARCHAR2(20)
EMPSALARY NUMBER
EMPJOINDATE VARCHAR2(20)
- 66 -
Enter value for empsalary: 20000
Enter value for empjoindate: '4-jan-2009'
old 1: insert into employee1
values(&empsid,&empname,&empjob,&empsalary,&empjoindate)
new 1: insert into employee1 values(20,'anil','java',20000,'4-jan-2009')
1 row created.
SQL> /
Enter value for empsid: 50
Enter value for empname: 'jyothi'
Enter value for empjob: 'faculty'
Enter value for empsalary: 30000
Enter value for empjoindate: '5-mar-2003'
old 1: insert into employee1
values(&empsid,&empname,&empjob,&empsalary,&empjoindate)
new 1: insert into employee1 values(50,'jyothi','faculty',30000,'5-mar-2003')
1 row created.
SQL> /
Enter value for empsid: 60
Enter value for empname: 'avinash'
Enter value for empjob: 'software'
Enter value for empsalary: 30000
Enter value for empjoindate: '5-apr-2009'
old 1: insert into employee1
values(&empsid,&empname,&empjob,&empsalary,&empjoindate)
new 1: insert into employee1 values(60,'avinash','software',30000,'5-apr-2009')
1 row created.
SQL> /
Enter value for empsid: 70
- 67 -
Enter value for empname: 'anitha'
Enter value for empjob: 'sql'
Enter value for empsalary: 40000
Enter value for empjoindate: '2-jun-2008'
old 1: insert into employee1
values(&empsid,&empname,&empjob,&empsalary,&empjoindate)
new 1: insert into employee1 values(70,'anitha','sql',40000,'2-jun-2008')
1 row created.
Display table
SQL> select * from employee1;
- 68 -
DPJOB VARCHAR2(20)
DPJOINDATE VARCHAR2(20)
DPLOCATION VARCHAR2(20)
SQL> insert into department
values(&dpsid,&dpname,&dpjob,&dpjoindate,&dplocation);
Enter value for dpsid: 1
Enter value for dpname: 'cse'
Enter value for dpjob: 'dbms'
Enter value for dpjoindate: '4-jan-2002'
Enter value for dplocation: 'hyd'
old 1: insert into department values(&dpsid,&dpname,&dpjob,&dpjoindate,&dplocation)
new 1: insert into department values(1,'cse','dbms','4-jan-2002','hyd')
1 row created.
SQL> /
Enter value for dpsid: 2
Enter value for dpname: 'os'
Enter value for dpjob: 'co'
Enter value for dpjoindate: '5-apr-2003'
Enter value for dplocation: 'hyd'
old 1: insert into department values(&dpsid,&dpname,&dpjob,&dpjoindate,&dplocation)
new 1: insert into department values(2,'os','co','5-apr-2003','hyd')
1 row created.
SQL> /
Enter value for dpsid: 3
Enter value for dpname: 'ece'
Enter value for dpjob: 'stld'
Enter value for dpjoindate: '6-dec-2004'
Enter value for dplocation: 'hyd'
- 69 -
old 1: insert into department values(&dpsid,&dpname,&dpjob,&dpjoindate,&dplocation)
new 1: insert into department values(3,'ece','stld','6-dec-2004','hyd')
1 row created.
SQL> /
Enter value for dpsid: 4
Enter value for dpname: 'eee'
Enter value for dpjob: 'bee'
Enter value for dpjoindate: '6-jun-2006'
Enter value for dplocation: 'hyd'
old 1: insert into department values(&dpsid,&dpname,&dpjob,&dpjoindate,&dplocation)
new 1: insert into department values(4,'eee','bee','6-jun-2006','hyd')
1 row created.
SQL> select * from department;
- 70 -
Name Null? Type
----------------------------------------------------------------- -------- -------------
EMPSID NUMBER
EMPNAME VARCHAR2(20)
EMPJOB VARCHAR2(20)
EMPSALARY NUMBER
EMPJOINDATE VARCHAR2(20)
EMPTIME NUMBER
SQL> drop table employee1;
Table dropped.
SQL> desc employee1;
ERROR:
ORA-04043: object employee1 does not exist
1. Create the table using following attributes Sailors (sid: number, sname:
varchar2(20), rating: number, age: number(4,2));
Creating table
Syntax
Query
Create table sailors (sid number, sname varchar2(20), rating number, age number(4,2));
Describing table
Query
Desc sailors
Output
- 71 -
Inserting records into table
Syntax
Query
Table Column Dat a T ype Lengt h Precisi on Scale Primar y Key Nullabl e Def ault Comment
SAILORS SID Number - - - 1 - - -
SNAME Varchar2 20 - - - - -
RATING Number - - - - - -
AGE Number - 4 2 - - -
1-4
Display table
Syntax
Query
- 72 -
Table Column Dat a T ype Lengt h Precisi on Scale Primar y Key Nullabl e Def ault Comment
Output
SI D SNAM E RATI NG AGE
22 dustin 7 45
29 brutus 1 33
31 lubber 8 55.5
32 andy 8 25.5
58 rusty 10 35
64 horatio 7 35
71 zobra 10 16
74 horatio 9 35
85 art 3 25.5
95 bob 3 63.5
Creating table
Syntax
Query
Describing table
Query
Desc boats
Output
- 73 -
BOATS BID Number - - - 1 - - -
BNAME Varchar2 10 - - - - -
COLOR Varchar2 10 - - - - -
1-3
Syntax
Query
Display table
Syntax
Query
Output
BI D BNAME COLOR
101 interlake blue
102 interlake red
103 clipper green
104 marine red
- 74 -
3. Create the table using following attributes Reserves (sid: number, bid: number, day:
date);
Creating table
Syntax
Query
Describing table
Query
Desc reserves
Output
DAY Date 7 - - - - -
Syntax
Query
- 75 -
insert into sailors values(31,102,’11/10/98’);
Display table
Syntax
Query
Output
SI D BI D DAY
22 101 10/10/98
22 102 10/10/98
64 102 9/8/98
74 103 9/8/98
22 103 10/8/98
22 104 10/7/98
31 102 11/10/98
31 103 11/6/98
31 104 11/12/98
64 101 9/5/98
1) Find the names of sailors who have reserved boat number 103 (Using AND).
Query
SNAME
horatio
- 76 -
Output dustin
lubber
2) Find the sids of sailors who have reserved a red boat (Using AND).
Query
Output
SID
22
64
22
31
31
3) Find the names of sailors who have reserved a red boat (Using AND).
Query
select s.sname from sailors s,reserves r,boats b where s.sid=r.sid and r.bid=b.bid and
b.color='red'
Output
SNAME
dustin
horatio
dustin
lubber
lubber
- 77 -
Query
select b.color from sailors s,reserves r,boats b where s.sid=r.sid and r.bid=b.bid and
s.sname='lubber'
Output
COLOR
green
red
red
5) Find the names of sailors who have reserved at least one boat.
Query
Output
SNAME
lubber
dustin
horatio
6) Find the ages of sailors whose name begins and ends with B and has at least three
characters.
Query
Output
AGE
63.5
7) Find the names of sailors who have reserved a red or a green boat (Using AND,OR).
- 78 -
Query
select s.sname from sailors s,reserves r,boats b where s.sid=r.sid and r.bid=b.bid and
(b.color='re' or b.color='green')
Output
SNAME
horatio
dustin
lubber
8) Find the names of sailors who have reserved both a red and a green boat .
Query
intersect
Output
SNAME
dustin
horatio
lubber
9)Find the sids of sailors who have reserved red boats but not green boats.
Query
Select s1.sname from sailors s1, reserves r1, boats b1 where s1.sid=r1.sid and
r1.bid=b1.bid and b1.color='red'
and s1.sid not in (select s2.sid from sailors s2,boats b2,reserves r2 where
s2.sid=r2.sid and r2.bid=b2.bid and b2.color='green');
- 79 -
Output
SNAME
horatio
10) Find all sids of sailors who have a rating of 10 or reserved boat 104.
Query
Union
Output
SID
22
31
58
71
11) Find the names of sailors who have reserved boat 103 (Using nested queries).
Query
Select s.sname from sailors s where s.sid in (select r.sid from reserves r where
r.bid=103)
Output
SNAME
dustin
lubber
horatio
- 80 -
12) Find the names of sailors who have reserved a red boat (Using nested queries).
Query
select s.sname from sailors s where s.sid in (select r.sid from reserves r where r.bid
in(select b.bid from boats b where b.color='red'));
Output
SNAME
dustin
lubber
horatio
13. Find the names of sailors who have not reserved a red boat (Using nested queries).
Query
Select s.sname from sailors s where s.sid not in (select r.sid from reserves r where
r.bid in (select b.bid from boats b where b.color=’red’));
Output
SNAME
brutus
andy
rusty
zobra
horatio
art
bob
14. Find the name of sailors who have reserved boat number 103 (Using correlated nested
query).
Query
Select s.sname from sailors s where exists (select * from reserves r where
r.bid=103 and r.sid=s.sid);
- 81 -
Output
SNAME
dustin
lubber
horatio
15. Find sailors whose rating is better than some sailor called Horatio (Using ANY
Operator).
Query
select s.sid from sailors s where s.rating > any(select s1.rating from sailors s1
where s1.sname='horatio');
Output
SID
31
32
58
71
74
16. Find sailors whose rating is better than every sailor called Horatio (Using ALL
Operator).
Query
Select s1.sid from sailors s1 where s1.rating > all (select s2.rating from sailors s2
where s2.sname='horatio');
Output
SID
58
71
17. Find the sailors with the highest rating (Using ALL Operator).
- 82 -
Query
Select s1.sid from sailors s1 where s1.rating >= all (select s2.rating from sailors
s2);
Output
SID
58
71
18. Find the names of sailors who have reserved both a red and a green boat (Using
nested query).
Query
Select s1.sname from sailors s1, reserves r1, boats b1 where s1.sid=r1.sid and
r1.bid=b1.bid and b1.color='red'
and s1.sid in (select s2.sid from sailors s2,boats b2,reserves r2 where s2.sid=r2.sid
and r2.bid=b2.bid and b2.color='green');
Output
SNAME
lubber
dustin
19. Find the average age of all sailors.
Query
Output
AVG(S.AGE)
36.9
- 83 -
20. Find the average age of sailors with a rating of 10.
Query
Output
AVG(S.AGE)
25.5
Query
Select s.sname,s.age from sailors s where s.age=(select max (s2.age) from sailors
s2);
Output
SNAME AGE
bob 63.5
Query
Output
COUNT(DISTINCT(S.SNAME))
9
- 84 -
23. Find the names of sailors who are older than oldest sailor with a rating 10 (Using
Aggregate Operators).
Query
Select s1.sname from sailors s1 where s1.age > (select max (s2.age) from sailors s2
where s2.rating =10);
Output
SNAME
dustin
lubber
bob
24. Find the age of the youngest sailor who is eligible to vote for each rating level with at
least two such sailors.
Query
Select s.rating, min (s.age) as minage from sailors s where s.age>=18 group by
s.rating having count (*) > 1;
25.Find the age of the youngest sailor for each rating level (Using Group By).
Query
Output
RATING MIN(S.AGE)
1 33
8 25.5
7 35
3 25.5
10 16
9 35
- 85 -