Rdbms & Oracle Lecture Notes
Rdbms & Oracle Lecture Notes
LECTURE HANDOUTS
Semester V
Course Objectives:
1. The course describes the data, organizing the data in database, database
administration.
3. To study the physical and logical database designs and database modeling
like relational, hierarchical, network models, database security, integrity and
normalization.
4. Introduction to SQL language to retrieve the data from the database with
suitable application development.
Database Relationships
1. Primary Key:
2. Foreign Key:
3. Referential Integrity:
1. Data Integrity:
1. Tables (Relations):
2. Attributes (Fields):
Each attribute has a data type, defining the kind of data it can
store (e.g., integer, string, date).
3. Tuples (Rows):
4. Primary Key:
5. Foreign Key:
2. Data Independence:
3. Query Flexibility:
2. Performance Implications:
Extended Concepts:
1. Database Normalization:
2. ACID Properties:
Integrity rules ensure the accuracy and consistency of data within a database.
Key integrity rules include entity integrity (ensuring that each row in a table is
unique), referential integrity (maintaining relationships between tables), and
domain integrity (ensuring that data values fall within defined ranges or sets).
Entity Integrity
Referential Integrity
Domain Integrity
Check Constraints
Cascading Actions
1. Relational Algebra:
Difference (-): It returns the rows that are present in one relation but
not in another.
Cartesian Product (×): It combines every row from the first relation
with every row from the second relation.
2. Relational Calculus:
While not traditional languages, the concepts of 4NF and DKNF are important
for understanding the theoretical aspects of relational databases.
Conclusion:
Oracle9i Overview:
1. Introduction to Oracle9i:
Release Version: Oracle9i was released in 2001 and was the successor to
Oracle8i. It introduced several new features and enhancements for
improved performance, scalability, and web integration.
Key Features:
2. Architecture of Oracle9i:
Database Files: Data files, control files, and redo log files constitute the
physical storage components of an Oracle database.
Personal Databases:
1. Definition:
2. Characteristics:
3. Use Cases:
Client/Server Databases:
1. Definition:
2. Components:
Client: The client is the end-user interface where applications run. It can
be a desktop computer, a web browser, or any device interacting with
the application.
Server: The server hosts the database management system and handles
database-related tasks. It manages data storage, retrieval, and
processing requests from clients.
3. Advantages:
SQL*Plus Environment:
1. Definition:
2. Key Features:
Scripting and Automation: Users can create and execute SQL scripts to
perform multiple tasks, automating database operations.
1. Connection Process:
sqlplus username/password@tnsname
2. Example:
After successful login, the user is presented with the SQL*Plus prompt,
where SQL commands and statements can be entered.
SQL*Plus Commands:
1. Basic Commands:
2. SQL*Plus-Specific Commands:
1. Error Handling:
Error messages provide details about the nature of the error, aiding in
troubleshooting.
2. Help Commands:
1. Introduction:
While SQL*Plus has its built-in editor for entering and editing SQL
commands, users may prefer using alternate text editors for a more
comfortable and feature-rich experience.
Commonly used editors include Notepad, Vim, Emacs, or any text editor
of choice.
3. Usage:
After setting the editor, the EDIT command opens the specified editor to
edit the SQL command currently in the buffer.
Once the user saves and exits the editor, the edited SQL command is
executed in SQL*Plus.
SQL*Plus Worksheet:
1. Definition:
2. Key Features:
Script Execution: Users can execute SQL scripts and PL/SQL blocks
directly from the worksheet.
3. Usage:
Users can open SQL*Plus Worksheet within Oracle SQL Developer and
connect to a database.
Once connected, users can enter and execute SQL and PL/SQL
commands, view query results, and perform various database-related
tasks through the graphical interface.
iSQL*Plus:
1. Definition:
iSQLPlus is a web-based version of SQLPlus that allows users to interact
with Oracle databases through a web browser. It provides a convenient
way to execute SQL commands and manage databases without the need
for a dedicated client installation.
2. Key Features:
Command Execution: Users can enter and execute SQL and PL/SQL
commands directly through the web interface.
Script Execution: Similar to SQL Plus, iSQL Plus allows users to execute
SQL scripts stored on the server.
3. Usage:
Once logged in, users can execute SQL commands, scripts, and perform
various database tasks through the web-based interface.
Interface:
Access:
Environment:
Usage Scenario:
Special characters such as $, _, and # are allowed within the name, but
the table name should not begin with a number or contain spaces.
Special characters and underscores are allowed, and they should not
begin with a number.
3. Case Sensitivity:
4. Reserved Words:
Data Types:
CLOB/BLOB: Large object types for handling character and binary data.
Numeric data types like NUMBER can include precision (total number of
digits) and scale (number of digits to the right of the decimal point).
Example:
3. Date Format:
Example:
hire_date DATE;
Large Object (LOB) types such as CLOB and BLOB are used to store large
amounts of character or binary data.
Example:
resume CLOB;
Constraints:
Ensures that a column (or set of columns) uniquely identifies each row in
a table.
Used to enforce data integrity and provide a quick way to access specific
rows.
Example:
The foreign key column in one table refers to the primary key column in
another.
Example:
Ensures that all values in a column (or set of columns) are unique.
Example:
4. Check Constraint:
Example:
Example:
Example:
The CREATE TABLE statement allows for the inclusion of constraints such
as primary key, foreign key, unique, check, etc., to define data integrity
rules.
1. Describing a Table:
Example:
DESCRIBE employees;
Example:
Example:
2. Modifying a Column:
The MODIFY clause is used within the ALTER TABLE statement to modify
the data type or size of an existing column.
Example:
The DROP TABLE statement is used to remove an entire table and its
data.
Example:
Example:
The TRUNCATE TABLE statement removes all rows from a table but
retains the structure for future use.
Example:
Table Types:
1. Heap-Organized Tables:
Example:
3. Temporary Tables:
Example:
Spooling:
1. Spooling in SQL*Plus:
Example:
This example spools the result of the query to a file named "output.txt."
Error Codes:
Oracle SQL errors are identified by error codes that provide information
about the nature of the error.
Example:
sqlCopy code
This query would result in an error, and the error code can be retrieved
using tools like SQL*Plus or by querying the DBA_ERRORS view.
2. Exception Handling:
Example:
BEGIN -- SQL statements here EXCEPTION WHEN OTHERS THEN -- Handle the
exception END;
Working with Table: Data Management and Retrieval: DML– Adding a new
Row/Record– Customized Prompts–Updating and Deleting an Existing
Rows/Records–retrieving Data from Table – Arithmetic Operations – restricting
Data with WHERE clause – Sorting – Revisiting Substitution Variables – DEFINE
command – CASE structure. Functions and Grouping: Built-in functions–
Grouping Data. Multiple Tables: Joins and Set operations: Join–Set operations.
1. INSERT Statement:
Example:
This example inserts a new employee record into the "employees" table.
When certain columns have default values, you can omit them from the
INSERT statement.
Example:
This assumes that other columns, such as the price, have default values
defined.
Customized Prompts:
1. User Input with PROMPT:
Example:
ACCEPT employee_id CHAR PROMPT 'Enter Employee ID: '; ACCEPT first_name
CHAR PROMPT 'Enter First Name: ';
These prompts will appear when the script is run, and users can input
values.
2. Using Variables:
Example:
1. UPDATE Statement:
Example:
2. DELETE Statement:
Example:
This example deletes products with stock quantities less than 10.
3. TRUNCATE TABLE:
The TRUNCATE TABLE statement is used to quickly remove all rows from
a table without logging individual row deletions.
Example:
Transaction Control:
1. COMMIT:
Example:
COMMIT;
After executing this statement, the changes are saved to the database.
2. ROLLBACK:
Example:
ROLLBACK;
This statement can be used to revert to the state of the database before
the transaction began.
1. SELECT Statement:
The SELECT statement is used to retrieve data from one or more tables
in a database.
Example:
SELECT * FROM employees;
2. Column Selection:
Example:
This retrieves only the specified columns from the "employees" table.
3. DISTINCT Keyword:
Example:
Arithmetic Operations:
1. Basic Arithmetic:
Example:
2. Aggregate Functions:
Aggregate functions like SUM, AVG, MIN, and MAX perform calculations
on sets of rows.
Example:
1. WHERE Clause:
Example:
2. Logical Operators:
Logical operators such as AND, OR, and NOT can be used to combine
conditions in the WHERE clause.
Example:
Sorting:
1. ORDER BY Clause:
The ORDER BY clause is used to sort the result set based on one or more
columns.
Example:
This retrieves employees and sorts them by last name and then first
name.
2. Sorting Direction:
Example:
SELECT employee_id, salary FROM employees ORDER BY salary DESC;
3. NULL Values:
Example:
1. Definition:
2. Usage:
Substitution variables are often prefixed with an ampersand & and can
be used in SQL statements, PL/SQL blocks, or SQL*Plus commands.
Example:
Example:
ACCEPT dept_id CHAR PROMPT 'Enter Department ID: '; SELECT employee_id,
first_name, last_name FROM employees WHERE department_id = &dept_id;
The ACCEPT statement prompts the user to enter a value for dept_id.
DEFINE Command:
1. Definition:
2. Syntax:
Example:
3. Managing Variables:
Example:
4. Displaying Variables:
To display the value of a substitution variable, you can use the DEFINE
command without assigning a new value.
DEFINE dept_id;
1. Definition:
Example:
Example:
SELECT employee_id, first_name, last_name, CASE WHEN salary > 50000 THEN
'High Salary' WHEN salary > 30000 THEN 'Medium Salary' ELSE 'Low Salary' END
AS salary_category FROM employees;
Built-in Functions:
1. Aggregate Functions:
Example:
SELECT AVG(salary) FROM employees;
2. String Functions:
Example:
3. Date Functions:
Example:
Grouping Data:
1. GROUP BY Clause:
Example:
2. HAVING Clause:
Example:
Example:
Join:
1. INNER JOIN:
Example:
A LEFT JOIN returns all rows from the left table and matching rows from
the right table.
Example:
A RIGHT JOIN returns all rows from the right table and matching rows
from the left table.
Example:
A FULL JOIN returns all rows when there is a match in either the left or
right table.
Example:
Set Operations:
1. UNION:
The UNION operator combines the result sets of two or more queries,
removing duplicates.
Example:
2. INTERSECT:
Example:
The MINUS (or EXCEPT) operator returns unique rows from the first
query but not from the second.
Example:
History
PL/SQL was first introduced by Oracle Corporation in the early 1990s as a way
to enhance the capabilities of the Oracle Database. The goal was to provide a
seamless integration of procedural constructs with SQL, enabling developers to
build more sophisticated and feature-rich applications. Over the years, PL/SQL
has evolved and matured, becoming an integral part of Oracle's database
ecosystem.
Fundamentals
2. Data Types:
Like other programming languages, PL/SQL supports various data types such as
VARCHAR2, NUMBER, DATE, BOOLEAN, etc. These data types define the kind
of data a variable can hold.
3. Control Structures:
4. Exception Handling:
Block Structure
PL/SQL code is organized into blocks, which are logical units of code that can
be as short as a single statement or as long as needed. The basic structure of a
PL/SQL block includes the following:
DECLARE
BEGIN
EXCEPTION
-- Exception handling
END;
The DECLARE section is optional and is used for declaring variables and
constants. The BEGIN and END define the executable part of the block where
the main code resides. The EXCEPTION section is also optional and is used for
handling exceptions that might occur during the execution of the block.
Comments
Comments in PL/SQL are used to provide explanatory notes within the code.
There are two types of comments:
1. Single-Line Comments:
Single-line comments are denoted by two consecutive hyphens (--). Anything
following these hyphens on the same line is considered a comment.
Example
2. Multi-Line Comments:
Multi-line comments are enclosed between /* and */. They can span multiple
lines.
Example
Comments are essential for documenting the code, making it easier for
developers to understand the purpose and functionality of different parts of
the program.
Data Types
Data types in PL/SQL define the kind of data that a variable can store. Some
common data types include:
1. VARCHAR2:
2. NUMBER:
3. DATE:
4. BOOLEAN:
Besides the basic data types, PL/SQL supports other types like:
3. TIMESTAMP:
4. TABLE:
Declaration
In PL/SQL, variables must be declared before they can be used. The basic
syntax for variable declaration is as follows:
Example:
Assignment Operation
Example:
Bind Variables
Bind variables are used in SQL and PL/SQL to pass values between different
program units. They are prefixed with a colon (:) in SQL statements.
Substitution Variables
Example:
In PL/SQL, there are several ways to display output, and one common method
is using the DBMS_OUTPUT package.
Example
Arithmetic Operators
Example
Example
Example
Example
Control Structures
IF-THEN-ELSE Statement
Example
FOR LOOP
Example
WHILE LOOP
The WHILE LOOP is used for repeated execution as long as a condition is true.
plsqlCopy code
Nested Blocks
PL/SQL allows the nesting of blocks within each other. This is useful for
organizing code and controlling the scope of variables.
Example
PL/SQL allows the embedding of SQL statements directly within the procedural
code. This is known as Embedded SQL.
Example
In this example, the SELECT statement is embedded within the PL/SQL block,
and the result is stored in the variable emp_name. This integration of SQL with
PL/SQL allows for seamless interaction with the database within the
procedural code.
Data Manipulation
1. INSERT:
Example
2. UPDATE:
Example
Example
1. COMMIT:
Example
COMMIT;
2. ROLLBACK:
Example
ROLLBACK;
3. SAVEPOINT:
Sets a point within a transaction to which you can later roll back.
Example
SAVEPOINT my_savepoint;
4. ROLLBACK TO SAVEPOINT:
Example
ROLLBACK TO my_savepoint;
PL/SQL Cursors
A cursor in PL/SQL is a pointer that is used to fetch rows from a result set.
Cursors are classified into two types: Implicit and Explicit.
Implicit Cursors
Example
Explicit cursors are declared by the programmer and offer more control,
especially for multi-row queries.
Example
Cursor Attributes:
A FOR loop can be used with an explicit cursor to iterate through the result set.
This syntax simplifies cursor handling and eliminates the need for explicit
OPEN, FETCH, and CLOSE statements.
Exceptions
DECLARE v_result NUMBER; BEGIN -- Some code that might raise an exception
v_result := 10 / 0; -- This will raise a 'DIVIDE BY ZERO' exception EXCEPTION
WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error occurred: ' ||
SQLERRM); END;
The WHEN OTHERS block catches any exception that is not explicitly handled.
SQLERRM provides a description of the error.
DECLARE
v_employee_name employees.employee_name%TYPE;
BEGIN
SELECT employee_name
INTO v_employee_name
FROM employees
FOR UPDATE;
END;
The FOR UPDATE clause ensures that the selected rows are locked exclusively
for the transaction that executed the SELECT...FOR UPDATE statement.
The WHERE CURRENT OF clause is used with cursors to update or delete the
current row being processed by a cursor. This is particularly useful when
dealing with explicit cursors.
Example
DECLARE
CURSOR employee_cursor IS
v_employee_id employees.employee_id%TYPE;
v_employee_name employees.employee_name%TYPE;
BEGIN
OPEN employee_cursor;
UPDATE employees
CLOSE employee_cursor;
Example
DECLARE
SELECT employee_name
FROM employees
v_employee_name employees.employee_name%TYPE;
BEGIN
CLOSE employee_cursor;
END;
Cursor Variables (Ref Cursors)
Cursor variables, also known as ref cursors, are pointers to result sets. They
provide a way to pass result sets between stored procedures or functions.
Example
DECLARE
emp_cursor EmpCursorType;
v_employee_name employees.employee_name%TYPE;
BEGIN
CLOSE emp_cursor;
END;
Exceptions
Exceptions in PL/SQL are used to handle errors and unexpected situations. The
EXCEPTION block is used to catch and handle specific exceptions or a generic
OTHERS exception.
Example
DECLARE
v_result NUMBER;
BEGIN
END;
Types of Exceptions
Custom exceptions can also be defined using the EXCEPTION block to handle
specific error scenarios in your application.
UNIT 5 – Pl/Sql Composite Data Types (15 Hours)
Records
A record in PL/SQL is a composite data type that allows you to group related
data items together under a single name. Each item in a record is called a field
or attribute. Records are often used to model structures or entities.
Example
DECLARE
employee_id NUMBER,
employee_name VARCHAR2(50),
salary NUMBER
);
emp_info EmployeeRecord;
BEGIN
emp_info.employee_id := 101;
emp_info.salary := 50000;
END;
Tables
Example
DECLARE
employee_id NUMBER,
employee_name VARCHAR2(50),
salary NUMBER
);
emp_info_list EmpInfoList;
BEGIN
emp_info_list := EmpInfoList(
);
-- Accessing table elements
END LOOP;
END;
Arrays
PL/SQL doesn't have a native array data type, but you can simulate arrays using
collections like VARRAYs (Variable Arrays) or nested tables.
Example
DECLARE
employee_id NUMBER,
employee_name VARCHAR2(50),
salary NUMBER
);
emp_info_array EmpInfoArray;
BEGIN
emp_info_array := EmpInfoArray(
END LOOP;
END;
Named Blocks
Named blocks in PL/SQL are modular units of code that consist of a set of
related statements. There are three main types of named blocks:
1. Procedures
Procedures are named blocks that group together a series of SQL and PL/SQL
statements to perform a specific task. They can have input and output
parameters
emp_id IN NUMBER,
) AS
salary NUMBER;
BEGIN
-- Calculate bonus
bonus := salary * 0.1;
END calculate_salary;
2. Functions
Functions are similar to procedures but return a value. They can be used in SQL
expressions and provide a way to encapsulate a computation or operation.
Example
emp_id IN NUMBER
) RETURN VARCHAR2 IS
emp_name VARCHAR2(50);
BEGIN
RETURN emp_name;
END get_employee_name;
3. Packages
Example
END payroll_package;
CREATE OR REPLACE PACKAGE BODY payroll_package AS
salary NUMBER;
BEGIN
-- Calculate bonus
END calculate_salary;
emp_name VARCHAR2(50);
BEGIN
RETURN emp_name;
END get_employee_name;
END payroll_package;
Triggers
Triggers are named blocks that are automatically executed or fired in response
to specific events on a particular table or view. They are often used to enforce
business rules or perform actions based on changes to data.
BEGIN
:NEW.created_at := SYSTIMESTAMP;
END before_employee_insert;
In this example, the trigger sets the created_at column to the current
timestamp before inserting a new employee.
Data Dictionary Views are special views in the Oracle database that provide
information about the database and its objects. They are often used for
querying metadata.
Example
SELECT table_name
FROM all_tables;
FROM all_tab_columns
Data Dictionary Views allow you to retrieve information about tables, columns,
constraints, privileges, and other database objects.
TEXT BOOKS
REFERENCE BOOKS
E – LEARNING.
1. https://academy.oracle.com
2. www.udemy.com
3. www.livesql.oracle.com
4. www.w3schools.com
5. www.simplilearn.com