Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

INDEX

Exp.No. Date Title of the Experiment Page No. Signature

Creating database, table & Integrity constraints


01 23.01.2024 * Creation of a database and writing SQL queries to retrieve 01
information from the database

Working with Data Manipulation commands


02 02.02.2024 * Performing Insertion, Deletion, Modifying, Altering, 04
Updating and Viewing records based on conditions.

Construct a ER Model for the application to be


03 09.02.2024 07
constructed to a Database

04 16.02.2024 Basic SQL Functions 12


*single row, aggregate

05 16.03.2024 SQL Joins 15


* inner, outer & self-join

06 01.03.2024 SQL Sub Quires 20


* Nested Queries

DB Objects Creation of DB Views, Synonyms,


07 01.03.2024 22
Sequence, Indexes, Save point.

08 15.03.2024 Basics of PL/SQL block to satisfy some conditions


by accepting input from the user and handling different types of exception.
30

Frame and execute the appropriate PL/SQL


09 15.03.2024 39
Cursors

10 22.03.2024 Creation of database triggers 41

Frame and create the appropriate Exception


11 22.03.2024 46
handling for the Project

12 01.04.2024 Creation of Functions for the Project 49

Frame and execute the appropriate PL/SQL


13 01.04.2024 51
Procedures for the Project

Design of Airline Reservation Management


14 08.04.2024 53
System

Deployment of Airline Reservation Management


15 17.04.2024 65
System
EX NO : 01 CREATING DATABASE, TABLE & INTEGRITY CONSTRAINTS
* Creation of a database and writing SQL queries to retrieve information from the database.

DATE :

AIM:
To Creation of a database and writing SQL queries to retrieve information from the
database.

(i) Write a SQL query to create a table


CREATE TABLE Students (
StudentID int NOT NULL,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

---> To View the table DESC Student;

(ii) Write a SQL query to drop the city


ALTER TABLE Student
DROP COLUMN CITY;

1
(iii) Write a SQL query to change the details
ALTER TABLE Student RENAME COLUMN Address TO Details;

(iv) Write a SQL query adding a phone number in the existing table
ALTER TABLE Student ADD Phone varchar(255);

(v) Write a SQL query to change PID data type (int, varchar)
ALTER TABLE Student
ADD CONSTRAINT STUDENTID PRIMARY KEY (STUDENTID);

2
(vi) Write a SQL query to update constraints
ALTER TABLE Student
MODIFY Phone int;

(vii) Write a SQL query to set a range for 10 digits exactly for phone number
ALTER TABLE student
ADD CONSTRAINT check_ten_digits
CHECK (LENGTH(phone) = 10 AND phone NOT LIKE '%[^0-9]%');

RESULT:
Hence Data Definition language commands in structured query language are
performed and output verified.

3
EX NO : 02 WORKING WITH DATA MANIPULATION COMMANDS
* Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on conditions.

DATE :

AIM:
To Creation of a database and writing SQL queries to retrieve information from the
database.

(i) INSERT:
Purpose:
To add records to the table
Syntax:
i. Direct method - only one record can be inserted in the field at a time
➢ Insert into <table name> values <values for all columns>
ii. Null method - we can skip some fields
➢ Insert into <table name> (column name) values (values for columns)
iii. Macro method - More than one value can be inserted in the field at a time
➢ Insert into <table name> values <&column names>

(ii) SELECT:
Purpose:
To retrieve or view records within the table
Syntax:
➢ Select * from <table name>
➢ Select * from <table name> where (condition)
➢ Select (column name) from <table name>

(iii) UPDATE:
Purpose:
To modify records within the table
Syntax:
➢ Update <table name> set (column name) = (value)
➢ Update <table name> set (column name) = (value) where (condition)

(iv) DELETE:
Purpose:
To modify records from a table
Syntax:
➢ Delete from <table name>
➢ Delete from <table name> where (condition)

4
EXAMPLE QUERIES:

(i) Write a SQL query to Performing Insertion


INSERT INTO Students (StudentID, FirstName, LastName, Address, Phone)
VALUES (1, 'Vibhi', 'R V', 'Chennai', '9876543210'),
(2, 'Madhavan', 'V', 'Chrompet', '9987754321'),
(3, 'Yaswanth', 'S', 'Nellore', '9976540321');

(ii) Write a SQL query to Performing Deletion


DELETE FROM Students
WHERE StudentID = 3;

(iii) Write a SQL query to Performing Modifying


UPDATE Students
SET Phone = '8776702345'
WHERE StudentID = 2;

5
(iv) Write a SQL query to Performing Altering
ALTER TABLE Students
ADD Email varchar(255);

(v) Write a SQL query to Performing Updating


UPDATE Students
SET Email = 'vibhi@gmail.com'
WHERE StudentID = 1;

(vi) Write a SQL query to Viewing records based on conditions.


SELECT *
FROM Students
WHERE FirstName = 'Vibhi';

RESULT:
Hence Data manipulation commands (INSERT, DELETE, UPDATE, ALTER,
SELECT) in structured query language are performed and output verified.

6
EX NO : 03 CONSTRUCT A ER MODEL FOR THE APPLICATION TO BE
CONSTRUCTED TO A DATABASE

DATE :

AIM:
The aim of this experiment is to design and construct an Entity-Relationship (ER)
model for an application that will be implemented in a database management system.

REQUIREMENTS:
❖ Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or faster
processor with at least 1GB RAM and 500 MB free disk space.
❖ MySQL 5.6.1

PROCEDURE:
(i) Identifying Entities and Attributes:
➢ Analyze the application domain and identify relevant entities and their
attributes.
➢ Create a list of entities and their respective attributes based on the
requirements.

(ii) Defining Relationships:


➢ Identify relationships between entities (e.g., one-to-one, one-to-many,
many-to-many).
➢ Determine the cardinality and participation constraints for each relationship.

(iii) Constructing the ER Diagram:


➢ Use an ER diagramming tool to create an Entity-Relationship (ER) diagram.
➢ Represent entities as rectangles, attributes as ovals connected to entities, and
relationships as diamonds connecting related entities.
➢ Label each relationship with cardinality and participation constraints (e.g., 1:1,
1:N, M:N).

(iv) Refining and Validating the ER Model:


➢ Review the ER diagram for completeness and correctness.
➢ Ensure that all entities, attributes, and relationships are properly represented.
➢ Validate the model to ensure data integrity and consistency.

(v) Documenting the ER Model:


➢ Provide a detailed description of each entity, including its attributes and
relationships.
➢ Document cardinality and participation constraints for each relationship.
➢ Include any additional notes or considerations related to the ER model.

7
EXAMPLE:
Entities:
1. BUS
2. Ticket
3. Passenger

Relationships:
1. Reservation
2. Cancellation

Primary Key Attributes:


1. Ticket ID (Ticket Entity)
2. Passport ID (Passenger Entity)
3. Bus_NO (Bus Entity)

E-R Model
Attributes of the following Entities

(i) BUS
❖ BusNo
❖ Source
❖ Destination
❖ CoachType

SCHEMA
Bus: Bus (BusNo: String, Source: String, Destination: String, CoachType: String)

8
(ii) TICKET
❖ TicketNo
❖ DOJ
❖ Address
❖ ContactNo
❖ BusNo
❖ SeatNo
❖ Source
❖ Destination
SCHEMA
Ticket(TicketNo: string, DOJ: date, Address:string,ContactNo: string, BusNo:String,
SeatNo:Integer,Source: String, Destination: String)

(iii) PASSENGER
❖ PassportID
❖ TicketNo
❖ Name
❖ ContactNo
❖ Age
❖ Sex
❖ Address
SCHEMA
Passenger(PassportID: String, TicketNo:string,Name: String, ContactNo:string,Age:
integer, Sex: character, Address: String)

9
(iv) RESERVATION
❖ PNRNo
❖ DOJ
❖ No_of_seats
❖ Address
❖ ContactNo
❖ BusNo
❖ SeatNo

SCHEMA
Reservation(PNRNo: String, DOJ: Date, NoofSeats: integer , Address: String,
ContactNo: String, , BusNo: String,SeatNo:Integer)

(v) CANCELLATION
❖ PNRNo
❖ DOJ
❖ SeatNo
❖ ContactNo
❖ Status

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

10
Concept design with E-R Model:

RESULT:

Hence Entity-Relationship (ER) model successfully constructed for the application


database.

11
EX NO : 04 BASIC SQL FUNCTIONS
*single row, aggregate
DATE :

AIM:
To execute simple query using SQL Functions.

SQL FUNCTION:
❖ Set of instructions which will do some specific task
❖ It may or may not return the value
❖ It’s the module.

TYPES
(i) Single row function

1. Data function
2. Numeric function or arithmetic or mathematical Function
3. Character function
4. General function or Miscellaneous function

DATE FUNCTIONS

01. Write a query to increase dates by number of months specified.


SQL>SELECT ADD_MONTHS (SYSDATE, 2) FROM DUAL;
ADD_MONTH
-------------------
13-APR-01

02. Write a query it find today’s date.


SQL>SELECT SYSDATE FROM DUAL;
SYSDATE
--------------
13-FEB-01

03. Write a query to find last date in a month of date specified.


SQL>SELECT SYSDATE, LAST_DAY (SYSDATE) FROM DUAL;
SYSDATE LAST_DAY
-------------------------------------
13-FEB-01 28-FEB-01

12
04. Write a query to find number of months between two dates.
SQL>SELECT MONTHS_BETWEEN (TO_DATE (’04-MAY-2001’,’DD-MON
YYYY’), TO_DATE (’14-FEB-2001’, ’DD-MON-YYYY’)) FROM DUAL;
MONTHS_BETWEEN (TO_DATE (’04-MAY-2001’, ’DD-MON-YYYY’),
TO_DATE(’14-FEB-2001’, ’DD-MON-YYYY’))
------------------------------------------------------------------------------------
2.6774194

05. Write a query to find the next day in a month of date specified
SQL>SELECT NEXT_DAY(SYSDATE,’SUNDAY’) FROM DUAL;
NEXT_DAY(
-----------------
18-FEB-01

06. Write a query to round off a particular date to next year


SQL>SELECT ROUND(SYSDATE,’YEAR’)FROM DUAL;
ROUND(SYS
-----------------------
01-JAN-01

07. Write a query to round off a particular date to next month


SQL>SELECT ROUND(SYSDATE,’MONTH’)FROM DUAL;
ROUND(SYS
-----------------------
01-FEB-01

08. Write a query to round off a particular date to next day.


SQL>SELECT ROUND(SYSDATE,’DAY’)FROM DUAL;
ROUND(SYS
-----------------------
11-FEB-01

09. Write a query to round off particular date to year preceding it.
SQL>SELECT TRUNC SYSDATE,’YEAR’) FROM DUAL;
TRUNC (SYS
---------------------
01-JAN-01

10. Write a query to round off particular date to month preceding it.
SQL>SELECT TRUNC SYSDATE,’MONTH’) FROM DUAL;
TRUNC (SYS
---------------------
01-FEB-01

13
11. Write a query to round off particular date to day preceding it.
SQL>SELECT TRUNC SYSDATE,’DAY’) FROM DUAL;
TRUNC (SYS
---------------------
11-FEB-01

12. Write a query to find greatest date


SQL>SELECT GREATEST(SYSDATE,TO_DATE(’11-APR-2001’, ‘DD-MON
YYYY’))FROM DUAL;
GREATEST(
-------------------
11-APR-01

13. Write a query to add 10 days from current date


SQL>SELECT SYSDATE+10 FROM DUAL;
SYSDATE+10
-------------------
23-FEB-01

RESULT:
Hence basic SQL functions were executed, database operations performed and output
verified.

14
EX NO : 05 SQL JOINS
* inner, outer & self-join
DATE :

AIM:
To know the use of join operators in SQL.

JOIN:
A join is used to combine rows from multiple tables. A join is performed whenever
two or more tables are listed in the form clause of an SQL statement.

TABLE STRUCTURE:

SQL>desc suppliers;
Name NULL? Type
------ --------- --------- -----------------
Supplier_id number(5)
Supplier_name varchar2(25)
SQL>desc order;

NAME NULL? TYPE


----- - --------- -------------- --------- ------- ----------
Order_id number(6)
Supplier_id number(5)
Order_date date
SQL>select * from suppliers;

SUPPLIER:
Supid supname
------- ------ --------- ------
12 abi
13 chindu
14 nithi
15 selvi

ORDER:
Oid supid odate
------- ------- ---------- ------- --------- -------
111 12 1/9/09
222 23 8/9/09
333 14 6/9/09
444 25 3/9/09
555 15 17/9/09

15
NATURAL JOINS:
SQL>select * from supplier,ord where supplier.supid=ord.supid;
Supid supname Oid supid odate
-------- ---------- ----------- --------------- ------------- ---------- ------
12 abi 111 12 1/9/09
14 nithi 333 14 6/9/09
15 selvi 555 15 17/9/09

OUTER JOIN:
Left outer join:
SQL>select supplier.suPID ,supplier.suPNAME,ord.oDATE where supplier.su PID(+)=ord
.suPID;

SuPID SuPNAME Odate


--------- --------- --------- --------- -------- ----------
12 abi 1/9/09
14 nithi 6/9/09
15 selvi 17/9/09
8/9/09
3/9/09
Right outer join:
SQL>select supplier.suPID ,supplier.suPNAME,ord.oID,ord.oDATE from supplier.ord
where supplier.suPID = ord.suPID(+);

SuPID SuPNAME oid Odate


-------- --------- --------- --------- -------- -------------
12 abi 111 1/9/09
14 nithi 333 6/9/09
15 selvi 555 17/9/09
13 chindu

Full outer join:


SQL>select * from supplier,ord where supplier.suPID(+) = ord.suPID(+) Union select * from
supplier,ord where supplier.suPID=ord.suPID(+);

SuPID SuPNAME oid supid Odate


--------- --------- --------- --------- -------- ------------- ----
12 abi 111 12 1/9/09
13 chindu
14 nithi 333 14 6/9/09
15 selvi 555 15 17/9/09
222 23 8/9/09
444 25 3/9/09

16
EXAMPLE QUERIES :
(i) Create a db student with attributes & another database advisor with a set of attributes &
come up with a relationship table in which the db contains student name with corresponding
advisor.
SQL>Select * from student crossjoin advisor;
Stu
fname lname dob dues dept employ adv_no fname lname dob sal dept
no
122 ante rtie ni 20.05.27 25000 cse a900 00 122 john mart ieni 20.05.17 25000 cse

122 ante rtie ni 20.05.27 25000 cse a800 00 111 mark rain 15.06.11 35000 cse

122 ante rtie ni 20.05.27 25000 cse a700 00 333 mark rain 15.06.11 35000 cse

122 ante rtie ni 20.05.27 25000 cse 1 10 bond john 20.07.98 15000 eee

(ii) Create db employee with set of attributes similarly another db called parking lot with set
of attributes, where output should have employee name who use parking lot.
SQL>Selectname from employee park innerjoin parking on employee.park=parking;

FNAME

JOHN

MARK

bond

dejane

(iii) Display the name, city & birth month of the employees with following cosiderations:
a) employee address contains e_name, country & city details, e_id.
b) employee payroll contains e_id,e_dept, e_birthdate&doj.

SQL> Selectename,doj,city from emp1 innerjoin emp2 on emp1.eid=emp2.eid;

FNAME DOB CITY


JOHN 20-MAY-27 Chennai
MANOJ 5-JUL-10 Bangalore
MAOPI 1-JAN-12 Kolkata
MARKIL 5-MAR-13 Delhi
MARK 1-APR-11 Mumbai
bond 20-JUL-98 Rajastan
dejane 20-JUN-93 Hyderabad

17
(iv) List emp_id& gender for all married empls& include the names of any charity to which
the employee donate via the company program.
SQL>Selecteid,gender from employee innerjoin charity on employee.char = charity.char;

EID GENDER
RA01 Male
RA03 Female
RA05 Male

(v) Get employee name, project name, order by first name from employee detail & project
detail for those employee who have assigned project already.

SQL>Selectename,project_name from emp1 inner join project on emp1.eid = project.eid;

ENAME PROJECT_NAME
Westbrook Machine Learning
Serena Biometrics
Wade Big data

(vi) Get employee name, project name, order by first name from employee detail & project
detail for those employee who have not assigned project.
SQL>Selectemp.name from emp join project on emp.id, project.id where original=’no’;

NAME
Harden
Sumitha
Wakarimashita

(vii) Display emp_name, project name from emp_detail&project_detail for all employees if
not project is assigned then display no project assigned.
SQL>select emp.name,emp.pnameproject.assign from emp join project on emp.id= project.id;

NAME PROJECT_NAME
Aikon Not Assigned
Ovonel Not Assigned
Durantula Not Assigned

18
(viii) Get all project name even they have not matching any emp_id in the left table order
by first name from emp_detail&project_detail.
SQL> Selectproject_namefrom emp1 left outer join project on emp1.eid = project.p_id;

PROJECT_NAME
Machine learning
Big data
Cache developement

(ix) Write a query to fetch emp.name & project who has assigned more than one project.
SQL>select ename,pname from emp1.join project on emp1.eid = project.eid where
pname in (Select ename from emp1 group by pname having count(*)>1);

ENAME PROJECT_NAME
Ni san Machine Learning
Ni san Biometrics

RESULT:
Thus SQL joins are executed to combine data from multiple tables and output
validated.

19
EX NO : 06 SQL SUB QUIRES
* Nested Queries
DATE :

AIM:
To perform Sub Queries using DML command.

(i) Subqueries with the Select Statement

Consider the EMPLOYEE table have the following records:

The subquery with a SELECT statement will be:


SELECT * FROM EMPLOYEE
WHERE ID IN (SELECT ID FROM EMPLOYEE WHERE SALARY > 4500);

(ii) Subqueries with the INSERT Statement

INSERT INTO EMPLOYEE_BKP


SELECT * FROM EMPLOYEE
WHERE ID IN (SELECT ID FROM EMPLOYEE);

20
(iii) Subqueries with the UPDATE Statement

UPDATE EMPLOYEE SET SALARY = SALARY * 0.25

WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 29);

(iv) Subqueries with the DELETE Statement


DELETE FROM EMPLOYEE WHERE AGE IN (SELECT AGE FROM
EMPLOYEE_BKP WHERE AGE >= 29 );

RESULT:
Hence the SQL subqueries executed to retrieve specific data subsets and output
validated.

21
EX NO : 07 DB OBJECTS CREATION OF DB VIEWS, SYNONYMS,
SEQUENCE, INDEXES, SAVE POINT.
DATE :

AIM:
To implement the creation of Views, Synonyms, Sequences, Indexes and Save point
using SQL.

(i) VIEWS:
View is a virtual table based on the result set of an SQL statement. It does not
physically exist. Rather, it is created by a query joining one or more tables.

Creating a View:
CREATE VIEW view_name AS
SELECT columns
FROM table
WHERE predicates;

Updating a View:
CREATE OR REPLACE VIEW view_name AS
SELECT columns
FROM table
WHERE predicates;

Dropping a View:
DROP VIEW view_name;

(ii) SYNONYMS:
Synonyms are alternate names for an existing object which are permanently stored in
the database. The various objects for which synonyms can be created are as follows:
❖ Tables
❖ Views
❖ Materialized Views
❖ Stored Function
❖ Stored Procedures
❖ Packages
❖ Sequences and Synonyms

Allowing SCOTT to create synonym:


SQL > connect sys/sys @xe as sysdba -- Let us login as SYS DBA
Connected.
SQL > grant create synonym to scott; -- Grant CREATE SYNONYM privilege to SCOTT user
Grant succeeded.

22
Now SCOTT user can create and use synonyms.
SQL > create synonym EMPLOYEE for EMP;
Synonym created.
SQL > select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600
SQL > select * from employee;
EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600

Granting Privileges:
❖ Granting privileges on the SYNONYM grants the privileges on the actual object.
❖ Suppose SCOTT user gives SELECT permission on EMPLOYEE synonym to JOHN
user then JOHN user will actually be given the specified permission on both the
synonym and the actual table.
SQL > connect scott/tiger @xe
SQL > grant select on employee to john;
Grant succeeded.
SQL > connect john/john @ xe
Connected.
SQL > select * from scott.employee;
EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600
SQL > select * from scott.emp;
EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600

Grantee (John) creating synonym for grantor's (Scott) table:


SQL > connect scott/tiger @ xe
Connected.
SQL > grant select on emp to john;
Grant succeeded.
SQL > connect john/john @ xe
Connected.
SQL > create synonym EMPLOYEE for scott.emp;
Synonym created.
SQL > select * from employee;
EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600

23
Data Dictionary for Synonyms:
“USER_SYNONYMS” is the data dictionary for synonyms.
SQL > select * from user_synonyms;
SYNONYM_NAME TABLE_OWNER TABLE_NAME DB_LINK
EMPLOYEE SCOTT EMP -

Dropping Synonym:
The DROP SYNONYM command can be used to remove a synonym.

SQL > drop synonym employee;


Synonym Dropped.

(iii) SEQUENCES:
Sequence can be used to generate numbers in a sequence. This can be used to generate
values for primary keys.

Creating Sequence:
CREATE SEQUENCE <sequence_name>
START WITH <integer_value>
INCREMENT BY <integer_value>
MAXVALUE <integer_value> OR NOMAXVALUE
MINVALUE <integer_value> OR NOMINVALUE
CYCLE OR NOCYCLE
CACHE OR NOCACHE
ORDER OR NOORDER

❖ START WITH <integer_value>:


➢ Specify the first sequence number to be generated.

❖ INCREMENT BY <integer_value>:
➢ The integer number by which the sequence number should be incremented for
generating the next number. If it is positive, then values are ascending, and if it
is negative, then values are descending. The default value is 1.

❖ MAXVALUE <integer_value>:
➢ If the increment value is positive, then MAXVALUE determines the maximum
value up to which the sequence numbers will be generated.

❖ NOMAXVALUE:
➢ Specifies a maximum value of 10^27 for an ascending sequence or -1 for a
descending sequence.

❖ MINVALUE <integer_value>:
➢ If the increment value is negative, then MINVALUE determines the minimum
value up to which the sequence numbers to be generated.

24
❖ NOMINVALUE:
➢ Specifies a minimum value of 1 for an ascending sequence and -10^26 for a
descending sequence.

❖ CYCLE:
➢ Causes the sequences to automatically recycle to the min value when the max
value is reached for ascending sequences; for descending sequences, it causes a
recycle from the min value back to the max value.

❖ NOCYCLE:
➢ Sequence numbers will not be generated after reaching the maximum value for
an ascending sequence or minimum value for a descending sequence.

❖ CACHE:
➢ Specifies how many values are pre-allocated in buffers for faster access. The
default value is 20.

❖ NOCACHE:
➢ Sequence numbers are not pre-allocated.

❖ ORDER:
➢ Generate the numbers in a serial order.

❖ NOORDER:
➢ Generate the numbers in a random order.

For example,
SQL > create sequence seq_empno
start with 1000
increment by 1
maxvalue 9999
nocycle
cache 2
order
/
Sequence created.

Initializing Sequence:
A sequence needs to be initialized before being used. Every sequence is initialized by
a pseudo-column NEXTVAL. Initialization means the START WITH <value> is assigned to
the sequence.
SQL > select seq_empno.nextval from dual;
NEXTVAL
1000

25
Determining the Last Running Sequence Number:
We can query the sequence for the currently held value by using the pseudo-column
CURRVAL meaning the current value.
SQL > select seq_empno.currval from dual;
CURRVAL
1000

Accessing the Successive Sequence Values:


The consecutive sequence values can be accessed by using the NEXTVAL
pseudo-column. NEXTVAL increments the previous value in the sequence object by the value
specified in the INCREMENT BY clause.
SQL > select seq_empno.nextval from dual;
NEXTVAL
1001

Using sequence in INSERT command:


SQL > insert into emp(empno, ename, sal, comm., deptno) values
(seq_empno.nextval,’Swathi’, 8000, 500, 10);
1 row created.
SQL > select * from emp;
EMPNO ENAME JOB HIREDATE SAL COMM DEPTNO
1002 Swathi - - 8000 500 10

Modifying Sequence:
SQL > alter sequence seq_empno INCREMENT BY 2
Sequence altered.
SQL > select seq_empno.currval from dual;
CURRVAL
1002
SQL > select seq_empno.nextval from dual;
NEXTVAL
1004

Data Dictionary for Sequences:


SQL > select * from user_sequences;
SEQUENCE MIN MAX INCREMENT CYCLE ORDER CACHE LAST
NAME VALUE VALUE BY FLAG FLAG SIZE NUMBER
SEQ_EMPNO 1 9999 2 N Y 2 1008

Dropping Sequence:
SQL > drop sequence seq_empno;
Sequence dropped.

26
User Allowing SCOTT to create synonym:
SQL > connect sys/sys @xe as sysdba -- Let us log in as SYS DBA
Connected.
SQL > grant create synonym to scott; -- Grant CREATE SYNONYM privilege to
SCOTT user
Grant succeeded.

Now SCOTT user can create and use synonyms.


SQL > create synonym EMPLOYEE for EMP;
Synonym created.

SQL > select * from emp;


EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600

SQL > select * from employee;


EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600

Granting Privileges:
❖ Granting privileges on the SYNONYM grants the privileges on the actual object.
❖ Suppose SCOTT user gives SELECT permission on EMPLOYEE synonym to JOHN
user then JOHN user will actually be given the specified permission on both the
synonym and the actual table.
SQL > connect scott/tiger @xe
SQL > grant select on employee to john;
Grant succeeded.
SQL > connect john/john @ xe
Connected.

SQL > select * from scott.employee;


EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600

SQL > select * from scott.emp;


EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600

27
Grantee (John) creating synonym for grantors (Scott) table:
SQL > connect scott/tiger @ xe
Connected.
SQL > grant select on emp to john;
Grant succeeded.
SQL > connect john/john @ xe
Connected.
SQL > create synonym EMPLOYEE for scott.emp;
Synonym created.
SQL > select * from employee;
EMPNO ENAME JOB MGR HIREDATE SAL
7369 SMITH CLERK 7902 17-DEC-80 800
7499 ALLEN SALESMAN 7698 20-FEB-81 1600

Data Dictionary for Synonyms:


“USER_SYNONYMS” is the data dictionary for synonyms.
SQL > select * from user_synonyms;
SYNONYM_NAME TABLE_OWNER TABLE_NAME DB_LINK
EMPLOYEE SCOTT EMP -

Dropping Synonym:
The DROP SYNONYM command can be used to remove a synonym.
SQL > drop synonym employee;
Synonym Dropped.

(iv) INDEXES:
Index is an object which can be defined as the ordered list of values of a column or
combination of columns used for faster searching and sorting of data.

Creating Index:
SQL > create index ind_student_college on student(college);
Index created.
Where ind_student_college is the user-defined name for the index object.

Removing Index:
SQL > drop index ind_student_college;
Index dropped.

Creating index on multiple columns:


SQL > create index ind_student_college_rollno on student(college, rollno);
Index created.

28
(v) SAVE POINT:
Oracle provides a feature wherein we can define save points in between various DML
(insert, update, delete) operations so that at a later stage we can rollback changes to a specific
save point.

Creating Save point:


SQL > savepoint savepoint_name;
Eg. SQL > savepoint sp1;
Savepoint created.

Rolling back to save point:


SQL > rollback to savepoint sp1;
Rollback complete.

RESULT:
Thus the creation of database objects such as views, synonyms, sequences, indexes,
and save points commands in SQL are performed and output verified.

29
EX NO : 08 BASICS OF PL/SQL BLOCK TO SATISFY SOME CONDITIONS
by accepting input from the user and handling different types of exception.

DATE :

AIM:
To write PL/SQL programs using procedures and functions.

DESCRIPTION:

PL / SQL PROGRAMMING:

❖ Procedural Language/Structured Query Language (PL/SQL) is an extension of SQL.

❖ PL/SQL is a block-structured language, meaning that PL/SQL programs are divided


and written in logical blocks of code. Each block consists of three sub- parts:

❖ DECLARE- This section starts with the keyword DECLARE. It is an optional section
and defines all variables, cursors, subprograms, and other elements to be used in the
program.

❖ EXECUTABLE COMMANDS- This section is enclosed between the keywords


BEGIN and END and it is a mandatory section. It consists of the executable PL/SQL
statements of the program. It should have at least one executable line of code, which
may be just a NULL command to indicate that nothing should be executed.

❖ EXCEPTION HANDLING- This section starts with the keyword EXCEPTION.


This section is again optional and contains exception(s) that handle errors in the
program.

BASIC SYNTAX OF PL / SQL


DECLARE
/* Variables can be declared here */ BEGIN
/* Executable statements can be written here */ EXCEPTION
/* Error handlers can be written here. */ END;

STEPS TO WRITE & EXECUTE PL / SQL


❖ As we want output of PL/SQL Program on screen, before Starting writing anything type
(Only Once per session)
❖ SQL> SET SERVEROUTPUT ON
❖ To write program, use Notepad through Oracle using ED command.
❖ SQL> ED ProName
❖ Type the program Save & Exit.
❖ To Run the program
❖ SQL> @ProName

30
Decision Making With If Statement :-
The general syntax for the using IF—ELSE statement is
IF(TEST_CONDITION) THEN
SET OF STATEMENTS ELSE
SET OF STATEMENTS END IF;

For Nested IF—ELSE Statement we can use IF--ELSIF—ELSE as follows


IF(TEST_CONDITION) THEN SET OF STATEMENTS ELSIF (CONDITION)
SET OF STATEMENTS END IF;

LOOPING STATEMENTS:-
For executing the set of statements repeatedly we can use loops. The oracle supports
number of looping statements like GOTO, FOR, WHILE & LOOP.
Here is the syntax of these all the types of looping statements.

GOTO STATEMENTS
<<LABEL>>
SET OF STATEMENTS
GOTO LABEL;

FOR LOOP:
FOR <VAR> IN [REVERSE] <INI_VALUE>..<END_VALUE>
SET OF STATEMENTS
END LOOP;

WHILE LOOP:
WHILE (CONDITION) LOOP SET OF STATEMENTS
END LOOP;

LOOP STATEMENT:
LOOP
SET OF STATEMENTS IF (CONDITION) THEN EXIT
SET OF STATEMENTS END LOOP;

While using LOOP statement, we have to take care of EXIT conditions; otherwise it
may go into infinite loop.

PROCEDURES
SYNTAX:

CREATE[OR REPLACE]PROCEDURE procedure_name [(Parameter [,parameter])]


IS [declaration_section]
BEGIN executable_section
EXCEPTION [exception _section]
END [procedure_name];

31
PROBLEMS:

(i) Write a procedure for executing a loop.


SQL>Create or replace procedure pro1(n number) is begin
for i in 1…n loop
dbms_output.put_line(i); end loop;
end;

OUTPUT:
SQL>set serverout on;
SQL>/
Procedure created. SQL>exe pro1(4) 1
2
3
4
PL/SQL procedure successfully completed.

(ii) Create a table employee which has the following columns eno,ename,sal and write a
procedure to display the employee details of given employee number.

PROCEDURE:
create or replace procedure p3(num number) is
erec emp%rowtype;
begin
select eno, ename into erec.eno, erec.ename from emp where eno=num;
dbms_output.put_line('Employee number: ' || erec.eno);
dbms_output.put_line('Employee name: ' || erec.ename);
exception
when no_data_found then
dbms_output.put_line('No record found');
end;

MAIN PROGRAM:
declare
num emp.eno%type;
salary emp.sal%type;
begin
num := &num;
salary := fun1(num);

if salary = -1 then
dbms_output.put_line('No records available with employee number: ' || num);
else
dbms_output.put_line('Salary of employee number ' || num || ' is: ' || salary);
end if;
end;

32
OUTPUT:
SQL>set serverout on;
SQL>/
SQL>execp2(4); Factorial of 4 is :24
PL/SQL procedure successfully completed.

(iii) Create a procedure for a swapping program.


Create or replace procedure swap(a in out number, b in out number) is
c number;
begin
c := a;
a := b;
b := c;
end;
MAIN PROGRAM:
declare
a number;
b number;
begin
a := &a;
b := &b;
dbms_output.put_line('Before swapping a=' || a || ' b=' || b);
swap(a, b);
dbms_output.put_line('After swapping a=' || a || ' b=' || b);
end;
OUTPUT:
Enter value for a: 3 Old 5: a:=&a;
New 5: a:=3;
Enter value for b: 5 Old 6: b:=&b;
New 6: b:=5;
Before swapping a = 3 b = 5 After swapping a = 5 b = 3
PL/SQL procedure successfully completed.
(iv) Write a procedure to input a value from the user and display it.
SQL> set serveroutput on;
SQL> declare
a varchar2(20) ;
begin
a:=&a;
dbms_output.put_line(a);
end;
/
OUTPUT:
Enter value for a: 5 old 4: a:=&a;
new 4: a:=5;
5
PL/SQL procedure successfully completed.

33
(v) Write a procedure to find the greatest of three numbers.
SQL> set serveroutput on;
SQL> declare
a number(7);
b number(7);
c number(7);
begin
a:=&a;
b:=&b;
c:=&c;
if(a>b and a>c) then
dbms_output.put_line (' The greatest of the three is ' || a);
else if (b>c) then
dbms_output.put_line (' The greatest of the three is ' || b);
else
dbms_output.put_line (' The greatest of the three is ' || c);
end if;
end if;
end;
/
OUTPUT:
Enter value for a: 5 old 6: a:=&a;
new 6: a:=5;
Enter value for b: 7 old 7: b:=&b;
new 7: b:=7;
Enter value for c: 1 old 8: c:=&c;
new 8: c:=1;
The greatest of the three is 7
PL/SQL procedure successfully completed.
(vi) Write a procedure to print numbers from 1 to 5 using simple loop
SQL> set serveroutput on;
SQL> declare
a number:=1;
begin
loop
dbms_output.put_line (a);
a:=a+1;
exit when a>5;
end loop;
end;
/
OUTPUT:
1
2
3
4
5
PL/SQL procedure successfully completed.

34
(vii) Write a procedure to print numbers from 1 to 4 using while loop
SQL> set serveroutput on;
SQL> declare
a number:=1;
begin
while(a<5)
loop
dbms_output.put_line (a);
a:=a+1;
end loop;
end;
10 /

OUTPUT:
1
2
3
4
PL/SQL procedure successfully completed.

(viii) Write a procedure to print numbers from 1 to 5 using for loop

SQL> set serveroutput on;


SQL> declare
a number:=1;
begin
for a in 1..5
loop
dbms_output.put_line (a);
end loop;
end;
/

OUTPUT:
1
2
3
4
5
PL/SQL procedure successfully completed.

35
​FUNCTIONS:

SYNTAX:

CREATE[OR REPLACE] FUNCTION function_name [(parameter[,parameter])]


RETURN return_datatype
IS | AS [declaration_section]
BEGIN
executable_section
EXCEPTION [ Exception_section]
END [function_name];

(i) Create a function to display the salary employee number.

SQl> create or replace function fun1(num emp.eno%type) return emp.sal%type is


esal emp.sal%type;
begin
select sal into esal from emp where eno = num;
return esal;
exception
when no_data_found then
return -1;
end;

MAIN PROGRAM:
declare
num emp.eno%type; salary emp.sal%type;
begin
num :=&num; salary:=fun 1(num); if(salary =-1)then
dbms_output.putline(‘No records available with employee number: ‘|| num); else
dbms_output.putline(‘Salary of employee number ‘||num ||’is:’||salary); end if;
end;

OUTPUT:
SQL>/
Function created SQL>/

Enter the value for num: 124 Old 5: num:=&num;


new 5: num:124;
Salary of employee number 124 is : 22312

PL/SQL procedure successfully completed.

36
(ii) Create a function to calculate the factorial of given number.
create or replace function fact(n in number)
return number
is
s number;
begin
s := 1;
if n = 0 then
return 1;
end if;
for i in 1..n loop
s := s * i;
end loop;
return s;
end;
/

Function created.
SQL>select fact(10) from dual;

OUTPUT:
FACT(10)
-------------
3628800

(iii) Create a function to calculate the sum of Odd numbers.


SQL> set serveroutput on
SQL> declare
2 n number;
3 sum1 number default 0;
4 endvalue number;
5 begin
6 endvalue := &endvalue;
7 n := 1;
8 while(n < endvalue)
9 loop
10 sum1 := sum1 + n;
11 n := n + 2;
12 end loop;
13 dbms_output.put_line('sum of odd numbers between 1 and ' || endvalue || ' is ' || sum1);
14 end;
15 /

OUTPUT:
Enter value for endvalue: 20 Old 6: endvalue :=&endvalue; New 6:endvalue:=20;
Sum of odd numbers between 1 and 20 is 100 PL/SQL procedure successfully
completed.

37
(iv) Create a function to display the table details.
SQL> create table pupil (name varchar2(10), age number(3));
Table created.

SQL> select * from pupil


2 NAME AGE
3 SOUND 18
4 Shwetha 19

SQL> create or replace function pup


2 (
3 p_age in number
4 )
5 Return varchar
6 is
7 i pupil.age%type;
8 begin
9 select age into i
10 from pupil
11 where age = p_age;
12 return 'exist';
13 Exception
14 when no_data_found
15 then
16 return 'not exist';
17 End;
18 /

SQL> select pup(18) from dual


2 PUP(18)

exist

SQL> select pup(20) from dual


2 PUP(18)

Not exist

RESULT:
Thus PL / SQL block executed successfully to satisfy specified conditions.

38
EX NO : 09 FRAME AND EXECUTE THE APPROPRIATE PL/SQL CURSORS

DATE :

AIM:
To implement PL/SQL cursors to fetch and process data, framing explicit and implicit
cursors for database operations in a structured manner.

PROCEDURE:

(i) Framing and Executing Explicit Cursor:

Create a PL/SQL block with an explicit cursor to fetch data from a specific table:

PL/SQL block with explicit cursor


DECLARE
CURSOR emp_cursor IS
SELECT EmployeeID, FirstName, LastName
FROM Employees;
emp_rec emp_cursor%ROWTYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_rec;
EXIT WHEN emp_cursor%NOTFOUND;
-- Process fetched data (e.g., display or manipulate)
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_rec.EmployeeID || ', Name:
' || emp_rec.FirstName || ' ' || emp_rec.LastName);
END LOOP;
CLOSE emp_cursor;
END;

39
(ii) Framing and Executing Implicit Cursor:

Create a PL/SQL block with an implicit cursor for data manipulation:

PL/SQL block with implicit cursor


DECLARE
emp_rec Employees%ROWTYPE;
BEGIN
FOR emp_rec IN (SELECT EmployeeID, FirstName, LastName FROM
Employees) LOOP
Process each row of data fetched by implicit cursor
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_rec.EmployeeID || ', Name:
' || emp_rec.FirstName || ' ' || emp_rec.LastName);
END LOOP;
END;

RESULT:
Thus PL / SQL block executed successfully to satisfy specified conditions.

40
EX NO : 10 CREATION OF DATABASE TRIGGERS

DATE :

AIM:
To Develop insert, delete, and update triggers to automate actions, maintain data
integrity, and enhance functionality within the database system.

(i) Create a row level trigger for the customers table that would fire for INSERT or
UPDATE or DELETE operations performed on the CUSTOMERS table.

This trigger will display the salary difference between the old values and new values:

CUSTOMERS TABLE:

ID NAME AGE ADDRESS SALARY


1 Alive 24 Khammam 2000
2 Bob 27 Kadappa 3000
3 Catri 25 Guntur 4000
4 Dena 28 Hyderabad 5000
5 Eeshwar 27 Kurnool 6000
6 Farooq 28 Nellur 7000

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff NUMBER;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
DBMS_OUTPUT.PUT_LINE('Old salary: ' || :OLD.salary);
DBMS_OUTPUT.PUT_LINE('New salary: ' || :NEW.salary);
DBMS_OUTPUT.PUT_LINE('Salary difference: ' || sal_diff);
END;
/
Trigger created.

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (7,
'Kriti', 22, 'HP', 7500.00 );

Old salary:
New salary: 7500
Salary difference:

41
(ii) Convert employee name into uppercase whenever an employee record is inserted
or updated. Trigger to fire before the insert or update.

SQL> CREATE TABLE Employee(


ID VARCHAR2(4 BYTE) NOTNULL,
First_Name VARCHAR2(10 BYTE),
Last_Name VARCHAR2(10 BYTE),
Start_Date DATE,
End_Date DATE,
Salary NUMBER(8,2),
City VARCHAR2(10 BYTE),
Description VARCHAR2(15 BYTE) 10)
11 /

Table created.

SQL> CREATE OR REPLACE TRIGGER employee_insert_update


2 BEFORE INSERT OR UPDATE ON employee FOR EACH ROW
3 DECLARE
4 dup_flag INTEGER;
5 BEGIN
6 --Force all employee names to uppercase.
7 :NEW.first_name := UPPER(:NEW.first_name);
8 END;
9 /

Trigger created.

SQL> INSERT INTO Employee(ID, First_Name, Last_Name, Start_Date,


End_Date, Salary, City, Description)
2 VALUES('01','Jason', 'Martin', TO_DATE('19960725','YYYYMMDD'),
TO_DATE('20060725','YYYYMMDD'), 1234.56, 'Toronto', 'Programmer')
3 /

1 row created.

SQL> INSERT INTO Employee(ID, First_Name, Last_Name, Start_Date,


End_Date, Salary, City, Description)
2 VALUES('02','Alison', 'Mathews', TO_DATE('19760321','YYYYMMDD'),
TO_DATE('19860221','YYYYMMDD'), 6661.78, 'Vancouver','Tester')
3 /
1 row created.

SQL> INSERT INTO Employee(ID, First_Name, Last_Name, Start_Date,


End_Date, Salary, City, Description)
2 VALUES('03','James', 'Smith', TO_DATE('19781212','YYYYMMDD'),
TO_DATE('19900315','YYYYMMDD'), 6544.78, 'Vancouver','Tester')
3 /
1 row created.

42
SQL> INSERT INTO Employee(ID, First_Name, Last_Name, Start_Date,
End_Date, Salary, City, Description)
2 VALUES('04','Celia', 'Rice', TO_DATE('19821024','YYYYMMDD'),
TO_DATE('19990421','YYYYMMDD'), 2344.78,'Vancouver','Manager')
3 /

1 row created.

SQL> INSERT INTO Employee(ID, First_Name, Last_Name, Start_Date,


End_Date, Salary, City, Description)
2 VALUES('05','Robert', 'Black', TO_DATE('19840115','YYYYMMDD'),
TO_DATE('19980808','YYYYMMDD'), 2334.78, 'Vancouver','Tester')
3 /

1 row created.

SQL> INSERT INTO Employee(ID, First_Name, Last_Name, Start_Date,


End_Date, Salary, City, Description)
2 VALUES('06','Linda', 'Green', TO_DATE('19870730','YYYYMMDD'),
TO_DATE('19960104','YYYYMMDD'), 4322.78,'New York','Tester')
3 /

1 row created.

SQL> INSERT INTO Employee(ID, First_Name, Last_Name, Start_Date,


End_Date, Salary, City, Description)
2 VALUES('07','David', 'Larry', TO_DATE('19901231','YYYYMMDD'),
TO_DATE('19980212','YYYYMMDD'), 7897.78,'New York','Manager')
3 /

1 row created.

SQL> INSERT INTO Employee(ID, First_Name, Last_Name, Start_Date,


End_Date, Salary, City, Description)
2 VALUES('08','James', 'Cat', TO_DATE('19960917','YYYYMMDD'),
TO_DATE('20020415','YYYYMMDD'), 1232.78,'Vancouver','Tester')
3 /

1 row created.

SQL> SELECT *
2 FROM Employee
3 /

43
ID FIRST_NAME LAST_NAMESTART_DATEND_DATE SALARY CITY DESCRIPTION

01 JASON Martin 25-JUL-96 25-JUL-06 Toronto


1234.56 Programmer
02 ALISON Mathews 21-MAR-76 21-FEB-86 Vancouver
6661.78 Tester
03 JAMES Smith 12-DEC-78 15-MAR-906 Vancouver
544.78 Tester
04 CELIA Rice 24-OCT-82 21-APR-99 Vancouver
2344.78 Manager
05 ROBERT Black 15-JAN-84 08-AUG-98 Vancouver
2334.78 Tester
06 LINDA Green 30-JUL-87 04-JAN-96 New
4322.78 YorkTester
07 DAVID Larry 31-DEC-90 12-FEB-98 New York
7897.78 Manager
08 JAMES Cat 17-SEP-96 15-APR-02 Vancouver
1232.78 Tester

8 rows selected.
SQL> drop table Employee 2 / Table dropped.

(iii) Trigger before deleting a record from emp table. Trigger will insert the row to
be deleted into another table and also record the user who has deleted therecord.

SQL> CREATE OR REPLACE TRIGGERemployee_before_delete


2 BEFOREDELETE
3 ON employee
4 FOR EACHROW
5 DECLARE
6 v_usernamevarchar2(10);
7 BEGIN
8 -- Find username of person performing the DELETE on thetable
9 SELECT user INTOv_username
10 FROMdual;
11 -- Insert record into audit table
12 INSERT INTO employee_audit (id, salary, delete_date,deleted_by)
13 VALUES (:old.id,:old.salary, sysdate, v_username);
14 END;
15 /
Trigger created.

44
SQL> delete from employee; 8 rows deleted. SQL> select * from employee_audit;

ID SALARY DELETE _DADELETED_BY


---- ---------- --------- ----------------
01 1234.56 09-SEP-06 JAVA2S
02 6661.78 09-SEP-06 JAVA2S
03 6544.78 09-SEP-06 JAVA2S
04 2344.78 09-SEP-06 JAVA2S
05 2334.78 09-SEP-06 JAVA2S
06 4322.78 09-SEP-06 JAVA2S
07 7897.78 09-SEP-06 JAVA2S
08 1232.78 09-SEP-06 JAVA2S

8 rows selected.

SQL>drop tableemployee_audit;

Table dropped.

RESULT:
Thus Database triggers successfully created to automate actions, enforce data integrity,
and enhance functionality within the database system.

45
EX NO : 11 FRAME AND CREATE THE APPROPRIATE EXCEPTION
HANDLING FOR THE PROJECT

DATE :

AIM:
To write PL/SQL procedures using Exception handling for manipulating the
tables/database

EXCEPTION:
An exception is an error which disrupts the normal flow of program instructions.
PL/SQL provides us the exception block which raises the exception thus helping the
programmer to find out the fault and resolve it.

There are two types of exceptions defined in PL/SQL


❖ User defined exception.
❖ System defined exceptions.

Syntax:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
Exception1-handling-statements
WHEN exception2 THEN
Exception2-handling-statements
WHEN exception3 THEN
Exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;

46
OUTPUT:

(i) PL/SQL procedure to handle in build exceptions while manipulating the table :

47
(ii) PL/SQL for user defined exception while manipulating the table :

RESULT:

Thus framing and creating an appropriate Exception Handling for the project is
executed successfully.

48
EX NO : 12 CREATION OF FUNCTIONS FOR THE PROJECT

DATE :

AIM:
To Create functions for the project in the database.

PROCEDURE
Function is created using the CREATE FUNCTION statement. The simplified syntax
for the CREATE OR REPLACE PROCEDURE statement
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

TABLE : STUDENTS

Display the records of the table student


Select * from students12;

Create a PL/SQL function to find the total of all marks of the students

49
Calling the PL/SQL function to calculate the total of one student

Display the records of students table after calling the PL/SQL function

RESULT:
Thus the creation and execution of functions for the project were completed
successfully.

50
EX NO : 13 CREATION OF DATABASE TRIGGERS

DATE :

AIM:
The aim of this experiment is to understand the concept of PL/SQL procedures,
including their structure, parameters, and execution, and to frame and execute PL/SQL
procedures with appropriate SQL comments.

PROCEDURE:

(i) Framing and Executing a Simple PL/SQL Procedure:


Create a PL/SQL procedure with input parameters to perform a specific task:

PL/SQL procedure with input parameter


CREATE OR REPLACE PROCEDURE CalculateAreaRect(length IN NUMBER, width IN
NUMBER) AS
area NUMBER;
BEGIN
area := length * width;
DBMS_OUTPUT.PUT_LINE('Area of Rectangle: ' || area);
END CalculateAreaRect;
/
Execute the procedure with sample input values
BEGIN
CalculateAreaRect(5, 10);
END;

(ii) Framing and Executing a Simple PL/SQL Procedure:

Create a PL/SQL procedure with an output parameter to return calculated values:

PL/SQL procedure with output parameter


CREATE OR REPLACE PROCEDURE DivideNumbers(dividend IN NUMBER, divisor IN
NUMBER, quotient OUT NUMBER) AS
BEGIN
IF divisor <> 0 THEN
quotient := dividend / divisor;
DBMS_OUTPUT.PUT_LINE('Quotient: ' || quotient);

51
ELSE
DBMS_OUTPUT.PUT_LINE('Error: Division by zero.');
END IF;
END DivideNumbers;
/
Declare variable to capture output parameter
DECLARE
result NUMBER;
BEGIN

Execute the procedure with sample input values and capture output
DivideNumbers(10, 5, result);
DBMS_OUTPUT.PUT_LINE('Result: ' || result);
END;

RESULT:
The above PL/SQL procedures were executed successfully, and their output/results
were displayed using DBMS_OUTPUT.PUT_LINE statements.

52
EX NO : 14 DESIGN OF AIRLINE RESERVATION MANAGEMENT SYSTEM

DATE :

AIM:
The aim of this experiment is to design and construct an Entity-Relationship (ER)
model and ER diagram tables for the Airline Reservation Management System .

REQUIREMENTS:
❖ Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or faster
processor with at least 1GB RAM and 500 MB free disk space.
❖ MySQL 5.6.1

PROCEDURE:
(i) Identifying Entities and Attributes:
➢ Analyze the application domain and identify relevant entities and their
attributes.
➢ Create a list of entities and their respective attributes based on the
requirements.

(ii) Defining Relationships:


➢ Identify relationships between entities (e.g., one-to-one, one-to-many,
many-to-many).
➢ Determine the cardinality and participation constraints for each relationship.

(iii) Constructing the ER Diagram:


➢ Use an ER diagramming tool to create an Entity-Relationship (ER) diagram.
➢ Represent entities as rectangles, attributes as ovals connected to entities, and
relationships as diamonds connecting related entities.
➢ Label each relationship with cardinality and participation constraints (e.g., 1:1,
1:N, M:N).

(iv) Refining and Validating the ER Model:


➢ Review the ER diagram for completeness and correctness.
➢ Ensure that all entities, attributes, and relationships are properly represented.
➢ Validate the model to ensure data integrity and consistency.

(v) Documenting the ER Model:


➢ Provide a detailed description of each entity, including its attributes and
relationships.
➢ Document cardinality and participation constraints for each relationship.
➢ Include any additional notes or considerations related to the ER model.

53
ENTITIES:

❖ Passengers
➢ Attributes:
● PassengersID (Primary Key),
● Name,
● Address,
● Email,
● Phone,
● DateOfBirth
❖ Flight Attendant
➢ Attributes:
● Flight Attendant ID (Primary Key),
● Name,
● Email,
● Phone,
● Education
❖ Flight
➢ Attributes:
● FlightID (Primary Key),
● FlightName,
● Routes

RELATIONSHIPS:

❖ Enrollment
➢ Links Passengers and Flight Entities
➢ Attributes: EnrollmentID (Primary Key), PassengersID (Foreign Key),
FlightID (Foreign Key), Duration, Year, Grade, etc.
❖ Teaching
➢ Links Flight Attendant and Flight Entities
➢ Attributes: TeachingID (Primary Key), Flight Attendant ID (Foreign Key),
FlightID (Foreign Key), Duration, Year, etc.

❖ Belongs_to LinksFlight Attendant and Department entities


➢ Attributes: BelongsID (Primary Key), Flight Attendant ID (Foreign Key),
DepartmentID (Foreign Key), Position (e.g., Professor, Assistant Professor),
etc.

PRIMARY KEY ATTRIBUTES:

1. PassengersID (Passengers Entity)


2. FlightattendantID (Flight Attendant Entity)
3. FlightID (FlightEntity)

54
E-R Model
Attributes of the following Entities
(i) PASSENGERS
❖ PassengersID (Primary Key)
❖ Name
❖ Address
❖ Email
❖ Phone
❖ Date Of Birth
❖ Gender
SCHEMA
Passengers: PassengersID (Primary Key), Name, Address, Email, Phone, DateOfBirth

TABLE NAME: PASSENGERS

Field Description Type Length

pas_ID (PK) Passengers ID Int 11

pas_name Passengers Name Varchar 255

pas_contact Passengers Mobile Int 11


Number

pas_email Passengers Email 255 255

Date_of_Birth Passengers Date of Birth Int 08

pas_Gender Passengers Gender Varchar 255

pas_Address Passengers Address Varchar 255

55
(ii) FLIGHT ATTENDANT
❖ Flight Attendant ID (Primary Key),
❖ Name,
❖ Email,
❖ Phone,
❖ Address
SCHEMA
Flight Attendant : Flight Attendant ID (Primary Key), Name, Email, Phone

TABLE NAME: FLIGHT ATTENDANT

Field Description Type Length

Flight Attendant _ID Flight Attendant ID Int 11


(PK)

Flight Attendant _name Flight Attendant Name Varchar 255

Flight Attendant Flight Attendant Mobile Number Int 11


_contact

Flight Attendant _email Flight Attendant Email 255 255

Date_of_Birth Flight Attendant Date of Birth Int 08

Flight Attendant Flight Attendant Gender Varchar 255


_Gender

Flight Attendant Flight Attendant Address Varchar 255


_Address

56
(iii) FLIGHT
❖ FlightID (Primary Key),
❖ FlightName,
❖ Route
❖ Duration
❖ FlightType

SCHEMA
Flight: FlightID (Primary Key), FlightName, Route, Duration, FlightType

TABLE NAME: FLIGHT

Field Description Type Length

Flight_ID (PK) FlightID Int 11

Flight_name FlightName Varchar 30

Flight_desc FlightDescription Varchar 30

Flight_type Flight Type varchar 30

Flight_std_ID Passengers ID int 11

Duration Duration varchar 30

57
(iv) LOCATION
❖ Loc_ID (Primary Key)
❖ Loc_desc
❖ Loc_type

SCHEMA
Location: Loc_ID (Primary Key), Loc_desc, Loc_type

TABLE NAME: LOCATION

Field Description Type Length

Loc_ID Location ID int 11

Loc_desc Location description varchar 255

Loc_type Type of the Location varchar 30

58
(v) RESERVATION
❖ Reg_ID (Primary Key)
❖ Reg_desc
❖ Reg_type
❖ Reg_date

SCHEMA
Reservation: Reg_ID (Primary Key), Reg_desc, Reg_type, Reg_date

TABLE NAME: RESERVATION

Field Description Type Length

Reg_pas_ID Passengers Reservation ID int 11

Reg_ID Reservation ID int 11

Reg_desc Description about Reservation varchar 255

Reg_type Type of Reservation varchar 30

Reg_date Date of Reservation varchar 30

59
(vi) PERMISSION
❖ Per_id (Primary Key)
❖ Per_role_id
❖ Per_module
❖ Per_name

SCHEMA
Permission: Per_id (Primary Key), Per_role_id, Per_module, Per_name

TABLE NAME: PERMISSION

Field Description Type Length

Per_id Permission id varchar 255

Per_role_id Permission role id varchar 255

Per_module Permission module Varchar 255

Per_name Permission name Varchar 255

60
(vii) ROLES
❖ Role-id (Primary Key)
❖ Role_name
❖ Role_desc

SCHEMA
Roles: Role-id (Primary Key), Role_name, Role_desc

TABLE NAME: ROLES

Field Description Type Length

Role-id Role id varchar 255

Role_name Role name varchar 255

Role_desc Role decription varchar 255

61
(viii) LOG-IN
❖ Login-ID (Primary Key)
❖ Login-role-ID
❖ Login_username
❖ Login_password

SCHEMA
Login: Login-ID (Primary Key), Login-role-ID, Login_username, Login_password

TABLE NAME: LOG-IN

Field Description Type Length

Login-ID Login ID Varchar 255

Login-role-ID Login-role ID Varchar 255

Login_username User name Varchar 255

Login_password Password Varchar 255

62
ER DIAGRAM FOR AIRLINE RESERVATION MANAGEMENT SYSTEM

63
Passengers Table:
❖ Contains details like ID, name, contact information, and password for
passengers. It's crucial for passenger record management, enrollment, and
authentication.
Flight Table:
❖ Stores essential information about Flightes, including ID, name, description,
type, and passenger enrollment details. It aids in Flight management and
tracking passenger enrollments.
Location Table:
❖ Holds data about locations within the university, such as IDs, descriptions, and
types. It’s useful for organizing academic units and allocating resources.
Reservation Table:
❖ Tracks passenger reservations with ID, description, type, and reservation date.
It's pivotal for monitoring enrollment trends and managing Flight capacities.
Permission Table:
❖ Manages access permissions with unique IDs, role associations, module
details, and permission names. It ensures secure data access and user
management.
Roles Table:
❖ Defines roles with IDs, names, and descriptions. It's essential for role-based
access control and user administration.
Log-In Table:
❖ Logs login activities with unique IDs, role associations, usernames, and
passwords. It’s critical for security monitoring and audit trails.

RESULT:
Hence, the Entity-Relationship (ER) model and ER diagram tables were successfully
designed for the Airline Reservation Management System .

64
EX NO : 15 DEPLOYMENT OF AIRLINE RESERVATION MANAGEMENT SYSTEM

DATE :

AIM:
To integrate a airlines database management system aimed at streamlining Flight
Reservation, including managing passenger records, Flight information, and
reservation tasks effectively.

(i) ADMIN PAGE


TABLE CREATION:
CREATE TABLE `admin` (
`admin_id` int(11) NOT NULL,
`admin_uname` varchar(20) NOT NULL,
`admin_email` varchar(50) NOT NULL,
`admin_pwd` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;
❖ The query creates a table named admin with four columns: admin_id, admin_uname,
admin_email, and admin_pwd.
❖ The table uses the InnoDB storage engine and has a default character set of latin1 with
a case-insensitive collation of latin1_swedish_ci.
DATA INSERTION:
INSERT INTO `admin` (`admin_id`, `admin_uname`, `admin_email`, `admin_pwd`)
VALUES(1,'admin','admin@mail.com',$2y$10$KRXGkY.dxYjD8FLZclW/Tu04wl76l
D7IA4Z3nAsxtpdZxHNbYo4ZW');
❖ The query inserts a new record into the admin table with values for the
admin_id, admin_uname, admin_email, and admin_pwd columns.
❖ Thepassword$10$KRXGkY.dxYjD8FLZclW/Tu04wl76lD7IA4Z3nAsxtpdZx
HNbYo4ZW is hashed and stored in the admin_pwd column for the admin
with admin_id 1.
SQL TABLE :

65
USER INTERFACE:

(ii) PASSENGER PROFILE

TABLE CREATION:

CREATE TABLE `passenger_profile` (


`passenger_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`flight_id` int(11) NOT NULL,
`mobile` varchar(110) NOT NULL,
`dob` datetime NOT NULL,
`f_name` varchar(20) DEFAULT NULL,
`m_name` varchar(20) DEFAULT NULL,
`l_name` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;
❖ The query creates a table named passenger_profile with eight columns: passenger_id,
user_id, flight_id, mobile, dob, f_name, m_name, and l_name.
❖ The table uses the InnoDB storage engine and has a default character set of latin1 with
a case-insensitive collation of latin1_swedish_ci.

DATA INSERTION:
INSERT INTO `passenger_profile` (`passenger_id`, `user_id`, `flight_id`, `mobile`,
`dob`, `f_name`, `m_name`, `l_name`) VALUES
(1, 1, 23, '9845514598', '1995-01-01 00:00:00', 'Sottai ', '', 'Saalaa'),
(2, 2, 22, '9791528988', '1995-02-13 00:00:00', 'Sottai', '', 'Rishi'),
(3, 3, 24, '9845214987', '1994-06-21 00:00:00', 'Koratur ', '', 'Kulla'),
(4, 4, 25, '965485469', '1995-05-16 00:00:00', 'Santhosh', '', 'Maami'),
(5, 2, 26, '7854444411', '1995-02-13 00:00:00', 'Sottai', '', 'Rishi');

66
❖ The query inserts multiple records into the passenger_profile table with values for the
passenger_id, user_id, flight_id, mobile, dob, f_name, m_name, and l_name columns.
❖ Each record represents a passenger's profile with details like name, mobile number,
date of birth, and associated user and flight IDs.

SQL TABLE :

USER INTERFACE:

67
(iii) LIST OF FLIGHT

TABLE CREATION:

CREATE TABLE `flight` (


`flight_id` int(11) NOT NULL,
`admin_id` int(11) NOT NULL,
`arrivale` datetime NOT NULL,
`departure` datetime NOT NULL,
`Destination` varchar(20) NOT NULL,
`source` varchar(20) NOT NULL,
`airline` varchar(20) NOT NULL,
`Seats` varchar(110) NOT NULL,
`duration` varchar(20) NOT NULL,
`Price` int(11) NOT NULL,
`status` varchar(6) DEFAULT NULL,
`issue` varchar(50) DEFAULT NULL,
`last_seat` varchar(5) DEFAULT '',
`bus_seats` int(11) DEFAULT 20,
`last_bus_seat` varchar(5) DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;

❖ The query creates a table named flight with fourteen columns: flight_id, admin_id,
arrivale, departure, Destination, source, airline, Seats, duration, Price, status, issue,
last_seat, bus_seats, and last_bus_seat.
❖ The table uses the InnoDB storage engine and has a default character set of latin1 with
a case-insensitive collation of latin1_swedish_ci.

DATA INSERTION:
INSERT INTO `flight` (`flight_id`, `admin_id`, `arrivale`, `departure`, `Destination`,
`source`, `airline`, `Seats`, `duration`, `Price`, `status`, `issue`, `last_seat`, `bus_seats`,
`last_bus_seat`) VALUES
(22, 1, '2024-04-22 13:30:00', '2024-04-22 10:00:00', 'Trerdence', 'Yleigh', 'Sottai
Airlines', '72', '3 hrs', 8000, 'dep', '', '', 20, ''),
(23, 1, '2024-04-23 08:00:00', '2024-04-22 09:00:00', 'Otiginia', 'San', 'Saalaa Airlines',
'81', '10hrs', 15000, '', '', '', 20, ''),
(24, 1, '2024-04-22 11:00:00', '2024-04-22 08:00:00', 'Vrexledo', 'Plueyby', 'Qatar
Airways', '286', '3hrs', 6500, 'dep', '', '', 20, ''),
(25, 1, '2024-04-22 09:30:00', '2024-04-22 07:00:00', 'Flerough', 'Yleigh', 'Air India',
'231', '2hrs 30min', 8200, '', '', '', 20, ''),
(26, 1, '2024-04-22 10:00:00', '2024-04-22 07:30:00', 'Chiby', 'Odonhull', 'Indigo',
'245', '2hrs 30min', 7500, '', '', '', 20, '');

❖ The query inserts multiple records into the flight table with values for the flight_id,
admin_id, arrivale, departure, Destination, source, airline, Seats, duration, Price,
status, issue, last_seat, bus_seats, and last_bus_seat columns.
❖ Each record represents a flight with details like departure and arrival times,
destination, source, airline, seat availability, price, and status.

68
SQL TABLE :

USER INTERFACE:

69
(iv) LIST OF AIRLINES
TABLE CREATION:

CREATE TABLE `airline` (


`airline_id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`seats` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;

❖ The query creates a table named airline with three columns: airline_id, name, and
seats.
❖ The table uses the InnoDB storage engine and has a default character set of latin1 with
a case-insensitive collation of latin1_swedish_ci.

DATA INSERTION:

INSERT INTO `airline` (`airline_id`, `name`, `seats`) VALUES


(15, 'Indigo', 245),
(16, 'Air India', 231),
(17, 'Sottai Airlines', 72),
(18, 'Saalaa Airlines', 81),
(19, 'Qatar Airways', 286);
❖ The query inserts multiple records into the airline table with values for the airline_id,
name, and seats columns.
❖ Each record represents an airline with details like the airline ID, name, and the number
of seats they offer.

SQL TABLE :

70
USER INTERFACE:

(v) SCHEDULE PAGE


TABLE CREATION:
CREATE TABLE `schedule_list` (
`flight_id` int(11) NOT NULL,
`admin_id` int(11) NOT NULL,
`arrivale` datetime NOT NULL,
`departure` datetime NOT NULL,
`Destination` varchar(20) NOT NULL,
`source` varchar(20) NOT NULL,
`airline` varchar(20) NOT NULL,
`duration` varchar(20) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;

❖ The query attempts to create a table named schedule_list with seven columns:
flight_id, admin_id, arrivale, departure, Destination, source, and airline.
❖ The table uses the InnoDB storage engine and has a default character set of latin1 with
a case-insensitive collation of latin1_swedish_ci. However, there's a syntax error due
to an extra comma after the duration column definition.

DATA INSERTION:
INSERT INTO `flight` (`flight_id`, `admin_id`, `arrivale`, `departure`, `Destination`,
`source`, `airline`, `Seats`, `duration`, `Price`, `status`, `issue`, `last_seat`, `bus_seats`,
`last_bus_seat`) VALUES
(26, 1, '2024-04-22 10:00:00', '2024-04-22 07:30:00', 'Chiby', 'Odonhull', 'Indigo',
'245', '2hrs 30min', 7500, '', '', '', 20, '');

❖ The query attempts to insert a record into the flight table with values for the flight_id,
admin_id, arrivale, departure, Destination, source, airline, Seats, duration, Price,
status, issue, last_seat, bus_seats, and last_bus_seat columns.
❖ The record represents a flight with specific details like departure and arrival times,
destination, source, airline, seat availability, price, and status.

71
SQL TABLE :

USER INTERFACE:

RESULT:
Hence, The Deployment of the Airline Reservation Management System involves
designing the database, creating the model, SQL Tables and implementing the model to
ensure effective data management.

72

You might also like