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

DBMS Lab Manual

Uploaded by

nv55872
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

DBMS Lab Manual

Uploaded by

nv55872
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

EXPERIMENT 1

CONCEPT DESIGN WITH ER-MODEL


A) The ER or (Entity Relational Model) is a high-level conceptual data model diagram. Entity-
Relation model is based on the notion of real-world entities and the relationship between them. ER
modeling helps you to analyze data requirements systematically to produce a well-
designed database.

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

A Relationship describes relation between entities. Relationship is represented using diamonds or


rhombus.

There are three types of relationship that exist between Entities.

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.

a) One to One Relationship

This type of relationship is rarely seen in real world.

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.

b) One to Many Relationship

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.

c) Many to One Relationship

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

When an Entity is related with itself it is known as Recursive Relationship.

Ternary Relationship

Relationship of degree three is called 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.

Q) Construct an E-R diagram for a car-insurance company

Car insurance tables:


Person (driver-id, name, address)
Car (license, year, model)
Accident (report-number, date, location)
Participated (driver-id, license, report-number, damage-amount)
Q) Construct an E-R diagram for a Hospital Management

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.

Aim: To Represent all the entities (Strong, Weak) in tabular fashion.


Represent relationships in a tabular fashion.
Bus: Bus(BusNo: String, Source: String, Destination: String, CoachType: String)

Mysql> create table Bus(BusNo varchar(10),source varchar(20),Destination


varchar(20),coachType varchar(10),primary key(BusNo));

Query OK, 0 rows affected (0.77 sec)


Mysql>desc Bus;
mysql> desc Bus;

+-------------+-------------+------+-----+---------+-------+

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:

Ticket(TicketNo: string, DOJ: date, Address:string,ContactNo: string, BusNo:String


,SeatNo:Integer,Source: String, Destination: String)

ColumnName Datatype Constraints Type of Attributes


TicketNo Varchar(20) Primary Key Single-valued
DOJ Date Single-valued
Address Varchar(20) Composite
ContactNo Integer Multi-valued

BusNo Varchar(10) Foreign Key Single-valued


SeatNo Integer Simple
Source Varchar(10) Simple
Destination Varchar(10) Simple
mysql> create table Ticket(TicketNo varchar(20),DOJ date,Address varchar(20),ContactNo
varchar(15),BusNo varchar(10),SeatNo int,Source varchar(10),primary
key(TicketNo,BusNo),foreign key(BusNo) references Bus(BusNo));
Query OK, 0 rows affected (1.14 sec)

mysql> desc 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:

Passenger(PassportID: String, TicketNo:string,Name: String,


ContactNo:string,Age: integer, Sex: character, Address: String);

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

Reservation(PNRNo: String, DOJ: Date, NoofSeats: integer , Address:


String ,ContactNo: String, , BusNo: String,SeatNo:Integer)

ColumnName Datatype Constraints Type of Attributes


PNRNo Varchar(20) Primary Single-valued
Key
DOJ Date Single-valued
No_of_Seats Integer Simple
Address Varchar(20) Composite
ContactNo Varchar(10) Multi-valued
BusNo Varchar(10) Foreign Single-valued
Key
SeatNo Integer Simple

mysql> Create table Resevation(PNRNo varchar(20),DOJ date,NoofSeates integer,Address


varchar(20),ContactNo varchar(20),BusNo varchar(20),SeatNo integer, primary
key(PNRNo,BusNo),foreign key(BusNo) references Bus(BusNo));

Query OK, 0 rows affected (0.63 sec)

mysql> desc Resevation;


+------------+-------------+------+-----+---------+-------+

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:

Cancellation(PNRNo: String,DOJ: Date, SeatNo: integer,ContactNo: String,Status: String)

ColumnName Datatype Constraints Type of Attributes


PNRNo Varchar(10) Primary Key Single-valued
DOJ Date Single-valued
SeatNo Integer Simple
ContactNo Varchar(15) Multi-valued
Status Varchar(10) Simple

Mysql>create table cancellation(PNRNo varchar(10),DOJ date,SeatNo integer, ContactNo


varchar(15),Status varchar(10), primary key(PNRNo), foreign key(PNRNo) references
Resevation(PNRNo));

Query OK, 0 rows affected (0.62 sec)

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

4.1 Functional Dependency

Functional dependency FD is a set of constraints between two attributes in a relation.


Functional dependency says that if two tuples have same values for attributes A1, A2,..., An,
then those two tuples must have to have same values for attributes B1, B2, ..., Bn.

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

Trivial − If a functional dependency FD X → Y holds, where Y is a subset of X, then it is


called a trivial FD. Trivial FDs always hold.
Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-
trivial FD.

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.

We re-arrange the relation (table) as below, to convert it to First Normal Form.

14
Each attribute must contain only a single value from its pre-defined domain.

4.2.2 Second Normal Form


Before we learn about the second normal form, we need to understand the following −

• Prime attribute − An attribute, which is a part of the prime-key, is known as a prime


attribute.

• Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a


non-prime attribute.

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.

4.2.3 Third Normal Form


For a relation to be in Third Normal Form, it must be in Second Normal form and the following
must satisfy −

• No non-prime attribute is transitively dependent on prime key attribute.

• For any non-trivial functional dependency, X → A, then either −

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 −

• For any non-trivial functional dependency, X → A, X must be a super-key.

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,

Stu_ID → Stu_Name, Zip

and

Zip → City

Which confirms that both the relations are in BCNF.

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.

DATA TYPE & Description

1. CHAR

Maximum length of 8,000 characters.( Fixed length non-Unicode characters)

2. INTEGER OR INT

Integer type of data to the column.

3. VARCHAR

Maximum of 8,000 characters.(Variable-length non-Unicode data).

4. VARCHAR (MAX)

Maximum length of 2E + 31 characters, Variable-length non-Unicode data (SQL Server 2005


only).

5. TEXT

Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters.

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)

CREATING TABLES AND ALTERING THE TABLES

Create table passenger1

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)

USING ALTER COMMAND


Adding Extra column to Existing Table
Mysql> Alter table passenger1 add column TicketNo varchar(10);
Query OK, 0 rows affected (0.53 sec)
Records: 0 Duplicates: 0 Warnings: 0

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 | |
| TicketNo | varchar(10) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

20
add

Mysql> Alter Table passenger1 add Foreign key(TicketNo) references Ticket(TicketNo);


Query OK, 0 rows affected (1.56 sec)
Records: 0 Duplicates: 0 Warnings: 0
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 | |
| TicketNo | varchar(10) | YES | MUL | NULL | |
+------------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)
Modify
mysql> Alter Table passenger1 Modify column Name char(20);

Query OK, 0 rows affected (1.50 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.07 sec)
mysql> alter table passenger1 add constraint fk1 foreign key(TicketNo) references

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;

Query OK, 0 rows affected (0.61 sec)


mysql> show tables;
+----------------+
| Tables_in_dbms |
+----------------+
| b_students |
| bus |
| cancellation |
| customers |
| departments |
| emp |
| employees |

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;

mysql> select *from student;

+------+-------+--------+------+

| id | name | branch | year |

+------+-------+--------+------+

| 1 | chari | CSE | 2 |

+------+-------+--------+------+

1 row in set (0.06 sec)

mysql> truncate table student;

Query OK, 0 rows affected (1.04 sec)

23
mysql> select *from student;

Empty set (0.00 sec)

mysql> desc student;

+--------+-----------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+--------+-----------------+------+-----+---------+-------+

| id | int(11) | YES | | NULL | |

| name | varchar(20) | YES | | NULL | |

| branch | varchar(20) | YES | | NULL | |

| year | int(11) | YES | | NULL | |

+--------+-----------------+------+-----+---------+-------+

4 rows in set (0.00 sec)

RENAME:

Syntax:

RENAME TABLE old_table_name to new_table_name

Example:

RENAME TABLE student to students_info;

Query OK, 0 rows affected (0.46 sec)

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)

DELETE COMMAND ON BUS RELATION

DELETES Selected Rows and Multiple Rows


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)
mysql> Delete from bus where BusNo=1234;
Query OK, 1 row affected (0.20 sec)
mysql> select *from bus;

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

TYPES OF DATA CONSTRAINTS

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

Primary key at table level:


Syntax:
SQL> CREATE TABLE <table name>(<columnname1>data type(<size>),
<columnname2>datatype(<size>), PRIMARY KEY(<column name>,…..));
Example:
SQL>CREATETABLE STUDENT (sid number (5) ,name varchar2
(20),gpa number(3),age number(2),PRIMARY KEY(sid) );

Name Null? Type


------------------------ -------- --------------
SID NOT NULL VARCHAR2(20)
NAME VARCHAR2(30)
GPA NUMBER(2)
AGE NUMBER(3)
THE FOREIGN KEY (SELF REFERENCE) CONSTRAINT
The foreign key represents relationships between the tables. A foreign key
is a column whose values are derived from the primary key or unique key of some other
table.
The table in which foreign key is defined id called a foreign table or detail
table. A foreign key can defined in either a create table statement and alter table
statement.
Features of foreign key:
1. Foreign key is a column that references a column of a table and it can be the same
table or different.
2. Parent that is being referred has to be unique or primary key.
3. Child may have duplicates and nulls but unless it is specified.
4. Foreign key constraint can be specified on child but not parent.
5. Parent record can be deleting provided no child record exist.
6. Master table cannot be updated if child record exists.
Foreign key defined at column level

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

SQL>CREATE TABLE ENROLLED(sid number (5), cid number (5),


FOREIGN KEY (sid) REFERENCES student, FOREIGN KEY (cid)
REFERENCES course, );
Foreign key defined at column level(on delete set to null):
FOREIGN KEY referencing doesn’t allows null values in its child relation
to allow this we use on delete set to null at the time of creation.
Syntax:
SQL>CREATE TABLE <table name>(<column name>data type(<size>) ON
DELETE SET TO NULL);
Example:
SQL>CREATE TABLE STUDENT(sid (5) PRIMARY KEY, name varchar
(20),gpa number(3), age number(2) );
SQL>CREATE TABLE COURSE( cid number (5) PRIMARY KEY, cname
varchar2 (20));
SQL>CREATE TABLE ENROLLED(sid number (5)REFERENCES student ON
DELETE SET TO NULL,cid number (5), REFERENCES course ON DELETE
SET TO NULL);

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.

5. Unique key cannot be LONG or LONGRAW data type.

Unique key defined at column level:

Syntax: SQL> CREATE TABLE <table name>

(<column name>data type(<size>) UNIQUE);


Example:
SQL>CREATE TABLE STUDENT

32
sid number (5) UNIQUE,
name varchar2 (20) );

Unique key defined at table level:


Syntax:
SQL> CREATE TABLE <table name> (<columnname1>data
type(<size>) <columnname2> data
type(<size>),UNIQUE);
Example:
SQL>CREATE TABLE ENROLLED
(sid number (5),
cid number (5), UNIQUE);

Null value concepts:


A null value is different from a blank or a zero. A null value can be
inserted into columns of any data type.
Principles of NULL values:
1. Setting a NULL value is appropriate when the actual value is unknown, or when
a value would not be meaningful.
2. A NULL value is not equivalent to value of zero if the data type is number and is
not equivalent to spaces if the data type is a character.
3. A NULL value will evaluate to NULL in any expression.
4. NULL value can be inserted into columns of any data type.
Syntax:
SQL>INSERT INTO STUDENT VALUES (1, NULL);
1 ROW CREATED.
SQL>INSERT INTO STUDENT VALUES (2,’ ‘);
1 ROW CREATED.
SQL>SELECT * FROM STUDENT WHERE STDNAME=’ ’;
OUTPUT:*CANNOT EXECUTE
SQL>SELECT * FROM STUDENT WHERE STDNAME IS NULL;
OUTPUT:
THE TUPLE WHICH IS HAVING NULL VALUE IN THE STUDENT NAME IS
PRINTED

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

The CHECK constraint:


Business rule validations can be applied to a table column by using
CHECK constraint. CHECK constraints must be specified as a logical expression that
evaluates either to true or false.

25

34
Syntax:

SQL>CREATE TABLE <table name>


(<column name><data type> (<size>)
CHECK (<logical expression>));
Example:
SQL> CREATE TABLE EMP
( empno number (5) NOT NULL,
empname varchar2 (20),
salary number(10) CHECK (salary>1000));

SQL>INSERT INTO EMP VALUES (1,’ramu’, 500);


Error:
Check constraint (SYSTEM.SYS_C005285) violated

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.

COMPUTATIONS DONE ON TABLE DATA


TYPES OF OPERATORS
ARITHMETIC OPERATORS
Oracle allows arithmetic operators to be used while viewing the records from a
table or while performing the manipulation operations such as INSERT, UPDATE and
DELETE.
The operators include:
+ Addition
- Subtraction
/ Division
* Multiplication
** Exponentiation
() Enclosed operation

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

SID BID DAY


22 101 10-OCT-98
22 102 10-OCT-98
22 103 10-AUG-98
22 104 10-JUL-98
31 102 11-OCT-98
31 103 11-JUN-98
31 104 11-DEC-98
64 101 09-MAY-98
64 102 09-AUG-98
74 103 09-AUG-98

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

2. Find all sailors with rating above 7.


SQL> SELECT sid,sname,rating,age
FROM sailors
WHERE sailors.rating>7;

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.

SQL>SELECT DISTINCT sailors.sname


FROM sailors, reserves WHERE sailors.sid=reserves.sid;
SNAME
-------------
dustin
horato
lubber

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

2. Find the sids of sailors who have reserved a red boat.


SQL>SELECT sid FROM boats,reserves WHERE boats.bid=reserves.bid AND
boats.color=’red’;

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

2. Find the ages of sailors whose name begins with D.


SQL>SELECT sailors.age FROM sailors
WHERE sailors.sname like’D%’;
AGE
-----
45

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

1. Find the names of sailors who have reserved boat 103.


SQL>SELECT sailors.sname
FROM sailors
WHERE sailors.sid IN(SELECT reserves.sid
FROM reserves
WHERE reserves.bid=103);
SNAME
--------
dusti
n
lubbe
r

43
horat
o
2. Find the names of sailors who have reserved a red boat.

SQL>SELECTsailors.sname FROM sailors WHERE sailors.sid IN(SELECT


reserves.sid FROM reserves WHERE reserves.bid IN(SELECT boats.bid
FROM boats WHERE boats.color=’red’));
SNAME
----------
dustin
lubber
horatio

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

GROUP BY AND HAVING CLAUSES


1. Find the average age of the sailors for each rating level that has at least two sailors.
SQL>SELECT sailors.rating,AVG(sailors.age) AS avgage
FROM sailors
GROUP BY sailors.rating
HAVING COUNT(*) >1;
RATING AVGAGE
------------ -------------
3 44.5
7 40.5
8 40.5
10 25.5
2. Find the average age of the sailors who are of voting age(i.e. at least 18 years old) for each
rating level that has at least two sailors.
SQL>SELECT S.rating,AVG(S.age) AS avgage FROM sailors S WHERE
S.age>=18 GROUP BY S.rating HAVING 1< (SELECT COUNT(*) FROM
sailors S2 WHERE S.rating=S2.rating);

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

SQL> insert into male_pass values(&PNR_NO,&age);


Enter value for pnr_no: 12
Enter value for age: 22
old 1: insert into male_pass values(&PNR_NO,&age)
new 1: insert into male_pass values(12,22)
1 row created.

c) DROP VIEW

SQL> drop view male_pass;


View dropped.

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;

ID NAME INCOME EXPENCE SAVINGS


---------- ---------- ---------- ---------- ---------------------------------------
2 kumar 2500 150 650
3 venky 5000 900 950
4 anish 9999 999 999

TYPE 1- TRIGGER AFTER UPDATE


------------------------------------------------
SQL> CREATE OR REPLACE TRIGGER VIJAY
AFTER UPDATE OR INSERT OR DELETE ON EMP
FOR EACH ROW
BEGIN
IF UPDATING THEN
DBMS_OUTPUT.PUT_LINE('TABLE IS UPDATED');
ELSIF INSERTING THEN
DBMS_OUTPUT.PUT_LINE('TABLE IS INSERTED');
ELSIF DELETING THEN
DBMS_OUTPUT.PUT_LINE('TABLE IS DELETED');
END IF;
END;
/
Trigger created.
SQL> update emp set income =900 where empname='kumar';
TABLE IS UPDATED
1 row updated.
SQL> insert into emp values ( 4,'Chandru',700,250,80);
TABLE IS INSERTED
1 row created.
SQL> DELETE FROM EMP WHERE EMPID = 4;
TABLE IS DELETED
1 row deleted.

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

TYPE 2 - TRIGGER BEFORE UPDATE


SQL> CREATE OR REPLACE TRIGGER VASANTH
BEFORE UPDATE OR INSERT OR DELETE ON EMPLOYEE
FOR EACH ROW
BEGIN
IF UPDATING THEN
DBMS_OUTPUT.PUT_LINE('TABLE IS UPDATED');
ELSIF INSERTING THEN
DBMS_OUTPUT.PUT_LINE('TABLE IS INSERTED');
ELSIF DELETING THEN
DBMS_OUTPUT.PUT_LINE('TABLE IS DELETED');
END IF;
END;
/
Trigger created.

SQL> INSERT INTO EMP VALUES (4,'SANKAR',700,98,564);


TABLE IS INSERTED
1 row created.
SQL> UPDATE EMP SET EMPID = 5 WHERE EMPNAME = 'SANKAR';
TABLE IS UPDATED
1 row updated.
SQL> DELETE EMP WHERE EMPNAME='SANKAR';
TABLE IS DELETED
1 row deleted.

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.

Name Null? Type


-------------------------------------------- -------- -------------------------
NAME CHAR(10)
AGE NUMBER(3)

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)

SQL> CREATE TRIGGER DATACHECK


AFTER INSERT OR UPDATE OF AGE ON DATA
FOR EACH ROW
BEGIN IF(:NEW.AGE<0)
THEN
RAISE_APPLICATION_ERROR(-20000,'NO NEGATIVE AGE ALLOWED');
END IF;
END;
/
Trigger created.
SQL> INSERT INTO DATA VALUES('ABC',10);
1 ROW CREATED.
SQL> INSERT INTO DATA VALUES ('DEF',-15)
*
ERROR at line 1:
ORA-20000: No negative age allowed ORA-
06512: at "4039.DATACHECK", line 3
ORA-04088: error during execution of trigger '4039.DATACHECK'
NAME AGE
---------- ----------
abc 10

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

PL/SQL procedure successfully completed.

53
II) PROGRAM:
PROCEDURE USING NOTATIONAL PARAMETERS:

SQL> CREATE OR REPLACE PROCEDURE


PROC2
2(N1 IN NUMBER,N2 IN NUMBER,TOT OUT
NUMBER) IS
3 BEGIN
4TOT := N1 + N2;
5 END;
6/
Output:
Procedure created.
SQL> VARIABLE T NUMBER
SQL> EXEC PROC2(33,66,:T)
PL/SQL procedure successfully completed.
SQL> PRINT T
T
----------
99
PROCEDURE FOR GCD NUMBERS
III) PROGRAM:
SQL> create or replace procedure pro
is
a number(3);
b number(3);
c number(3);
d number(3);
begin a:=&a;
b:=&b;
if(a>b) then
c:=mod(a,b);
if(c=0) then

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

You might also like