0% found this document useful (0 votes)
5 views53 pages

SQL project for Bca semester 6

Oracle Database is a leading Relational Database Management System (RDBMS) known for its reliability and scalability, catering to various business needs. Oracle Corporation, founded in 1977, offers multiple database editions, including Standard, Enterprise, and Cloud Editions, each designed for different organizational requirements. The document also outlines the history, advantages, disadvantages, and key features of Oracle Database and DBMS, along with SQL and PL/SQL programming details.

Uploaded by

Shubham Sah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views53 pages

SQL project for Bca semester 6

Oracle Database is a leading Relational Database Management System (RDBMS) known for its reliability and scalability, catering to various business needs. Oracle Corporation, founded in 1977, offers multiple database editions, including Standard, Enterprise, and Cloud Editions, each designed for different organizational requirements. The document also outlines the history, advantages, disadvantages, and key features of Oracle Database and DBMS, along with SQL and PL/SQL programming details.

Uploaded by

Shubham Sah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 53

INTRODUCTION TO ORACLE

Oracle Database is a popular and fully-featured Relational Database Management System (RDBMS)
developed by Oracle Corporation. It is known for its reliability, scalability, and extensive features. This
makes it a top choice for businesses needing to manage and retrieve large amounts of data
efficiently.

What is Oracle?

Oracle Corporation is a global technology company founded in 1977 by Larry Ellison, Bob Miner,
and Ed Oates. They specialize in software, hardware, and cloud services that help businesses manage
data, run applications, and improve operations.

Over time, Oracle has grown to be one of the largest technology companies in the world. They offer
products like Oracle Cloud, Oracle Fusion Middleware, and Oracle Applications. Still, their most
important product is Oracle Database.

What is the Oracle database?

Oracle Database is an advanced RDBMS by Oracle Corporation that manages large volumes of
structured data efficiently. The database also supports on-premise and cloud deployment. Oracle
Database is used for transactions, data warehousing, and enterprise resource applications.

Architecture Of Oracle Database

ORACLE PROJECT 1
Editions of Oracle database
Oracle Database offers different editions to suit various needs. There are free basic versions for small
projects and more advanced editions for large enterprises. It provides features and
solutions tailored to different needs and budgets.

1. Oracle Standard Edition (SE): It is Suitable for small to medium businesses because of its
core database functionality and more affordablity. It offers reliability without enterprise-level
complexities.

2. Oracle Enterprise Edition (EE): This edition is for large organizations that need advanced
features like RAC (Real Application Clusters), data partitioning, and high security. It's ideal for
important, mission-critical applications.

3. Oracle Express Edition (XE): It is free but very limited by CPU and storage. Mainly for
students, developers and small projects.

4. Oracle Cloud Edition: This database targets cloud environments with maximum scalability
and flexibility in Oracle infrastructures.

5. Oracle Lite: It is a very lightweight, targeted at mobile and embedded applications. It is


designed for working at top gear both on resource-constrained mobile devices and at remote
location implementations.

History of Oracle
Oracle Corporation was founded in August 1977 by Larry Ellison, Bob Miner, Ed Oates, and Bruce
Scott. Initially known as Systems Development Labs (SDL), where they developed a specialized
database for the CIA, known as Project Oracle. In 1978, the company rebranded as Relational
Software Inc. and later as Oracle Systems Corporation in 1982.

In 1979, Oracle released Oracle V2, the first commercially available SQL-based RDBMS. By
1983, Oracle Version 3 was developed in C, making it the first relational database to run on various
hardware, including mainframes, minicomputers, and PCs, supporting SQL queries and transactions.

The other later editions are:

• It was in 1984 that Oracle 4 was released to support Transactions (Commit/Rollback),


export/import utilities and the report writer.

• Oracle 5 was released in the year 1985. This supported Client-Server Architecture. It could
connect the client's software to a database server over the network.

• Oracle 6 which was released in 1989 supports PL/SQL language. The new feature includes
OLTP high-speed systems, facility of hot backup, and row-level locking.

• Oracle 7 was released in 1992 to the market. Four years of hard work and two years
of customer testing. Some exhilarating features and abilities were added in the areas of
security, administration, development, and performance.

• Oracle 8 was released in the year 1997. It supports ORDBMS, which is tuned to work with
Oracle's Network Computer, NC. Along with these, it provides support to Java, HTML,
and OLTP in its features.

ORACLE PROJECT 2
• Oracle 8i was released in the year 1998. Here, the alphabet 'I' stands for Internet. It was the
first database version that added support for Web technologies like Java and HTTP.

• The release in the year 2001 was Oracle 9i and added a total of 400 new features like XML,
RAC, etc. These new features reduce the size of the database and provide great availability
and performance.

• Oracle 10g was released in 2003. The word g stands for grid computing technology means
grid. It is the first version that supports 64-bit LINUX OS.

• Oracle 11g was published in 2006. Some inclusions of features that were new then included,
but were not limited to, Oracle Database Replay, Log Miner-based Transaction Management,
Virtual Column Partitioning, Case-sensitive passwords, Online Patching, and Parallel Backups
through the same file with RMAN.

• Oracle 12c, released in July 2014 with Cloud Support.

• Oracle 18 C was released in Feb 2018. It was the world's first autonomous database.

• In 2020, Oracle released Oracle 19c without making any compromise in high
performance, scalability, and advanced security features, thereby improving in cloud areas.

Advantages of Oracle Database


1. Scalability: Oracle Database, as an organization grows and scales effortlessly to huge
amounts of data and transactions.

2. High performance: Advanced optimization features execute queries and process data in the
shortest time.

3. Data Security: Having Strong security features that keep data safe from unauthorized access.

4. Flexibility: It is very flexible, supporting multiple data models and on-


premises deployment as well as cloud deployment.

5. High availability: mechanisms like Oracle RAC and Data Guard guarantee that the system is
available in case of failures or other outages.

Disadvantages of Oracle Database


1. Costly: Licensing and Oracle's support service are pretty high, hence a challenge to small-
scale firms.

2. Complexity: Multiplicity of features and multiple configurations require a steep learning


curve for management.

3. High hardware resources: Oracle Database could prove to be overweight for lightweight
applications if some hardware requirements are considered.

4. Maintenance: It involves quite regular maintenance, updating, and tuning for its effective
working.

ORACLE PROJECT 3
DBMS
Database Management System (DBMS) is a software used to manage data from a database.

• A database is a structured collection of data that is stored in an electronic device. The data can be
text, video, image or any other format.

• A relational database stores data in the form of tables and a NoSQL database in the form of key-value
pairs.

• SQL (Structured Query Language) is a standard language for accessing and manipulating data in a
relational database.

• A DBMS is a software that allows to create, update and retrieval of data in an organized way. It also
provides security to the database.

• Examples of relational DBMS are MySQL, Oracle, Microsoft SQL Server, Postgre SQL and Snowflake.

• Examples of NoSQL DBMS are MongoDB, Cassandra, DynamoDB and Redis.

Key Features of DBMS

1. Data Modeling: Tools to create and modify data models, defining the structure and
relationships within the database.

2. Data Storage and Retrieval: Efficient mechanisms for storing data and executing queries to
retrieve it quickly.

3. Concurrency Control: Ensures multiple users can access the database simultaneously
without conflicts.

4. Data Integrity and Security: Enforces rules to maintain accurate and secure data, including
access controls and encryption.

5. Backup and Recovery: Protects data with regular backups and enables recovery in case of
system failures.

ORACLE PROJECT 4
Architecture of DBMS

Types of DBMS

There are several types of Database Management Systems (DBMS), each tailored to different data
structures, scalability requirements, and application needs. The most common types are as follows:

1. Relational Database Management System (RDBMS)

RDBMS organizes data into tables (relations) composed of rows and columns. It uses primary keys to
uniquely identify rows and foreign keys to establish relationships between tables. Queries are written
in SQL (Structured Query Language), which allows for efficient data manipulation and retrieval.

Examples: MySQL, Oracle, Microsoft SQL Server and Postgre SQL.

2. NoSQL DBMS

NoSQL systems are designed to handle large-scale data and provide high performance for scenarios
where relational models might be restrictive. They store data in various non-relational formats, such
as key-value pairs, documents, graphs, or columns. These flexible data models enable rapid scaling
and are well-suited for unstructured or semi-structured data.

Examples: MongoDB, Cassandra, DynamoDB and Redis.

3. Object-Oriented DBMS (OODBMS)


ORACLE PROJECT 5
OODBMS integrates object-oriented programming concepts into the database environment,
allowing data to be stored as objects. This approach supports complex data types and relationships,
making it ideal for applications requiring advanced data modeling and real-world simulations.

Examples: ObjectDB, db4o.

Database Languages

Database languages are specialized sets of commands and instructions used to define, manipulate,
and control data within a database. Each language type plays a distinct role in database
management, ensuring efficient storage, retrieval, and security of data. The primary database
languages include:

1. Data Definition Language (DDL)

DDL is the short name for Data Definition Language, which deals with database schemas and
descriptions, of how the data should reside in the database.

• CREATE: to create a database and its objects like (table, index, views, store procedure,
function, and triggers)

• ALTER: alters the structure of the existing database

• DROP: delete objects from the database

• TRUNCATE: remove all records from a table, including all spaces allocated for the records are
removed

• COMMENT: add comments to the data dictionary

• RENAME: rename an object

2. Data Manipulation Language (DML)

DML focuses on manipulating the data stored in the database, enabling users to retrieve, add,
update, and delete data.

• SELECT: retrieve data from a database

• INSERT: insert data into a table

• UPDATE: updates existing data within a table

• DELETE: Delete all records from a database table

• MERGE: UPSERT operation (insert or update)

• CALL: call a PL/SQL or Java subprogram

• EXPLAIN PLAN: interpretation of the data access path

• LOCK TABLE: concurrency Control

3. Data Control Language (DCL)

DCL commands manage access permissions, ensuring data security by controlling who can perform
certain actions on the database.

ORACLE PROJECT 6
• GRANT: Provides specific privileges to a user (e.g., SELECT, INSERT).

• REVOKE: Removes previously granted permissions from a user.

4. Transaction Control Language (TCL)

TCL commands oversee transactional data to maintain consistency, reliability, and atomicity.

• ROLLBACK: Undoes changes made during a transaction.

• COMMIT: Saves all changes made during a transaction.

• SAVEPOINT: Sets a point within a transaction to which one can later roll back.

5. Data Query Language (DQL)

DQL is a subset of DML, specifically focused on data retrieval.

• SELECT: The primary DQL command, used to query data from the database without altering
its structure or contents.

ORACLE PROJECT 7
RDBMS RELATIONAL DATABASE MANAGEMENT
SYSTEM
RDBMS stands for Relational Database Management System.

All modern database management systems like SQL, MS SQL Server, IBM DB2, ORACLE, My-SQL, and
Microsoft Access are based on RDBMS.

It is called Relational Database Management System (RDBMS) because it is based on the relational
model introduced by E.F. Codd.

What is table/Relation?

Everything in a relational database is stored in the form of relations. The RDBMS database uses
tables to store data. A table is a collection of related data entries and contains rows and columns to
store data. Each table represents some real-world objects such as person, place, or event about
which information is collected. The organized collection of data into a relational table is known as the
logical view of the database.

Properties of a Relation:

o Each relation has a unique name by which it is identified in the database.

o Relation does not contain duplicate tuples.

o The tuples of a relation have no specific order.

o All attributes in a relation are atomic, i.e., each cell of a relation contains exactly one value.

A table is the simplest example of data stored in RDBMS.

Let's see the example of the student table.

ORACLE PROJECT 8
RDBMS ARCHITECTURE

ORACLE PROJECT 9
SQL- Structured Query Language
the standard language for managing relational databases
SQL is supported by MySQL, Oracle, SQL Server, PostgreSQL, etc.

Important Commands example-


1. CREATE TABLE – Creates a new table
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);

2. INSERT INTO- Inserts new records


INSERT INTO students (id, name, age) VALUES (1, 'John', 20);

3. SELECT – Retrieves data


SELECT name, age FROM students WHERE age > 18;

4. GRANT – Gives permissions


GRANT SELECT ON students TO user1;

5. REVOKE – Removes permissions


REVOKE SELECT ON students FROM user1;

SQL Constraints

ORACLE PROJECT 10
Constraints ensure data integrity in tables.

Example:
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
salary DECIMAL(10,2) CHECK (salary > 0)
);

SQL Joins
Joins combine records from multiple tables

SQL Aggregate Functions


Used for calculations on data.

SQL Subqueries & Views


• Subquery: A query inside another query.

ORACLE PROJECT 11
SELECT name FROM students WHERE age = (SELECT MAX(age) FROM students);
• View: A virtual table based on a query.
CREATE VIEW student_view AS SELECT name, age FROM students;

SQL Data Types:

Data types define the type of data that can be stored in a column.

Different categories:

1. Numeric Data types

Used for storing numbers (integers and floating-point values).

Example:

CREATE TABLE employees (

emp_id INT,

salary NUMBER(10,2),

bonus DECIMAL(8,2)

);

2. Character/String Data Types

Used for storing text and string values.

Example:

CREATE TABLE students (

ORACLE PROJECT 12
student_id INT,
name VARCHAR(50),
remarks TEXT
);

3. Date/Time Data Types

Used for storing date and time values.

Example:

CREATE TABLE orders (

order_id INT,

order_date DATE,

delivery_time TIMESTAMP

);

4. Other SQL Data Types

Components of SQL system:

1.Database 2.Tables 8.Join

3.Queries 4.Index 9.Views

5.Constraints 6.Stored Procedure

7.Transactions- (group of SQL statements executed as a single unit)

Types of SQL Operators

ORACLE PROJECT 13
ORACLE PROJECT 14
Operator Precedence (Execution Order)

Operators follow a specific order of execution, similar to BODMAS (Brackets, Orders, Division,
Multiplication, Addition, Subtraction) in Mathematics.

1. Arithmetic Operators (*, /, %, +, -)


2. Comparison Operators (=, >, <, >=, <=, !=)
3. Logical NOT
4. Logical AND
5. Logical OR

ORACLE PROJECT 15
PL/SQL

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

Allows procedural programming using loops, conditions, and exception handling.

PL/SQL is used for writing stored procedures, triggers, functions, and packages.

Features:

1. Supports procedural programming (IF, LOOP, CASE).


2. Allows error handling using EXCEPTION
3. Enhances performance by reducing multiple SQL calls.
4. Supports modular programming with procedures and functions.
5. Ensures data security with stored procedures.

PL/SQL block structure:

DECLARE -- (Optional) Declare variables

BEGIN -- (Mandatory) Execution section

-- SQL and PL/SQL statements

EXCEPTION -- (Optional) Error handling

-- Error-handling code

END;

PL/SQL Data Types

PL/SQL Control Statements

1. Conditional Statements

IF-THEN

IF salary > 50000 THEN

DBMS_OUTPUT.PUT_LINE('High Salary');

END IF;

ORACLE PROJECT 16
IF-THEN-ELSE

IF salary > 50000 THEN

DBMS_OUTPUT.PUT_LINE('High Salary');

ELSE

DBMS_OUTPUT.PUT_LINE('Low Salary');

END IF;

CASE Statement

CASE

WHEN salary > 50000 THEN DBMS_OUTPUT.PUT_LINE('High Salary');

WHEN salary > 30000 THEN DBMS_OUTPUT.PUT_LINE('Medium Salary');

ELSE DBMS_OUTPUT.PUT_LINE('Low Salary');

END CASE;

Loops in PL/SQL

Example: FOR LOOP

BEGIN

FOR i IN 1..5 LOOP

DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);

END LOOP;

END;

ORACLE PROJECT 17
SQL *PLUS
SQL*Plus is an interactive tool provided by Oracle for executing SQL commands and PL/SQL blocks. t
supports both command-line and GUI versions.

SQL*Plus Commands

1. Environment Commands

2. Formatting Commands

3. Query Execution Commands

SQL*Plus Editing Commands

SQL*Plus provides editing commands to modify SQL statements.

ORACLE PROJECT 18
Stored Procedures
A Stored Procedure is a precompiled set of SQL statements stored in the database. It executes as a
single unit

Key Characteristics

✔ Stored in the database schema and executed when needed.

✔ Supports parameters to accept input values and return output.


✔ Can be used to perform DML and DDL operations.
✔ Reduces redundancy by allowing reuse of SQL logic.

Advanatges-

1.Because it is precompiled, it saves execution time.

2. Code Reusability

3. Centralized logic ensures uniform business rules across application

A stored procedure typically consists of:

Types of Stored Procedures

Stored Procedure vs. Regular SQL Queries

ORACLE PROJECT 19
ORACLE PROJECT 20
Functions in SQL
SQL Functions are built-in operations that perform calculations, modify data, and return results.

Types of SQL Functions

SQL functions are categorized into two main types:

1. Single-Row (Scalar) Functions

• Operate on a single value and return a single result.

• Used for string, numeric, date, and conversion operations.

2. Aggregate (Group) Functions

• Operate on multiple rows and return a single summary value.

• Commonly used with GROUP BY for summarizing data.

Single-Row (Scalar) Functions

A. String Functions (Used to manipulate text data)

B. Numeric Functions (Perform mathematical calculations)

C. Date & Time Functions (Work with date and time values)

ORACLE PROJECT 21
D. Conversion Functions (Convert data types)

Aggregate (Group) Functions

ORACLE PROJECT 22
TRIGGER
A Trigger is a stored PL/SQL block that automatically executes when a specified event occurs in the
database. Triggers can be set to fire BEFORE or AFTER an event.

Advantages of Triggers

✔ Automatic Execution – No manual execution required.


✔ Enforces Business Rules – Restrict invalid data.
✔ Audit and Logging – Track changes automatically.
✔ Maintains Data Integrity – Prevent unauthorized modifications.

CURSOR
A cursor in PL/SQL is a pointer to a result set of a SQL query. It is used to fetch and process multiple
rows from a database. Cursors are essential for handling query results row by row.

ORACLE PROJECT 23
Advantages of Cursors

✔ Handles multiple rows from queries efficiently.


✔ Provides row-by-row processing for complex logic.
✔ Dynamic processing using parameterized or REF cursors.
✔ Improves performance by avoiding multiple query executions

JOIN
Joins in SQL are used to combine data from two or more tables based on a related column

ORACLE PROJECT 24
1.Inner join:

SELECT Students.student_name, Courses.course_name

FROM Students

INNER JOIN Courses

ON Students.course_id = Courses.course_id;

2.Left join:

SELECT Students.student_name, Courses.course_name

FROM Students

LEFT JOIN Courses

ORACLE PROJECT 25
ON Students.course_id = Courses.course_id;

3.Right join:

SELECT Students.student_name, Courses.course_name

FROM Students

RIGHT JOIN Courses

ON Students.course_id = Courses.course_id;

4.Full join:

SELECT Students.student_name, Courses.course_name

FROM Students

FULL JOIN Courses

ON Students.course_id = Courses.course_id;

5.Cross join:

SELECT Students.student_name, Courses.course_name

FROM Students
ORACLE PROJECT 26
CROSS JOIN Courses;

CLAUSES

SQL clause helps us to retrieve a set of records from the table by specifying a condition on the
columns or records of a table.

(A) WHERE Clause

Used to filter records based on a condition


Works with SELECT, UPDATE, DELETE statements

Example: Get students enrolled in course 101

SELECT * FROM Students WHERE course_id = 101;

ORACLE PROJECT 27
(B) HAVING Clause

Used to filter records based on aggregated data (GROUP BY results)


Works only with GROUP BY

Example: Get courses where more than 2 students are enrolled

SELECT course_id, COUNT(student_id)

FROM Students

GROUP BY course_id

HAVING COUNT(student_id) > 2;

(C) ORDER BY Clause

Used to sort query results in ascending or descending order


Default sorting is ASC (Ascending)

Example: Get all students sorted by name in descending order

SELECT * FROM Students ORDER BY student_name DESC;

(D) GROUP BY Clause

Groups rows based on a column’s value and applies aggregate functions

Example: Count the number of students in each course

SELECT course_id, COUNT(student_id)

FROM Students

GROUP BY course_id;

ORACLE PROJECT 28
CONSTRAINTS
SQL Constraints are rules applied to table columns to ensure data integrity and accuracy.
They prevent invalid, duplicate, or inconsistent data in the database.
Constraints are applied during table creation using the CREATE TABLE or later with ALTER TABLE.

Types of SQL Constraints

(A) PRIMARY KEY Constraint

Ensures that each row in a column is unique and NOT NULL.


A table can have only one PRIMARY KEY

CREATE TABLE Students (

student_id INT PRIMARY KEY,

student_name VARCHAR(50),

course_id INT

);

Key Points:

• Each student_id must be unique and cannot be NULL.

• A table can have only one PRIMARY KEY, but it can consist of multiple columns (Composite
Key).

(B) FOREIGN KEY Constraint

ORACLE PROJECT 29
Ensures referential integrity by linking a column to the PRIMARY KEY of another table.
Prevents invalid data entry in child tables.

CREATE TABLE Courses (

course_id INT PRIMARY KEY,

course_name VARCHAR(50)

);

CREATE TABLE Students (

student_id INT PRIMARY KEY,

student_name VARCHAR(50),

course_id INT,

FOREIGN KEY (course_id) REFERENCES Courses(course_id)

);

Key Points:

• course_id in Students must match a valid course_id in Courses.

• If a course_id does not exist in Courses, it cannot be inserted in Students.

(C) UNIQUE Constraint

Ensures that values in a column are unique (no duplicates allowed).


Unlike PRIMARY KEY, it allows NULL values (unless NOT NULL is used).

CREATE TABLE Users (

user_id INT PRIMARY KEY,

email VARCHAR(100) UNIQUE

);

Key Points:

• Each email must be unique but can be NULL.

• A table can have multiple UNIQUE columns.

(D) NOT NULL Constraint

Ensures that a column cannot store NULL values.

CREATE TABLE Employees (

ORACLE PROJECT 30
emp_id INT PRIMARY KEY,

emp_name VARCHAR(50) NOT NULL,

salary DECIMAL(10,2) NOT NULL

);

Key Points:

• emp_name and salary must have values (cannot be NULL).

• Useful for mandatory fields like Name, Email, etc.

(E) CHECK Constraint

Ensures that column values meet a specific condition.

CREATE TABLE Products (

product_id INT PRIMARY KEY,

price DECIMAL(10,2) CHECK (price > 0)

);

Key Points:

• The price must be greater than 0.

• Helps enforce valid data ranges (e.g., age must be ≥18).

(F) DEFAULT Constraint

Assigns a default value to a column if no value is provided.

CREATE TABLE Orders (

order_id INT PRIMARY KEY,

order_status VARCHAR(20) DEFAULT 'Pending'

);

Key Points:

• If no value is inserted in order_status, it defaults to 'Pending'.

• Useful for setting default values like 0 for quantity, CURRENT_TIMESTAMP for dates, etc.

ORACLE PROJECT 31
Transaction Control & Concurrency Control
1. Transaction Control in SQL

What is a Transaction?

A transaction is a set of SQL operations executed as a single unit.


It follows the ACID properties (Atomicity, Consistency, Isolation, Durability).

Transaction Control Language (TCL) Commands

SQL provides TCL commands to manage transactions effectively:

2. Concurrency Control in SQL

What is Concurrency Control?

Concurrency control manages multiple users accessing the database simultaneously to prevent
conflicts.
It ensures data consistency and integrity when multiple transactions are executed at the same
time.

ORACLE PROJECT 32
FORMS
1. What is a Form in Oracle?

Forms in Oracle are graphical user interfaces (GUI) that allow users to view, insert, update, and
delete data from a database easily.
They provide an interactive way to interact with database tables without writing SQL queries
manually.
Used in Oracle Forms Builder, a tool in Oracle Developer Suite.

2. Features of Oracle Forms


ORACLE PROJECT 33
3. Types of Forms in Oracle

4. Components of an Oracle Form

Blocks → Containers that hold items (text fields, buttons, etc.).


Items → Individual fields (text boxes, radio buttons, checkboxes).
Canvas → The area where the form is displayed.
Triggers → PL/SQL code executed when an event occurs (e.g., clicking a button).
Alerts → Pop-up messages to show warnings or confirmations.

REPORTS
1. What is a Report in Oracle?

Reports in Oracle are formatted documents that present database data in a structured way.
Used for data analysis, summaries, invoices, charts, and printable documents.
Created using Oracle Reports Builder, part of Oracle Developer Suite.

2. Features of Oracle Reports

ORACLE PROJECT 34
3. Types of Reports in Oracle

4. Components of an Oracle Report

Data Model → Defines the data source (SQL query, table, view).
Layout Model → Controls the report structure and formatting.
Parameter Form → Allows user input to filter data dynamically.
Triggers → PL/SQL code executed before/after the report runs.
Report Output → Can be displayed as PDF, HTML, Excel, or printed documents.

SET OPERATORS
SET operators are special type of operators which are used to combine the result of two queries. The
queries must have the same number of columns.

Types of Set Operators in SQL

ORACLE PROJECT 35
Examples of Set Operators

Consider two tables: Students_2023 and Students_2024

(1) UNION (Removes Duplicates)

Combines both tables but removes duplicate records.

Result of UNION

ORACLE PROJECT 36
(2) UNION ALL (Keeps Duplicates)

Combines both tables but keeps duplicates.

Result of UNION ALL

(3) INTERSECT (Common Rows in Both Tables)

Returns only the common records present in both tables.

Result of INTERSECT

(4) MINUS (First Table - Second Table)

Returns records from Students_2023 that are not in Students_2024.

Result of MINUS

ORACLE PROJECT 37
ATTRIBUTE DECLARATIONS (%TYPE, %ROWTYPE)

Attribute declarations in PL/SQL are placeholders used to declare variables dynamically based
on existing database structures.
They ensure data consistency and reduce maintenance efforts by automatically adapting to
changes in database schema.
The two main types of attribute declarations in PL/SQL are:

• %TYPE → Inherits the data type of a specific column.

• %ROWTYPE → Inherits the structure (all columns) of a table or cursor.

%TYPE Attribute

Definition:

The %TYPE attribute is used to declare a variable that inherits the data type of a specific column
in a table or another variable.
This ensures that if the column’s data type changes, the variable automatically adapts.

Syntax:

variable_name table_name.column_name%TYPE;

Advantages of %TYPE:

Prevents datatype mismatches.


Adapts automatically if the column’s data type changes.

%ROWTYPE Attribute

Definition:

The %ROWTYPE attribute is used to declare a record variable that inherits the structure of an
entire table row.
This means the record will have all columns and their respective data types from the table.

Syntax:

record_name table_name%ROWTYPE;

Advantages of %ROWTYPE:

ORACLE PROJECT 38
Stores multiple column values at once.
Reduces the number of variables needed.
Adapts automatically to table structure changes.

Key Differences Between %TYPE and %ROWTYPE

LIBRARY, ALERTS and LOV IN DEVELOPER 2000

1. Library

A Library (.PLL file) is a collection of reusable PL/SQL procedures, functions, and packages.
It allows developers to store and share commonly used PL/SQL code across multiple forms and
reports.
Libraries help in maintaining modular programming and code reusability.

Key Features of Libraries:

Encapsulation – Store reusable PL/SQL code in one place.


Modularity – Helps in reducing redundant code in forms and reports.

2. Alerts

What is an Alert?

An Alert is a popup message box used to display important messages, warnings, or


confirmations to users.
Alerts help in getting user input or providing error messages during form execution.

Types of Alerts in Oracle Developer 2000:

ORACLE PROJECT 39
3. LOV (List Of Values)

List of Values (LOV) is a popup window that displays a list of valid values for a field in an Oracle
Form.
It helps users select values easily instead of manually entering them.

ORACLE PROJECT 40
PROJECT 1- STUDENT MANAGEMENT SYSTEM

-- Creating Students Table


CREATE TABLE Students (
StudentID NUMBER PRIMARY KEY,
Name VARCHAR2(50) NOT NULL,
Age NUMBER CHECK (Age BETWEEN 5 AND 30),
Gender VARCHAR2(10) CHECK (Gender IN ('Male', 'Female', 'Other')),
CourseID NUMBER,
Email VARCHAR2(100) UNIQUE,
Phone VARCHAR2(15) UNIQUE,
Address VARCHAR2(200),
CONSTRAINT fk_course FOREIGN KEY (CourseID) REFERENCES Courses(CourseID) ON
DELETE SET NULL
);

-- Creating Courses Table


CREATE TABLE Courses (
CourseID NUMBER PRIMARY KEY,
CourseName VARCHAR2(50) NOT NULL,
Duration NUMBER CHECK (Duration BETWEEN 1 AND 5), -- in years
Fees NUMBER CHECK (Fees > 0)
);

-- Creating Marks Table


CREATE TABLE Marks (
MarkID NUMBER PRIMARY KEY,
StudentID NUMBER REFERENCES Students(StudentID) ON DELETE CASCADE,
Subject VARCHAR2(50),

ORACLE PROJECT 41
Marks NUMBER CHECK (Marks BETWEEN 0 AND 100),
ExamDate DATE DEFAULT SYSDATE
);

-- Creating Attendance Table


CREATE TABLE Attendance (
AttendanceID NUMBER PRIMARY KEY,
StudentID NUMBER REFERENCES Students(StudentID) ON DELETE CASCADE,
AttendanceDate DATE DEFAULT SYSDATE,
Status VARCHAR2(10) CHECK (Status IN ('Present', 'Absent', 'Late'))
);

-- Creating Teachers Table


CREATE TABLE Teachers (
TeacherID NUMBER PRIMARY KEY,
Name VARCHAR2(50) NOT NULL,
Subject VARCHAR2(50),
Email VARCHAR2(100) UNIQUE,
Phone VARCHAR2(15) UNIQUE
);

-- Inserting Courses
INSERT INTO Courses VALUES (101, 'Computer Science', 4, 120000);
INSERT INTO Courses VALUES (102, 'Mathematics', 3, 100000);
INSERT INTO Courses VALUES (103, 'Physics', 3, 110000);

-- Inserting Students

ORACLE PROJECT 42
INSERT INTO Students VALUES (1, 'John Doe', 20, 'Male', 101, 'john.doe@example.com',
'9876543210', 'New York, USA');
INSERT INTO Students VALUES (2, 'Jane Smith', 22, 'Female', 102,
'jane.smith@example.com', '8765432109', 'California, USA');
INSERT INTO Students VALUES (3, 'Sam Brown', 19, 'Male', 103, 'sam.brown@example.com',
'7654321098', 'Texas, USA');

-- Inserting Marks
INSERT INTO Marks VALUES (1, 1, 'Mathematics', 90, TO_DATE('2024-02-10', 'YYYY-MM-
DD'));
INSERT INTO Marks VALUES (2, 1, 'Science', 85, TO_DATE('2024-02-15', 'YYYY-MM-DD'));
INSERT INTO Marks VALUES (3, 2, 'Mathematics', 88, TO_DATE('2024-02-12', 'YYYY-MM-
DD'));

-- Inserting Attendance
INSERT INTO Attendance VALUES (1, 1, SYSDATE, 'Present');
INSERT INTO Attendance VALUES (2, 2, SYSDATE, 'Absent');

-- Inserting Teachers
INSERT INTO Teachers VALUES (1, 'Dr. Alan Turing', 'Computer Science',
'alan.turing@example.com', '9988776655');
INSERT INTO Teachers VALUES (2, 'Dr. Isaac Newton', 'Mathematics',
'isaac.newton@example.com', '8877665544');

-- Fetch all students


SELECT * FROM Students;

-- Get students and their courses


SELECT S.StudentID, S.Name, C.CourseName, C.Duration

ORACLE PROJECT 43
FROM Students S
JOIN Courses C ON S.CourseID = C.CourseID;

-- Find students who scored above 85


SELECT S.Name, M.Subject, M.Marks
FROM Students S
JOIN Marks M ON S.StudentID = M.StudentID
WHERE M.Marks > 85;

-- Show attendance of all students


SELECT S.Name, A.AttendanceDate, A.Status
FROM Students S
JOIN Attendance A ON S.StudentID = A.StudentID;

CREATE OR REPLACE PROCEDURE Add_Student(


p_StudentID NUMBER,
p_Name VARCHAR2,
p_Age NUMBER,
p_Gender VARCHAR2,
p_CourseID NUMBER,
p_Email VARCHAR2,
p_Phone VARCHAR2,
p_Address VARCHAR2
) AS
BEGIN
INSERT INTO Students (StudentID, Name, Age, Gender, CourseID, Email, Phone, Address)

ORACLE PROJECT 44
VALUES (p_StudentID, p_Name, p_Age, p_Gender, p_CourseID, p_Email, p_Phone,
p_Address);
DBMS_OUTPUT.PUT_LINE('Student added successfully!');
END;
/

EXEC Add_Student(4, 'Alice Johnson', 21, 'Female', 101, 'alice.j@example.com',


'9998887776', 'Florida, USA');

CREATE OR REPLACE TRIGGER prevent_duplicate_email


BEFORE INSERT OR UPDATE ON Students
FOR EACH ROW
BEGIN
IF EXISTS (SELECT 1 FROM Students WHERE Email = :NEW.Email) THEN
RAISE_APPLICATION_ERROR(-20001, 'Email already exists!');
END IF;
END;
/

CREATE OR REPLACE TRIGGER auto_mark_absent


AFTER INSERT ON Students
FOR EACH ROW
BEGIN
INSERT INTO Attendance (AttendanceID, StudentID, AttendanceDate, Status)
VALUES (SEQ_ATTENDANCEID.NEXTVAL, :NEW.StudentID, SYSDATE, 'Absent');
END;
/

ORACLE PROJECT 45
CREATE OR REPLACE VIEW Top_Students AS
SELECT S.Name, M.Subject, M.Marks
FROM Students S
JOIN Marks M ON S.StudentID = M.StudentID
WHERE M.Marks > 85;

SELECT * FROM Top_Students;

CREATE OR REPLACE FUNCTION Get_Avg_Marks(p_StudentID NUMBER) RETURN NUMBER IS


v_AvgMarks NUMBER;
BEGIN
SELECT AVG(Marks) INTO v_AvgMarks
FROM Marks
WHERE StudentID = p_StudentID;
RETURN v_AvgMarks;
END;
/
SELECT Get_Avg_Marks(1) FROM DUAL;

ORACLE PROJECT 46
PROJECT 2- LIBRARY MANAGEMENT SYSTEM

-- Books Table
CREATE TABLE Books (
BookID NUMBER PRIMARY KEY,
Title VARCHAR2(100) NOT NULL,
Author VARCHAR2(100) NOT NULL,
PublishedYear NUMBER CHECK (PublishedYear BETWEEN 1500 AND 2100),
ISBN VARCHAR2(20) UNIQUE NOT NULL,
AvailableCopies NUMBER CHECK (AvailableCopies >= 0)
);

-- Borrowers Table
CREATE TABLE Borrowers (
BorrowerID NUMBER PRIMARY KEY,
Name VARCHAR2(50) NOT NULL,
Contact VARCHAR2(20) UNIQUE NOT NULL,
Email VARCHAR2(100) UNIQUE NOT NULL,
Address VARCHAR2(200),
RegistrationDate DATE DEFAULT SYSDATE
);

-- Borrowed Books Table (Tracks Issued & Returned Books)


CREATE TABLE BorrowedBooks (
TransactionID NUMBER PRIMARY KEY,
BookID NUMBER REFERENCES Books(BookID) ON DELETE CASCADE,
BorrowerID NUMBER REFERENCES Borrowers(BorrowerID) ON DELETE CASCADE,
BorrowDate DATE DEFAULT SYSDATE,
ReturnDate DATE,

ORACLE PROJECT 47
Status VARCHAR2(10) CHECK (Status IN ('Issued', 'Returned'))
);

-- Librarians Table
CREATE TABLE Librarians (
LibrarianID NUMBER PRIMARY KEY,
Name VARCHAR2(50) NOT NULL,
Email VARCHAR2(100) UNIQUE NOT NULL,
Phone VARCHAR2(15) UNIQUE NOT NULL
);

-- Fines Table (For Late Returns)


CREATE TABLE Fines (
FineID NUMBER PRIMARY KEY,
BorrowerID NUMBER REFERENCES Borrowers(BorrowerID) ON DELETE CASCADE,
Amount NUMBER CHECK (Amount >= 0),
FineDate DATE DEFAULT SYSDATE,
PaidStatus VARCHAR2(10) CHECK (PaidStatus IN ('Paid', 'Unpaid'))
);

-- Inserting Books
INSERT INTO Books VALUES (1, 'Introduction to SQL', 'John Smith', 2020, '1234567890', 5);
INSERT INTO Books VALUES (2, 'Database Design', 'Alice Brown', 2019, '0987654321', 3);
INSERT INTO Books VALUES (3, 'Oracle PL/SQL Programming', 'Steven Feuerstein', 2021,
'1122334455', 2);

-- Inserting Borrowers

ORACLE PROJECT 48
INSERT INTO Borrowers VALUES (1, 'Tom Hardy', '9876543210', 'tom@example.com', 'New
York, USA', SYSDATE);
INSERT INTO Borrowers VALUES (2, 'Emily Clark', '8765432109', 'emily@example.com',
'California, USA', SYSDATE);

-- Inserting Librarians
INSERT INTO Librarians VALUES (1, 'Robert Langdon', 'robert@example.com', '9988776655');
INSERT INTO Librarians VALUES (2, 'Sarah Connor', 'sarah@example.com', '8877665544');

-- Borrowing Books
INSERT INTO BorrowedBooks VALUES (1, 1, 1, TO_DATE('2024-02-10', 'YYYY-MM-DD'), NULL,
'Issued');
INSERT INTO BorrowedBooks VALUES (2, 2, 2, TO_DATE('2024-02-12', 'YYYY-MM-DD'),
TO_DATE('2024-02-20', 'YYYY-MM-DD'), 'Returned');

--Adding Fines
INSERT INTO Fines VALUES (1, 1, 100, TO_DATE('2024-02-15', 'YYYY-MM-DD'), 'Unpaid');

-- Get All Available Books


SELECT * FROM Books WHERE AvailableCopies > 0;

-- Get All Borrowed Books


SELECT B.Title, Bo.Name, Bb.BorrowDate, Bb.ReturnDate, Bb.Status
FROM BorrowedBooks Bb
JOIN Books B ON Bb.BookID = B.BookID
JOIN Borrowers Bo ON Bb.BorrowerID = Bo.BorrowerID;

-- Get Overdue Books (Not Returned in 14 Days)

ORACLE PROJECT 49
SELECT B.Title, Bo.Name, Bb.BorrowDate
FROM BorrowedBooks Bb
JOIN Books B ON Bb.BookID = B.BookID
JOIN Borrowers Bo ON Bb.BorrowerID = Bo.BorrowerID
WHERE Bb.Status = 'Issued' AND Bb.BorrowDate < SYSDATE - 14;

-- Get Borrowers with Unpaid Fines


SELECT Bo.Name, F.Amount, F.FineDate
FROM Fines F
JOIN Borrowers Bo ON F.BorrowerID = Bo.BorrowerID
WHERE F.PaidStatus = 'Unpaid';

Procedure to Issue a Book


CREATE OR REPLACE PROCEDURE IssueBook(
p_BookID NUMBER,
p_BorrowerID NUMBER
) AS
v_AvailableCopies NUMBER;
BEGIN
-- Check if the book is available
SELECT AvailableCopies INTO v_AvailableCopies FROM Books WHERE BookID = p_BookID;

IF v_AvailableCopies > 0 THEN


-- Insert Borrow Record
INSERT INTO BorrowedBooks (TransactionID, BookID, BorrowerID, BorrowDate, Status)
VALUES (SEQ_TRANSACTIONID.NEXTVAL, p_BookID, p_BorrowerID, SYSDATE, 'Issued');

ORACLE PROJECT 50
-- Update Available Copies
UPDATE Books SET AvailableCopies = AvailableCopies - 1 WHERE BookID = p_BookID;

DBMS_OUTPUT.PUT_LINE('Book Issued Successfully!');


ELSE
DBMS_OUTPUT.PUT_LINE('Book Not Available!');
END IF;
END;
/
Execute the Procedure
sql
CopyEdit
EXEC IssueBook(1, 2);

Trigger to Prevent Duplicate ISBN Numbers


sql
CopyEdit
CREATE OR REPLACE TRIGGER PreventDuplicateISBN
BEFORE INSERT OR UPDATE ON Books
FOR EACH ROW
BEGIN
IF EXISTS (SELECT 1 FROM Books WHERE ISBN = :NEW.ISBN) THEN
RAISE_APPLICATION_ERROR(-20002, 'ISBN already exists!');
END IF;
END;
/
Trigger to Auto-Update Fines for Late Returns

ORACLE PROJECT 51
sql
CopyEdit
CREATE OR REPLACE TRIGGER AutoApplyFine
AFTER UPDATE ON BorrowedBooks
FOR EACH ROW
BEGIN
IF :NEW.ReturnDate > :OLD.BorrowDate + 14 THEN
INSERT INTO Fines (FineID, BorrowerID, Amount, FineDate, PaidStatus)
VALUES (SEQ_FINEID.NEXTVAL, :NEW.BorrowerID, 50, SYSDATE, 'Unpaid');
END IF;
END;
/

View to Show Borrowed Books with Borrower Details


CREATE OR REPLACE VIEW Borrowed_Book_View AS
SELECT Bb.TransactionID, B.Title, Bo.Name, Bb.BorrowDate, Bb.ReturnDate, Bb.Status
FROM BorrowedBooks Bb
JOIN Books B ON Bb.BookID = B.BookID
JOIN Borrowers Bo ON Bb.BorrowerID = Bo.BorrowerID;
Use the View
sql
CopyEdit
SELECT * FROM Borrowed_Book_View;

ORACLE PROJECT 52
ORACLE PROJECT 53

You might also like