DBMS Lab Manual
DBMS Lab Manual
1
1) Rectangle – It represents entity in the ER Model.
2) Ellipse – It represents attribute in the ER Model.
3) Diamond – It represents relationship between entity and attribute.
4) Line – It links attribute(s) to entity set(s) and entity set(s) to relationship
set(s).
5) Doubles Ellipses – It represents multivalued attributes.
6) Dashed Ellipses – It denotes derived attributes.
7) Double lines – It indicates total participation of an entity in a relationship set.
8) Double Rectangle – It represents weak entity set.
9) Double Diamonds – It represents weak relationships.
10) Multiple ellipses connected to single ellipse using lines – It represents
composite attribute
11) Ellipse with line inside it – It represents single values attributes
ER Diagram: Relationship
1. Binary Relationship
2. Recursive Relationship
3. Ternary Relationship
2
1.Binary Relationship
Binary Relationship means relation between two Entities. This is further divided into three types.
The above example describes that one student can enroll only for one course and a course will also
have only one Student. This is not what you will usually see in real-world relationships.
The below example showcases this relationship, which means that 1 student can opt for many
courses, but a course can only have 1 student. Sounds weird! This is how it is.
It reflects business rule that many entities can be associated with just one entity. For example,
Student enrolls for only one Course but a Course can have many Students.
3
d) Many to Many Relationship
The above diagram represents that one student can enroll for more than one courses. And a course
can have more than 1 student enrolled in it.
Recursive Relationship
Ternary Relationship
A Ternary relationship involves three entities. In such relationships we always consider two
entities together and then look upon the third. For example, in the diagram above, we have three
related entities, Company, Product and Sector.
4
To understand the relationship better or to define rules around the model, we should relate two
entities and then derive the third one. A Company produces many Products/ each product is
produced by exactly one company. A Company operates in only one Sector / each sector has many
companies operating in it. Considering the above two rules or relationships, we see that although
the complete relationship involves three entities, but we are looking at two entities at a time.
5
Patients (patient-id, name, insurance, date-admitted, date-checked-out)
Doctors (doctor-id, name, specialization)
Test (testid, testname, date, time, result)
Doctor-patient (patient-id, doctor-id)
Test-log (testid, patient-id)
Performed-by (testid, doctor-id)
6
EXPERIMENT 2
RELATIONAL MODEL
In relational model, the data and relationships are represented by collection of inter-
related tables. Each table is a group of column and rows, where column represents attribute of an
entity and rows represents records.
Tables: In relational data model, relations are saved in the format of Tables. This format stores
the relation among entities. A table has rows and columns, where rows represent records and
columns represent the attributes.
Tuple: A single row of a table, which contains a single record for that relation, is called a tuple.
Relation instance: A finite set of tuples in the relational database system represents relation
instance. Relation instances do not have duplicate tuples.
Relation schema: A relation schema describes the relation name (table name), attributes, and
their names.
Relation key: Each row has one or more attributes, known as relation key, which can identify the
row in the relation (table) uniquely.
Attribute domain: Every attribute has some pre-defined value scope, known as attribute domain.
+-------------+-------------+------+-----+---------+-------+
7
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| BusNo | varchar(10) | NO | PRI | NULL | |
| source | varchar(20) | YES | | NULL | |
| Destination | varchar(20) | YES | | NULL | |
| coachType | varchar(10) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
Ticket:
+------------+----------------+--------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
8
+------------+---------------+---------+-----+---------+-------+
| TicketNo | varchar(20) | NO | PRI | NULL | |
| DOJ | date | YES | | NULL | |
| Address | varchar(20) | YES | | NULL | |
| ContactNo | varchar(15) | YES | | NULL | |
| BusNo | varchar(10) | NO | PRI | NULL | |
| SeatNo | int(11) | YES | | NULL | |
| Source | varchar(10) | YES | | NULL | |
+-----------+-----------------+------+-------+---------+-------+
7 rows in set (0.05 sec)
Passenger:
Type of
ColumnName Datatype Constraints
Attributes
PassportID Varchar(15) Primary Key Single-valued
TicketNo Varchar(20) Foreign Key Single-valued
Name Varchar(20) Composite
ContactNo Varchar(20) Multi-valued
Age Integer Single-valued
Sex character Simple
Address Varchar(20) Composite
Mysql> Create table passenger(passportID varchar(15) ,TicketNo
varchar(15),Name varchar(15),ContactNo varchar(20),Age integer, sex
char(2),address varchar(20), primary key(passportID,TicketNo),foreign
key(TicketNo) references Ticket(TicketNo));
Query OK, 0 rows affected (0.52 sec)
mysql> desc passenger;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
9
+------------+-------------+------+-----+---------+-------+
| passportID | varchar(15) | NO | PRI | NULL | |
| TicketNo | varchar(15) | NO | PRI | NULL | |
| Name | varchar(15) | YES | | NULL | |
| ContactNo | varchar(20) | YES | | NULL | |
| Age | int(11) | YES | | NULL | |
| sex | char(2) | YES | | NULL | |
| address | varchar(20) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
7 rows in set (0.01 sec)
Reservation
10
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| PNRNo | varchar(20) | NO | PRI | NULL | |
| DOJ | date | YES | | NULL | |
| NoofSeates | int(11) | YES | | NULL | |
| Address | varchar(20) | YES | | NULL | |
| ContactNo | varchar(20) | YES | | NULL | |
| BusNo | varchar(20) | NO | PRI | NULL | |
| SeatNo | int(11) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
Cancellation:
+-----------+-------------+------+-----+---------+-------+
11
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| PNRNo | varchar(10) | NO | PRI | NULL | |
| DOJ | date | YES | | NULL | |
| SeatNo | int(11) | YES | | NULL | |
| ContactNo | varchar(15) | YES | | NULL | |
| Status | varchar(10) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec);
EXPERIMENT 3
12
NORMALIZATION
Functional dependency is represented by an arrow sign → that is, X→Y, where X functionally
determines Y. The left-hand side attributes determine the values of attributes on the right-hand
side.
Armstrong's Axioms
If F is a set of functional dependencies then the closure of F, denoted as F+, is the set of all
functional dependencies logically implied by F. Armstrong's Axioms are a set of rules, that
when applied repeatedly, generates a closure of functional dependencies.
Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds
beta.
Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That
is adding attributes in dependencies, does not change the basic dependencies.
Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then
a → c also holds. a → b is called as a functionally that determines b.
Trivial Functional Dependency
13
Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to
be a completely non-trivial FD.
4.2 Normalization
If a database design is not perfect, it may contain anomalies, which are like a bad dream for any
database administrator. Managing a database with anomalies is next to impossible.
Update anomalies − If data items are scattered and are not linked to each other properly,
then it could lead to strange situations. For example, when we try to update one data item
having its copies scattered over several places, a few instances get updated properly while
a few others are left with old values. Such instances leave the database in an inconsistent
state.
Deletion anomalies − We tried to delete a record, but parts of it was left undeleted
because of unawareness, the data is also saved somewhere else.
Insert anomalies − We tried to insert data in a record that does not exist at all.
Normalization is a method to remove all these anomalies and bring the database to a consistent
state.
4.2.1 First Normal Form
First Normal Form is defined in the definition of relations tables itself. This rule defines that all
the attributes in a relation must have atomic domains. The values in an atomic domain are
indivisible units
First Normal Form is defined in the definition of relations (tables) itself. This rule defines that all
the attributes in a relation must have atomic domains. The values in an atomic domain are
indivisible units.
14
Each attribute must contain only a single value from its pre-defined domain.
If we follow second normal form, then every non-prime attribute should be fully functionally
dependent on prime key attribute. That is, if X → A holds, then there should not be any proper
subset Y of X, for which Y → A also holds true.
We see here in Student_Project relation that the prime key attributes are Stu_ID and Proj_ID.
According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent upon
both and not on any of the prime key attribute individually. But we find that Stu_Name can be
identified by Stu_ID and Proj_Name can be identified by Proj_ID independently. This is
called partial dependency, which is not allowed in Second Normal Form.
15
We broke the relation in two as depicted in the above picture. So there exists no partial
dependency.
o X is a superkey or,
o A is prime attribute.
We find that in the above Student_detail relation, Stu_ID is the key and only prime key attribute.
We find that City can be identified by Stu_ID as well as Zip itself. Neither Zip is a superkey nor
is City a prime attribute. Additionally, Stu_ID → Zip → City, so there exists transitive
dependency.
To bring this relation into third normal form, we break the relation into two relations as follows
16
4.2.4 Boyce-Codd Normal Form
Boyce-Codd Normal Form (BCNF) is an extension of Third Normal Form on strict terms. BCNF
states that −
In the above image, Stu_ID is the super-key in the relation Student_Detail and Zip is the super-
key in the relation ZipCodes. So,
and
Zip → City
17
EXPERIMENT 4
PRACTICING DDL COMMANDS:
DDL(Data Definition Language) : DDL or Data Definition Language actually consists of
theSQL commands that can be used to define the database schema. It simply deals with
descriptions of the database schema and is used to create and modify the structure of database
objects in the database.
Examples of DDL commands:
1) CREATE – is used to create the database or its objects (like table, index, function, views,
store procedure and triggers).
2) DROP – is used to delete objects from the database.
3) ALTER-is used to alter the structure of the database.
4) TRUNCATE–is used to remove all records from a table, including all spaces allocated
for the records are removed.
5) COMMENT –is used to add comments to the data dictionary.
6) RENAME –is used to rename an object existing in the database.
1. CHAR
2. INTEGER OR INT
3. VARCHAR
4. VARCHAR (MAX)
5. TEXT
18
CREATE DATABASE:
A Database is defined as a structured set of data. So, in SQL the very first step to store the data in
a well structured manner is to create a database. The CREATE DATABASE statement is used to
create a new database in SQL.
Syntax:
CREATE DATEBASE DATABASE_NAME;
EXAMPLE:
CREATE DATABASE DBMS;
CREATE TABLE:
Syntax:
CREATE TABLE table_name
(column1 data_type(size),column2 data_type(size),column3 data_type(size),....);
Example Query:
This query will create a table named Students with three columns, ROLL_NO, NAME and
SUBJECT.
CREATE TABLE Students(ROLL_NO int(3),NAME varchar(20),SUBJECT varchar(20));
Output:
Query OK, 0 rows affected, 1 warning (0.66 sec)
Mysql>desc students;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| ROLL_NO | int(3) | YES | | NULL | |
| NAME | varchar(20) | YES | | NULL | |
| SUBJECT | varchar(20) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
3 rows in set (0.11 sec)
Mysql> Create table passenger1(passportId int primary key,Name varchar(10) not null,Age int not
null,Sex char,Address varchar(20) not null);
19
Query OK, 0 rows affected (0.89 sec)
mysql> desc passenger1;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| passportId | int(11) | NO | PRI | NULL | |
| Name | varchar(10) | NO | | NULL | |
| Age | int(11) | NO | | NULL | |
| Sex | char(1) | YES | | NULL | |
| Address | varchar(20) | NO | | NULL | |
+------------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
20
add
21
Ticket(TicketNo);
Query OK, 0 rows affected (0.93 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> Alter table passenger1 drop foreign key fk1;
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc passenger1;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| passportId | int(11) | NO | PRI | NULL | |
| Name | char(20) | YES | | NULL | |
| Age | int(11) | NO | | NULL | |
| Sex | char(1) | YES | | NULL | |
| Address | varchar(20) | NO | | NULL | |
| TicketNo | varchar(10) | YES | MUL | NULL | |
+------------+-------------+------+-----+---------+-------+
6 rows in set (0.08 sec)
DROP:
mysql> drop table passenger1;
22
| enrolled |
| location |
| orders |
| passenger |
| persons |
| resevation |
| stu |
| student |
| students |
| ticket |
| users |
| work_in |
+----------------+
19 rows in set (0.00 sec)
TRUNCATE
Syntax:
TRUNCATE TABLE table_name;
+------+-------+--------+------+
+------+-------+--------+------+
| 1 | chari | CSE | 2 |
+------+-------+--------+------+
23
mysql> select *from student;
+--------+-----------------+------+-----+---------+-------+
+--------+-----------------+------+-----+---------+-------+
+--------+-----------------+------+-----+---------+-------+
RENAME:
Syntax:
Example:
24
EXPERIMENT 5
PRACTICING DML COMMANDS
Aim : Create a DML Commands are used to manage data within the scheme objects.
DML Commands:
DML(Data Manipulation Language) : The SQL commands that deals with the manipulation of
data present in the database belong to DML or Data Manipulation Language and this includes most
of the SQL statements.
Examples of DML:
• INSERT – is used to insert data into a table.
• UPDATE – is used to update existing data within a table.
• DELETE – is used to delete records from a database table.
INSERT COMMAND ON BUS2 & PASSENGER2 RELATIONS
mysql> select * from Bus2; Empty set (0.00 sec)
mysql> insert into bus values(1234,'Hyderabad','Tirupathi');
Query OK, 1 row affected (0.09 sec)
mysql> insert into bus values(2345,'Hyderabad','Banglore');
Query OK, 1 row affected (0.16 sec)
mysql> insert into bus values(3423,'Hyderabad','Kolkata');
Query OK, 1 row affected (0.11 sec)
mysql> select *from bus;
+-------+-----------+-------------+
| BusNo | source | Destination |
+-------+-----------+-------------+
| 1234 | Hyderabad | Tirupathi |
| 2345 | Hyderabad | Banglore |
| 3423 | Hyderabad | Kolkata |
+-------+-----------+-------------+
3 rows in set (0.00 sec)
mysql> insert into bus values(45,'Tirupathi','Banglore');
Query OK, 1 row affected (0.11 sec)
mysql> insert into bus values(34,'Hyderabad','Chennai');
Query OK, 1 row affected (0.28 sec)
25
mysql> select *from bus;
+-------+-----------+-------------+
| BusNo | source | Destination |
+-------+-----------+-------------+
| 1234 | Hyderabad | Tirupathi |
| 2345 | Hyderabad | Banglore |
| 34 | Hyderabad | Chennai |
| 3423 | Hyderabad | Kolkata
| 45 | Tirupathi | Banglore |
+-------+-----------+-------------+
5 rows in set (0.00 sec)
mysql> insert into Passenger2 values(145,'Ramesh',45,'M','abc123');
Query OK, 1 row affected (0.07 sec)
mysql> insert into Passenger2 values(278,'Geetha',36,'F','abc124');
Query OK, 1 row affected (0.11 sec)
mysql> insert into Passenger2 values(4590,'Ram',30,'M','abc12');
Query OK, 1 row affected (0.12 sec)
mysql> insert into Passenger2 values(6789,'Ravi',50,'M','abc14');
Query OK, 1 row affected (0.16 sec)
mysql> insert into Passenger2 values(5622,'Seetha',32,'F','abc55');
Query OK, 1 row affected (0.12 sec)
mysql> select *from passenger2;
+-------------+--------+------+------+---------+
| PassengerId | Name | Age | sex | address |
+-------------+--------+------+------+---------+
| 145 | Ramesh | 45 | M | abc123 |
| 278 | Geetha | 36 | F | abc124 |
| 4590 | Ram | 30 | M | abc12 |
| 5622 | Seetha | 32 | F | abc55 |
| 6789 | Ravi | 50 | M | abc14 |
+-------------+--------+------+------+---------+
5 rows in set (0.00 sec)
26
UPDATE COMMAND ON BUS RELATION
UPDATE Selected Rows & Multiple Rows
Update bus SET Source='Secundrabad' where BusNo=1234;
Query OK, 1 row affected (0.12 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select *from bus;
+-------+-------------+-------------+
| BusNo | source | Destination |
+-------+-------------+-------------+
| 1234 | Secundrabad | Tirupathi |
| 2345 | Hyderabad | Banglore |
| 34 | Hyderabad | Chennai |
| 3423 | Hyderabad | Kolkata |
| 45 | Tirupathi | Banglore |
+-------+-------------+-------------+
5 rows in set (0.00 sec)
27
+-------+-----------+-------------+
| BusNo | source | Destination |
+-------+-----------+-------------+
| 2345 | Hyderabad | Banglore |
| 34 | Hyderabad | Chennai |
| 3423 | Hyderabad | Kolkata |
| 45 | Tirupathi | Banglore |
+-------+-----------+-------------+
4 rows in set (0.05 sec)
28
EXPERIMENT 6
Querying( using ANY, ALL, IN, EXISTS, NOT EXIST, UNION, INTERSECT, Constraints
etc.)
I/O CONSTRAINTS:
The input output constraints are further divided into two distinctly different
constraints
THE PRIMARY KEY CONTRAINT:
The primary key is one or more columns in a table used ti uniquely identify each
row in the table. A table can have only one primary key. A primary key can defined in either a
create table statement and alter table statement.
It defines the column, as a mandatory column. The data held across the column
must be unique.
A single primary key is called simple key. A multicolumn primary key is called
composite primary key.
Features of primary key:
1. Primary key is a column or a set of columns that uniquely identifies a row. Its main
purpose is the Record uniqueness.
2. Primary key will not allow duplicate values and null values.
3. Primary key is not compulsory but it is recommended.
4. It helps to identify one record from another record and helps in relating tables with one
another.
5. Primary key cannot be LONG or LONGRAW data type.
6. Only one primary key is created for one table. Unique index is created
automatically if there is a primary key.
7. One table can combine up to 16 columns in a composite primary key.
Primary key at column level:
Syntax
SQL>CREATE TABLE <tablename> (<columnname>datatype
(<size>) PRIMARY KEY);
29
Example:
SQL>CREATE TABLE STUDENT (sid number(5) PRIMARY KEY, name
varchar2 (20), gpa number(3), age number(2) );
30
Syntax: SQL> CREATE TABLE <table name1>(<column name>data type (<size>)
REFERENCES <table name2> <column name>);
Example:
SQL>CREATE TABLE STUDENT (sid number (5) PRIMARY KEY, name
varchar2 (20),gpa number(3), age number(2), );
SQL>CREATE TABLE ENROLLED(sid number (5) REFERENCES student
sid, cid number (5));
Foreign key defined at table level(reference):
Syntax:
SQL>CREATE TABLE <table name1>(<column name>data type
(<size>),FOREIGN KEY (<column name>) REFERENCES
<table name2> <column name> );
Example:
SQL>CREATE TABLE STUDENT(sid (5) PRIMARY KEY, name varchar
(20),gpa number(3), age number(2) );
SQL>CREATE TABLE COURSE(cid (5) PRIMARY KEY, cname varchar2
(20), credits number(3));
31
Foreign key at table level (on delete cascade):
When the FOREIGN KEY is referenced to PRIMARY KEY of parent table the
child table is dependent on the parent table. The deletion from the parent table is not possible to
perform this we use ON DELETE CASCADE, using this to child helps us to delete the parent
and its reference child data.
Syntax:
SQL>CREATE TABLE <table name> (<columnname1>data
type(<size>) <columnname2> data type(<size>),
FOREIGN ON DELETE CASCADE);
Example:
SQL>CREATE TABLE ENROLLED ( sid number (5),
cid number (5), ON DELETE CASCADE);
The unique key constraint:
The unique column constraint permits multiple entries of NULL into the
column. These NULL values are clubbed at the top of the column in the order in which
they were entered into the table.
Key points about the unique constraint:
1. Unique key will not allow duplicate values.
2. Unique index is created automatically.
3. A table can have more than one unique key which is not possible in primary
key.
4. Unique key can combine up to 16 columns in a composite unique key.
32
sid number (5) UNIQUE,
name varchar2 (20) );
33
NOT NULL Constraint defined at the column level:
In addition to primary key and foreign key, Oracle has NOT NULL as column
constraint. The NOT NULL column constraint ensures that a table column cannot be
left empty.
When a column is defined as NOT NULL, then that column becomes a mandatory
column. It implies that a value must be entered into the column if the record is to be
accepted for storage in the table.
Syntax: SQL> CREATE TABLE <table name>
(<column name><data type> (<size>) NOT NULL);
Example:
SQL> CREATE TABLE STUDENT
( sid number (5) NOT NULL,
name varchar2 (20)
);
25
34
Syntax:
35
EXPERIMENT 7
You are going to practice queries using Aggregate functions (COUNT, SUM, AVG,
MAX,and MIN), GROUP BY, HAVING and Creation and droping of VIEWS.
LOGICAL OPERATORS
The logical operators that can be used in SQL sentences are:
The AND operator:
The oracle engine will process all rows in a table and display the result only when all of the
conditions specified using AND operators are satisfied.
The OR operator:
The oracle engine will process all rows in a table and display the result only when any of the
conditions specified using OR operators are satisfied.
The NOT operator:
The oracle engine will process all rows in a table and display only those records that do not
satisfy the conditions specified.
36
AGGREGATE FUNCTIONS
The functions that act on set of values are called group functions (or) aggregate functions.
AVG (n): Returns an average value ‘n’, ignoring null values in a column.
SUM (n): Returns the sum of n values.
MIN (n): Returns a minimum value of the n values.
MAX (n): Returns a maximum value of the n values.
COUNT ( ): Returns the number of values in expression and is NOT NULL.
COUNT (*): Returns the number of values in expression including NULL values and duplicates.
SQL QUERIS USING DIFFERENT OPERATORS
SAILORS
SID SNAME RATING AGE
22 dustin 7 45
29 brutus 1 33
31 lubber 8 55.5
32 andy 8 25
58 rusty 10 35
64 horatio 7 35
71 zorba 10 16
74 horatio 9 35
85 art 3 25.5
95 bob 3 63.5
BOATS
BID BNAME COLOR
101 interlake blue
102 interlake red
103 clipper green
104 marine red
37
RESERVES
SQL QUERIES
AIRTHMETIC OPERATORS
1. Find the names and ages of all sailors.
SQL> SELECT DISTINCT sname,age FROM sailor WHERE sailors.age<=35;
SNAME
-----------
andy
art
brutus
horato
rusty
zorba
38
SID SNAME RATING AGE
---------- -------------- ---------- --------
31 lubber 8 55.5
32 andy 8 25.5
58 rusty 10 35
71 zorba 10 16
74 horatio 9 35
3. Find the names of sailors who have reserved at least one boat.
LOGICAL OPERATORS
1. Find the names of sailors who have reserved boat number 103.
SQL>SELECT sname FROM sailors,reserves WHERE sailors.sid=reserves.sid
AND reserves.bid=103;
SNAME
----------
dustin
lubber
horati
39
SID
-------
22
22
31
31
64
3. Find the names of sailors who have reserved a red
boat. SQL>SELECT sailors.sname
FROM boats,reserves,sailors
WHERE
boats.bid=reserves.bid AND
sailors.sid=reserves.sid AND
boats.color=’red’;
SNAME
----------
dustin
lubber
horato
dustin
lubber
4. Find the names sailors who have reserves a red or a green boat.
SQL>SELECT DISTINCT sname
FROM sailors,reserves,boats
WHERE sailors.sid=reserves.sid
AND reserves.bid=boats.bid
AND (boats.color=’red’ OR boats.color=’green’);
SNAME
------------
dustin
lubber
horato
5. Find the colors of boats reserved by lubber.
40
SQL>SELECT boats.color FROM sailors,reserves,boats WHERE
sailors.sid=reserves.sid AND reserves.bid=boats.bid AND
sailors.sname=’lubber’;
COLOR
-------
red
gree
n red
6. Compute increments for the ratings of persons who have sailed two different boats on the same
day.
SQL>SELECT S.snames, S.ratings+1 AS rating
FROM sailors S, reserves R1, reserves R2
WHERE S.sid=R1.sid AND S.sid=R2.sid
AND R1.day=R2.day AND R1.bid<>R2.bid;
SNAME RATING
-------------------- ----------
dustin 8
dustin 8
PATTERN MATCHING
1. Find the ages of sailors whose name begins and ends with B and has at least 3 characters.
SQL>SELECT sailors.age FROM sailors
WHERE sailors.sname like’B%B’;
AGE
-----
63.5
41
AGGREGATE OPERTORS
1. Find the average age of all sailors.
SQL>SELECT AVG(sailors. age) FROM sailors;
AVG AGE
-------------
37.4
2. Find the average age of sailors with a rating of 10.
SQL>SELECT AVG(sailors. age)
FROM sailors
WHERE sailors.rating=10;
AVG AGE
-------------
25.5
3. Find the name of the oldest sailor.
42
SQL>SELECT sname,MAX (sailors. age)FROM sailors;
SNAME
-------------
bob
4. Find the name of the sailor whose age is minimum.
SQL>SELECT sname, MIN(sailors. age)
FROM sailors;
SNAME
-------------
zorba
5. Find the count number of different sailors names.
SQL>SELECT COUNT(DISTINCT sailors.sname)
FROM sailors;
COUNT
-------------
9
NESTED QUERIES
43
horat
o
2. Find the names of sailors who have reserved a red boat.
3. Find the names of sailors who have not reserved a red boat.
SQL>SELECT sailors.sname FROM sailors WHERE sailors.sid NOT
IN(SELECT reserves.sid FROM reserves WHERE reserves.bid
IN(SELECT boats.bid FROM boats WHERE boats.color=’red’));
SNAME
-------------
brutu
s
andy
rusty
zorba
horat
o art
bob
4. Find the names sailors who have reserved red or a green boat.
SQL> SELECT sname FROM sailors,reserves,boats WHERE
sailors.sid=reserves.sid AND reserves.bid=boats.bid AND boats.color=’red’
UNION
SELECT snameFROM sailors,reserves,boatsWHERE sailors.sid=reserves.sid
AND reserves.bid=boats.bidAND boats.color=’green’;
SNAME
44
------------
dusti
n
lubbe
r
horat
o
5. Find the names sailors who have reserved both red and a green boat.
SQL> SELECT sname FROM sailors,reserves,boats WHERE
sailors.sid=reserves.sid AND reserves.bid=boats.bid AND boats.color=’red’
INTERSECTS
SELECT sname FROM sailors,reserves,boats WHERE sailors.sid=reserves.sid
AND reserves.bid=boats.bid AND boats.color=’green’;
SNAME
-----------
dusti
n
horat
o
lubbe
r
6. Find the sid of sailors who have reserved red boats but not green boats.
SQL> SELECT sid FROM sailors,reserves,boats
WHERE sailors.sid=reserves.sid
AND reserves.bid=boats.bid
AND boats.color=’red’
EXCEPT
SELECT sidFROM sailors,reserves,boats
WHERE sailors.sid=reserves.sid
AND reserves.bid=boats.bid
AND boats.color=’green’;
SID
-------
64
45
CORRELATED NESTED QUERIES
1. Find the names of sailors who have reserved boat number 103.
SQL>SELECT sailors.sname
FROM sailors
WHERE EXISTS (SELECT *
FROM reserves
WHERE reserves.bid=103
AND reserves.sid=sailors.sid);
SNAME
------------
dustn
lubbr
horao
46
RATING AVGAGE
------------ -------------
3 45.5
7 40.0
8 40.5
10 35.0
VIEWS
a) CREATE VIEW
SQL> create view male_pass as select PNR_NO,age from Passenger where sex='m';
View created.
SQL> select * from male_pass;
PNR_NO AGE
---------- ----------
1 12
2 43
4 22
5 45
6 32
Create a view from two tables with all columns.
SQL> create view v1 as select * from Passenger full natural join Reservation;
View created.
b) INSERT
c) DROP VIEW
47
EXPERIMENT 8
TRIGGERS
AIM: To develop and execute a Trigger for Before and After update, Delete, Insert operations on
a table.
PROCEDURE
STEP 1: Start
STEP 2: Initialize the trigger with specific table id.
STEP 3:Specify the operations (update, delete, insert) for which the trigger has to be
executed.
STEP 4: Execute the Trigger procedure for both Before and After sequences
STEP 5: Carryout the operation on the table to check for Trigger execution.
STEP 6: Stop
EXECUTION
1. Create a Trigger to pop-up the DML operations
SQL> create table empa(id number(3),name varchar2(10),income
number(4),expence number(3),savings number(3));
Table created.
SQL> insert into empa alues(2,'kumar',2500,150,650);
1 row created.
SQL> insert into empa alues(3,'venky',5000,900,950);
1 row created.
SQL> insert into empa alues(4,'anish',9999,999,999);
1 row created.
48
SQL> select * from empa;
49
SQL> select * from emp;
EMPID EMPNAME INCOME EXPENSE SAVINGS
--------- --------------- ------------ ------------- -------------
2 vivek 830 150 100
3 kumar 5000 550 50
9 vasanth 987 6554 644
50
2. Create a Trigger to check the age valid or not Using Message Alert
SQL> CREATE TABLE TRIG(NAME CHAR(10),AGE NUMBER(3));
SQL> DESC TRIG;
Table created.
PROGRAM
SQL> SET SERVEROUTPUT ON;
SQL> CREATE TRIGGER TRIGNEW
AFTER INSERT OR UPDATE OF AGE ON TRIG
FOR EACH ROW
BEGIN IF(:NEW.AGE<0) THEN
DBMS_OUTPUT.PUT_LINE('INVALID AGE');
ELSE
DBMS_OUTPUT.PUT_LINE('VALID AGE');
END IF; END;
/
Trigger created.
SQL> insert into trig values('abc',15); Valid age
1 row created.
SQL> insert into trig values('xyz',-12); Invalid age
1 row created.
NAME AGE
---------- ----------
abc 15
xyz -12
Create a Trigger to check the age valid and Raise appropriate error code and error message.
SQL> create table data(name char(10),age number(3));
51
Table created.
SQL> desc data;
Name Null? Type
----------------------------------------- -------- ------------------------
NAME CHAR(10)
AGE NUMBER(3)
EXPERIMENT 9
PROCEDURES
52
AIM:To write a PL/SQL block to display the student name, marks whose average mark is above
60%.
ALGORITHM
STEP1:Start
STEP2:Create a table with table name stud_exam
STEP3:Insert the values into the table and Calculate total and average of each student STEP4:
Execute the procedure function the student who get above 60%.
STEP5: Display the total and average of student
STEP6: End
EXECUTION
SETTING SERVEROUTPUT ON:
SQL> SET SERVEROUTPUT ON
I) PROGRAM:
PROCEDURE USING POSITIONAL PARAMETERS:
SQL> SET SERVEROUTPUT ON
SQL> CREATE OR REPLACE PROCEDURE PROC1 AS
2 BEGIN
3 DBMS_OUTPUT.PUT_LINE('Hello from procedure...'); 4
END;
5/
Output:
Procedure created.
SQL> EXECUTE PROC1
Hello from procedure...
53
II) PROGRAM:
PROCEDURE USING NOTATIONAL PARAMETERS:
54
dbms_output.put_line('GCD is');
dbms_output.put_line(b);
else
dbms_output.put_line('GCD is');
dbms_output.put_line(c);
end if;
else
d:=mod(b,a)
; if(d=0) then
dbms_output.put_line('GCD is');
dbms_output.put_line(a);
else
dbms_output.put_line('GCD is');
dbms_output.put_line(d);
end if;
end if;
end;
/
Enter value for a: 8
old 8: a:=&a; new
8: a:=8;
Enter value for b: 16
old 9: b:=&b;
new 9: b:=16;
Procedure created.
SQL> set serveroutput on;
SQL> execute pro;
GCD is
55
EXPERIMENT 10
CURSORS
Aim: To write a Cursor to display the list of Male and Female Passengers.
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:');
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
56
Name of female Passengers are:
swetha
neha
PL/SQL procedure successfully completed.
b) To write a Cursor to display List of Passengers from 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.
57
58