Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
235 views

Rdbms & Oracle Lecture Notes

Uploaded by

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

Rdbms & Oracle Lecture Notes

Uploaded by

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

Dr. R.A.N.

M ARTS AND SCIENCE COLLEGE


(Co-Education), Rangampalayam, Erode - 638009
Affiliated to Bharathiar University
Accredited with B+ by NAAC

LECTURE HANDOUTS

B.SC – Computer Science / Information


Technology / BCA

Semester V

Core Paper 8: RDBMS & ORACLE

Total Lecture Hours - 75

Course Faculty: Yuvaraj S

Course Objectives:

The main objectives of this course are to:

1. The course describes the data, organizing the data in database, database
administration.

2. To grasp the different issues involved in the design of a database system.

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.

5. Provide strong foundation of database concepts and to introduce students


to application development in DBMS.
UNIT 1 – Database Concepts (15 Hours)

Database Concepts: A Relational approach: Database – Relationships – DBMS


– Relational Data Model – Integrity Rules – Theoretical Relational Languages.
Database Design: Data Modeling and Normalization: Data Modeling –
Dependency – Database Design – Normal forms – Dependency Diagrams –
De-normalization – Another Example of Normalization.

Database Concepts: A Relational Approach

A database is a structured collection of data organized to be easily accessed,


managed, and updated. The relational approach to databases is based on the
principles introduced by Edgar F. Codd in the 1970s. In a relational database,
data is organized into tables, where each table consists of rows and columns.
Each row represents a record, and each column represents a field or
attribute.

Database Relationships

Relationships in a relational database refer to the associations between


tables. The primary key of one table is often linked to a foreign key in another
table, establishing a connection between them. Common types of
relationships include one-to-one, one-to-many, and many-to-many. These
relationships help maintain data integrity and enable efficient data retrieval.

Introduction to Database Relationships:

In the context of relational databases, a database relationship is a connection


or association between tables that is established based on common fields.
These relationships are crucial for maintaining the integrity of the data and
organizing it in a way that supports efficient querying and retrieval.

Types of Database Relationships:

1. One-to-One (1:1) Relationship:

 In a one-to-one relationship, each record in the first table is


related to exactly one record in the second table, and vice versa.

 This type of relationship is less common and is typically used


when the data in one table is a subset of the data in another.
2. One-to-Many (1:N) Relationship:

 In a one-to-many relationship, each record in the first table can


be related to multiple records in the second table, but each
record in the second table is related to only one record in the
first table.

 This is the most common type of relationship and is often used


to represent hierarchies or categories.

3. Many-to-One (N:1) Relationship:

 The many-to-one relationship is essentially the reverse of the


one-to-many relationship. Multiple records in the first table can
be related to a single record in the second table.

 This type of relationship is less common but is still important in


certain scenarios.

4. Many-to-Many (N:N) Relationship:

 In a many-to-many relationship, multiple records in the first


table can be related to multiple records in the second table, and
vice versa.

 To implement a many-to-many relationship, an intermediary


table, known as a junction or linking table, is often introduced to
break down the relationship into two one-to-many relationships.

Components of Database Relationships:

1. Primary Key:

 The primary key is a unique identifier for each record in a table.


It is used to establish relationships with other tables.

 In a one-to-many relationship, the primary key of the "one" side


becomes the foreign key in the "many" side.

2. Foreign Key:

 A foreign key is a column in a table that refers to the primary key


in another table. It establishes a link between the two tables.
 Foreign keys are essential for maintaining referential integrity,
ensuring that relationships between tables are valid.

3. Referential Integrity:

 Referential integrity ensures that relationships between tables


are maintained and valid. It prevents the creation of orphaned
records by enforcing the use of valid foreign keys.

Importance of Database Relationships:

1. Data Integrity:

 Relationships help maintain data integrity by ensuring that


related information is accurate and consistent across tables.

2. Efficient Data Retrieval:

 Well-designed relationships facilitate efficient data retrieval


through the use of JOIN operations in queries. JOINs allow data
from multiple tables to be combined based on their
relationships.

3. Reduced Data Redundancy:

 By establishing relationships, redundant data can be minimized.


Instead of storing the same information in multiple places,
related data can be linked through foreign keys.

Examples of Database Relationships:

1. Employee and Department:

 In a company database, there may be a one-to-many relationship


between employees and departments, where each employee
belongs to one department, but each department can have
multiple employees.

2. Customer and Orders:

 In a sales database, there is typically a one-to-many relationship


between customers and orders. Each customer can place
multiple orders, but each order is placed by one customer.
3. Students and Courses:

 In an educational database, a many-to-many relationship may


exist between students and courses. Students can enroll in
multiple courses, and each course can have multiple students. A
junction table is used to represent this relationship.

Best Practices for Designing Database Relationships:

1. Identify Key Entities:

 Identify the key entities in your database and the relationships


between them. This forms the basis for designing tables and
defining relationships.

2. Use Meaningful Primary and Foreign Keys:

 Choose primary and foreign keys that have meaningful names


and reflect the nature of the data they represent.

3. Normalize Your Database:

 Normalize your database to reduce data redundancy and


dependency. This involves organizing tables and their attributes
efficiently.

4. Enforce Referential Integrity:

 Enforce referential integrity to ensure that relationships between


tables are maintained. This is typically done through the use of
foreign key constraints.

In summary, database relationships are essential for organizing and


maintaining the integrity of data in relational databases. They define the
connections between tables, enable efficient data retrieval, and contribute to
the overall structure and functionality of a well-designed database.

Database Management System (DBMS)

A Database Management System (DBMS) is software that facilitates the


creation, maintenance, and use of databases. It provides an interface for
users and applications to interact with the database. DBMS handles tasks
such as data storage, retrieval, and security. Popular examples of DBMS
include MySQL, Oracle, and Microsoft SQL Server.

Relational Data Model

The relational data model is a mathematical model for representing data in


tables. It uses the concept of relations, which are tables with rows and
columns. The model emphasizes data independence, meaning that the
database structure (tables and relationships) can be modified without
affecting the applications using the data.

Introduction to Relational Data Model:

The relational data model is a conceptual framework for organizing and


representing data in a relational database. Proposed by Edgar F. Codd in
1970, this model has become the foundation for most modern database
management systems (DBMS). The model uses a tabular structure to
represent data, where each table consists of rows and columns.

Key Components of the Relational Data Model:

1. Tables (Relations):

 In the relational data model, data is organized into tables, also


referred to as relations.

 Each table comprises rows (tuples) and columns (attributes).

 Tables are used to represent entities, and each row in a table


corresponds to a specific record or instance of that entity.

2. Attributes (Fields):

 Columns in a table are known as attributes or fields.

 Attributes represent the characteristics or properties of the


entities being modeled.

 Each attribute has a data type, defining the kind of data it can
store (e.g., integer, string, date).

3. Tuples (Rows):

 Rows in a table are called tuples.


 A tuple represents a specific instance or record of the entity
modeled by the table.

 Tuples are composed of values, with each value corresponding to


an attribute.

4. Primary Key:

 A primary key is a unique identifier for each tuple in a table.

 It ensures the uniqueness of each record and serves as a


reference point for establishing relationships with other tables.

 The primary key can be a single attribute or a combination of


attributes.

5. Foreign Key:

 A foreign key is a column or set of columns in a table that refers


to the primary key in another table.

 It establishes relationships between tables, creating links and


enabling data consistency.

Advantages of the Relational Data Model:

1. Simplicity and Intuitiveness:

 The tabular structure of the relational model is easy to


understand and intuitive, making it user-friendly for both
designers and end-users.

2. Data Independence:

 The model promotes data independence, allowing changes to be


made to the database structure without affecting the
applications that use the data.

3. Query Flexibility:

 SQL (Structured Query Language) is the standard language for


interacting with relational databases, providing a powerful and
flexible means for querying and manipulating data.
4. Normalization:

 The relational model supports normalization, a process that


minimizes data redundancy and dependency, leading to efficient
storage and maintenance of data.

Limitations of the Relational Data Model:

1. Complexity for Certain Relationships:

 Representing certain types of relationships, especially many-to-


many relationships, can be complex in the relational model.

2. Performance Implications:

 Join operations, which are fundamental to relational databases,


can have performance implications as the size of the database
grows.

3. Not Ideal for Hierarchical Data:

 The relational model is not well-suited for representing


hierarchical data structures, such as organizational charts.

Extended Concepts:

1. Database Normalization:

 Database normalization is a process in the relational model that


minimizes redundancy and dependency by organizing tables and
their attributes efficiently.

2. ACID Properties:

 The relational model adheres to the ACID properties (Atomicity,


Consistency, Isolation, Durability), ensuring the reliability and
integrity of transactions.

3. Structured Query Language (SQL):

 SQL is the standard language for interacting with relational


databases. It includes commands for creating tables, querying
data, and modifying database structures.
Integrity Rules

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

Entity integrity is a fundamental integrity rule that ensures the uniqueness of


each row (record) within a table. In practical terms, it means that every table
in a relational database must have a primary key, a column (or set of
columns) that uniquely identifies each record. This primary key constraint
ensures that there are no duplicate records in the table, preventing data
redundancy and maintaining the integrity of individual records.

Referential Integrity

Referential integrity is concerned with maintaining the relationships between


tables. In a relational database, tables are often related through foreign key
constraints. A foreign key is a column or set of columns in one table that
refers to the primary key of another table. Referential integrity ensures that
relationships between tables are valid, meaning that foreign key values
correspond to existing primary key values in the referenced table. This
prevents the creation of "orphaned" records and helps maintain data
consistency across related tables.

Domain Integrity

Domain integrity focuses on the allowable values within a database. It


ensures that data values for each attribute (column) fall within defined
domains or ranges. This can include data type constraints (e.g., ensuring a
numeric field only contains numerical values) and check constraints (e.g.,
ensuring a date falls within a specific range). Domain integrity helps prevent
the insertion of invalid or inappropriate data into the database, contributing
to data accuracy.

Check Constraints

Check constraints are a specific implementation of domain integrity rules.


They allow the definition of conditions that must be satisfied for data to be
inserted or updated in a table. For example, a check constraint might ensure
that the values in a "quantity" column are always greater than zero. By
enforcing such conditions, check constraints contribute to the overall
integrity of the database.

Integrity Constraints in Database Management Systems

Database Management Systems (DBMS) enforce integrity rules through the


use of constraints. Constraints are rules or conditions applied to columns or
tables that restrict the type of data that can be stored. DBMS automatically
checks and enforces these constraints during data modifications (inserts,
updates, deletes) to ensure that the data remains consistent and accurate.

Cascading Actions

In the context of referential integrity, cascading actions define the behavior of


the database when a referenced (parent) record is modified or deleted. For
example, a cascading delete action might specify that if a record in the parent
table is deleted, all associated records in the child table should also be
deleted. These actions help maintain the consistency of data relationships.

Theoretical Relational Languages

Theoretical relational languages include SQL (Structured Query Language),


which is widely used for interacting with relational databases. SQL provides a
standardized way to define, query, and manipulate data in a relational
database. It includes commands for tasks such as creating tables, inserting
data, updating records, and retrieving information through queries.

Theoretical relational languages are formal languages that provide a


foundation for interacting with relational databases based on the principles of
the relational data model. These languages are not necessarily the practical
languages used in database systems like SQL, but rather theoretical
constructs that help define the concepts and operations associated with the
relational model. Here's an elaboration on the theoretical relational
languages:

1. Relational Algebra:

Relational algebra is a theoretical language that describes a set of operations


to manipulate relations (tables) in the relational data model. The
fundamental operations in relational algebra are:

 Selection (σ): It selects rows from a relation that satisfy a given


condition.

 Projection (π): It selects specific columns from a relation, discarding


the rest.

 Union (∪): It combines two relations to produce a new relation


containing all unique rows.

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

 Renaming (ρ): It is used to rename the attributes of a relation.

Relational algebra serves as the foundation for query languages and


optimization strategies in relational databases.

2. Relational Calculus:

Relational calculus is another theoretical language for relational databases. It


expresses queries in the form of logical formulas rather than as a sequence of
operations like relational algebra. There are two main types of relational
calculus:

 Tuple Relational Calculus (TRC): Specifies the desired result by


describing a set of tuples. It uses variables and quantifiers to define
conditions on tuples.

 Domain Relational Calculus (DRC): Specifies the desired result by


defining conditions on the attributes (domains) rather than tuples. It
also uses variables and quantifiers.

Relational calculus is more declarative than relational algebra, meaning that it


describes what data is needed rather than how to obtain it. SQL, the practical
language used in relational databases, is closer in syntax to relational calculus.
3. The Fourth Normal Form (4NF) and Domain-Key Normal Form (DKNF):

While not traditional languages, the concepts of 4NF and DKNF are important
for understanding the theoretical aspects of relational databases.

 Fourth Normal Form (4NF): It addresses certain types of redundancy


that can occur when dealing with multivalued dependencies. A relation
is in 4NF if it is in Boyce-Codd Normal Form (BCNF) and has no
nontrivial multivalued dependencies.

 Domain-Key Normal Form (DKNF): It ensures that every constraint on


the relation is a logical consequence of the definition of keys and
domains. A relation in DKNF is free from redundancy and has a clear,
concise structure.

Conclusion:

Theoretical relational languages provide a formal foundation for


understanding and reasoning about relational databases. While these
languages may not be directly used in practical database interactions, they
play a crucial role in the design, optimization, and theoretical underpinnings
of relational database systems. Practical languages like SQL have been
influenced by these theoretical constructs, making it easier to bridge the gap
between theoretical concepts and real-world database management.
UNIT 2 – Oracle 9i (15 Hours)

Oracle9i: Overview: Personal Databases – Client/Server Databases – Oracle9i


an introduction – SQL *Plus Environment – SQL – Logging into SQL *Plus - SQL
*Plus Commands – Errors &Help – Alternate Text Editors - SQL *Plus
Worksheet - iSQL *Plus. Oracle Tables: DDL: Naming Rules and conventions –
Data Types – Constraints – Creating Oracle Table – Displaying Table
Information–Altering an Existing Table– Dropping, Renaming, Truncating
Table–Table Types –Spooling – Error codes.

Oracle9i Overview:

1. Introduction to Oracle9i:

 Oracle Corporation: Oracle9i is a relational database management


system (RDBMS) developed by Oracle Corporation. The "i" in Oracle9i
stands for "Internet," indicating a strong focus on internet computing
and integration.

 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:

 Internet Integration: Oracle9i was designed to seamlessly


integrate with internet technologies, allowing for easy
development and deployment of web-based applications.

 Real Application Clusters (RAC): Introduced the concept of Real


Application Clusters for improved scalability and high availability.

 XML Support: Enhanced support for XML (eXtensible Markup


Language) to accommodate the growing importance of XML in
data exchange.

2. Architecture of Oracle9i:

 Instance and Database: Oracle9i follows a client/server architecture. An


Oracle database consists of one or more instances, where each instance
represents the set of memory structures and background processes
managing a database.

 Background Processes: Various background processes handle tasks such


as managing locks, writing to the redo log, and maintaining data
consistency.

 Shared Memory: Oracle9i utilizes shared memory areas for efficient


communication between processes. The System Global Area (SGA) is a
key shared memory component that stores data and control information
shared among database users.

 Database Files: Data files, control files, and redo log files constitute the
physical storage components of an Oracle database.

Personal Databases:

1. Definition:

 A personal database, in the context of Oracle9i, typically refers to a


database designed for use by an individual or a small group of users. It is
often used for applications where the database requirements are
relatively modest.

2. Characteristics:

 Single User or Small Group: Personal databases are generally used by a


single user or a small group of users, and they may be stored on a local
machine or a network.

 Ease of Use: These databases are designed to be user-friendly and easy


to set up. They might not have the complexity of large-scale enterprise
databases.

 Limited Scalability: Personal databases may have limited scalability


compared to enterprise-level databases. They are suitable for
applications with lower data volume and user concurrency.

3. Use Cases:

 Personal databases are often employed in scenarios such as desktop


applications, small business tools, educational projects, and other
situations where the database requirements are modest and don't
necessitate the features and scalability of larger systems.

Client/Server Databases:

1. Definition:

 A client/server database architecture involves the separation of the user


interface (client) from the database management system (server). The
client and server communicate over a network, allowing for distributed
computing.

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:

 Scalability: Client/server databases are scalable, allowing multiple


clients to connect to a central server. This makes them suitable for
applications with a large number of users.

 Centralized Control: The server centralizes control over data, ensuring


data consistency and integrity. Changes to the database structure or
security can be managed more effectively.

 Improved Performance: Client/server architecture often leads to better


performance as the server can be optimized for data processing tasks,
and clients can focus on presenting information to users.

4. Oracle9i and Client/Server Model:

 Oracle9i is designed with a client/server architecture. The Oracle


database server manages data storage and processing, while client
applications (web applications, desktop applications, etc.) connect to the
server to interact with the data.
 Oracle Net Services facilitates communication between clients and
servers, supporting various network configurations.

SQL*Plus Environment:

1. Definition:

 SQL*Plus is an interactive command-line tool provided by Oracle for


interacting with Oracle databases. It is widely used by database
administrators, developers, and users to execute SQL commands, scripts,
and manage the Oracle database.

2. Key Features:

 Command-Line Interface: SQL*Plus provides a command-line interface


for executing SQL commands and scripts.

 Scripting and Automation: Users can create and execute SQL scripts to
perform multiple tasks, automating database operations.

 Report Generation: SQL*Plus can be used to generate reports based on


SQL queries and commands.

 Data Manipulation: It supports data manipulation operations, allowing


users to insert, update, and delete data.

SQL - Logging into SQL*Plus:

1. Connection Process:

 To log into SQL*Plus, users need the following information: Oracle


database username, password, and the Oracle Net Service name or
database connection string.

 The basic syntax for logging in is:

sqlplus username/password@tnsname
2. Example:

 If the username is "myuser," the password is "mypassword," and the


Oracle Net Service name is "mydb," the login command would be:

 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:

 SELECT: Used to retrieve data from one or more tables.

 INSERT: Adds new records to a table.

 UPDATE: Modifies existing records in a table.

 DELETE: Removes records from a table.

2. SQL*Plus-Specific Commands:

 DESCRIBE (DESC): Shows the structure of a table.

 SPOOL: Captures query results to a file.

 SET: Configures various SQL*Plus settings, such as formatting options


and display preferences.

 @ (at symbol): Runs a script.

 / (slash): Executes the last SQL command.

Errors & Help:

1. Error Handling:

 SQL*Plus provides error messages to indicate issues with SQL commands


or database operations.
 Common error types include syntax errors, runtime errors, and
database-related errors (e.g., constraint violations).

 Error messages provide details about the nature of the error, aiding in
troubleshooting.

2. Help Commands:

 HELP: Displays a list of SQL*Plus commands or provides help on a


specific command.

 ? (question mark): Used to get help on SQL*Plus commands.

Alternate Text Editors:

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.

2. Configuring Alternate Editors:

 SQL*Plus allows users to set an alternate editor using the EDIT


command. For example:

 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:

 SQLPlus Worksheet is a component of Oracle SQL Developer, which is a


graphical tool for database development. SQLPlus Worksheet provides a
user-friendly interface for executing SQL and PL/SQL commands and
scripts.

 2. Key Features:

 Graphical Interface: Unlike the traditional command-line interface of


SQLPlus, SQLPlus Worksheet provides a graphical interface, making it
more accessible for users who prefer visual tools.

 Syntax Highlighting: The SQL*Plus Worksheet often includes syntax


highlighting, which helps users identify and correct syntax errors more
easily.

 Script Execution: Users can execute SQL scripts and PL/SQL blocks
directly from the worksheet.

 Query Results: The results of SQL queries are displayed in a tabular


format within the worksheet, allowing for easy data inspection.

 History and Recall: SQL*Plus Worksheet keeps a history of executed


commands, and users can recall and re-run previous commands easily.

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

 SQL*Plus Worksheet is particularly useful for developers and


administrators who prefer a more visual and interactive environment for
working with databases.

 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:

 Web-Based Interface: iSQL*Plus operates through a web browser,


eliminating the need for a client-side installation. Users access it by
navigating to a specific URL.

 User Authentication: Users log in to iSQL*Plus using their Oracle


database credentials, and the tool provides a secure connection to the
database.

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

 Basic Reporting: iSQL*Plus provides basic reporting capabilities, allowing


users to view and export query results.

 3. Usage:

 Users access iSQL*Plus by entering the appropriate URL in a web


browser.

 Once logged in, users can execute SQL commands, scripts, and perform
various database tasks through the web-based interface.

 iSQL*Plus is particularly useful in scenarios where a lightweight, web-


based tool is preferred, or where users need to interact with databases
without installing client software.

 Key Differences Between SQL Plus Worksheet and iSQL Plus:

 Interface:

 SQL*Plus Worksheet is a component within Oracle SQL Developer,


offering a graphical interface.
 iSQL*Plus is a standalone web-based tool, accessible through a web
browser.

 Access:

 SQL*Plus Worksheet is part of the Oracle SQL Developer client and


needs to be installed on the user's machine.

 iSQL*Plus is accessed through a web browser, eliminating the need for a


client-side installation.

 Environment:

 SQL*Plus Worksheet is designed for users who prefer a graphical tool


within the SQL Developer environment.

 iSQL*Plus is designed for users who prefer a web-based tool with a


simplified interface.

 Usage Scenario:

 SQL*Plus Worksheet is suitable for developers and administrators who


are already using Oracle SQL Developer for other development tasks.

 iSQL*Plus is suitable for scenarios where users want a lightweight, web-


based tool without the need for a dedicated client installation.

Oracle Tables: DDL (Data Definition Language)

Naming Rules and Conventions:

**1. Table Name Rules:

 Table names in Oracle must begin with a letter and can be up to 30


characters long.

 Special characters such as $, _, and # are allowed within the name, but
the table name should not begin with a number or contain spaces.

2. Column Name Rules:

 Column names follow similar rules as table names.


 They must begin with a letter and can be up to 30 characters long.

 Special characters and underscores are allowed, and they should not
begin with a number.

3. Case Sensitivity:

 In Oracle, table and column names are case-insensitive by default.

 However, it's a common convention to use uppercase for SQL keywords


and lowercase for user-defined identifiers.

4. Reserved Words:

 Avoid using Oracle reserved words as table or column names to prevent


conflicts and improve code readability.

Data Types:

1. Common Data Types:

 NUMBER: Represents numeric values and can include precision and


scale.

 VARCHAR2: Variable-length character strings.

 DATE: Stores date and time information.

 CHAR: Fixed-length character strings.

 CLOB/BLOB: Large object types for handling character and binary data.

2. Precision and Scale:

 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:

salary NUMBER(8, 2);

3. Date Format:

 The DATE data type stores date and time values.


 It can be formatted using the TO_DATE function or displayed in a specific
format using the TO_CHAR function.

 Example:

hire_date DATE;

4. LOB Data Types:

 Large Object (LOB) types such as CLOB and BLOB are used to store large
amounts of character or binary data.

 Example:

resume CLOB;

Constraints:

1. Primary Key Constraint:

 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:

CREATE TABLE employees ( employee_id NUMBER PRIMARY KEY, first_name


VARCHAR2(50), last_name VARCHAR2(50) );

2. Foreign Key Constraint:

 Establishes a link between two tables, enforcing referential integrity.

 The foreign key column in one table refers to the primary key column in
another.

 Example:

CREATE TABLE orders ( order_id NUMBER PRIMARY KEY, product_id NUMBER,


CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES
products(product_id) );
3. Unique Constraint:

 Ensures that all values in a column (or set of columns) are unique.

 Provides an alternative to the primary key constraint when uniqueness is


required without being a primary key.

 Example:

CREATE TABLE departments ( department_id NUMBER UNIQUE,


department_name VARCHAR2(50) );

4. Check Constraint:

 Imposes a condition on the values entered into a column.

 Ensures that data adheres to specific criteria.

 Example:

CREATE TABLE employees ( employee_id NUMBER PRIMARY KEY, salary


NUMBER CHECK (salary > 0) );

5. NOT NULL Constraint:

 Ensures that a column cannot contain NULL values.

 Enforces the presence of data in a specific column.

 Example:

CREATE TABLE customers ( customer_id NUMBER PRIMARY KEY,


customer_name VARCHAR2(100) NOT NULL );

Creating Oracle Table:

1. Syntax for Creating a Table:

 The CREATE TABLE statement is used to create a table in Oracle.

 Example:

CREATE TABLE employees ( employee_id NUMBER PRIMARY KEY, first_name


VARCHAR2(50), last_name VARCHAR2(50), hire_date DATE, salary NUMBER );
 This example creates an "employees" table with columns for employee
information, including an employee_id as the primary key.

2. Constraints and Indexes:

 The CREATE TABLE statement allows for the inclusion of constraints such
as primary key, foreign key, unique, check, etc., to define data integrity
rules.

 Indexes can be added to columns for improved query performance.

 Example with constraints:

CREATE TABLE products ( product_id NUMBER PRIMARY KEY, product_name


VARCHAR2(100) UNIQUE, price NUMBER CHECK (price > 0) );

Displaying Table Information:

1. Describing a Table:

 The DESCRIBE or DESC command can be used to display the structure of


a table, showing the column names, data types, and constraints.

 Example:

DESCRIBE employees;

 This command provides information about the "employees" table.

2. Querying Data Dictionary Views:

 Data dictionary views like ALL_TABLES, ALL_TAB_COLUMNS, and


ALL_TAB_COMMENTS provide detailed information about tables,
columns, and comments.

 Example:

SELECT * FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = 'EMPLOYEES';

 This query retrieves information about columns in the "employees"


table.

Altering an Existing Table:


1. Adding a Column:

 The ALTER TABLE statement is used to add a new column to an existing


table.

 Example:

ALTER TABLE employees ADD (phone_number VARCHAR2(20));

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:

ALTER TABLE employees MODIFY (phone_number VARCHAR2(15));

3. Dropping, Renaming, Truncating Table:

 The DROP TABLE statement is used to remove an entire table and its
data.

 Example:

DROP TABLE employees;

 The RENAME statement is used to rename an existing table.

 Example:

RENAME employees TO staff;

 The TRUNCATE TABLE statement removes all rows from a table but
retains the structure for future use.

 Example:

TRUNCATE TABLE employees;

Table Types:

1. Heap-Organized Tables:

 Default type of table where data is stored in an unsorted heap.

2. Index-Organized Tables (IOT):


 Data is stored in a B-tree index structure for faster retrieval.

 Example:

CREATE TABLE products_iot ( product_id NUMBER PRIMARY KEY,


product_name VARCHAR2(100) ) ORGANIZATION INDEX;

3. Temporary Tables:

 Created for temporary storage, often used in complex queries or large


data operations.

 Example:

CREATE GLOBAL TEMPORARY TABLE temp_employees ( employee_id


NUMBER, first_name VARCHAR2(50) ) ON COMMIT DELETE ROWS;

Spooling:

1. Spooling in SQL*Plus:

 Spooling is the process of saving the output of SQL*Plus commands to a


file.

 Example:

SPOOL output.txt SELECT * FROM employees; SPOOL OFF

 This example spools the result of the query to a file named "output.txt."

Error Codes:

1. Oracle SQL Error Codes:

 Oracle SQL errors are identified by error codes that provide information
about the nature of the error.

 Example:

sqlCopy code

SELECT * FROM non_existent_table;

 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:

 PL/SQL, Oracle's procedural language, allows for exception handling


using EXCEPTION blocks to gracefully manage errors.

 Example:

BEGIN -- SQL statements here EXCEPTION WHEN OTHERS THEN -- Handle the
exception END;

 This block catches any exceptions that occur during execution.


UNIT 3 – Working with table (15 Hours)

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.

Data Management and Retrieval Using DML:

Adding a New Row/Record:

1. INSERT Statement:

 The INSERT statement is used to add new rows or records to a table.

 Example:

INSERT INTO employees (employee_id, first_name, last_name, hire_date,


salary) VALUES (1, 'John', 'Doe', TO_DATE('2022-01-01', 'YYYY-MM-DD'),
50000);

 This example inserts a new employee record into the "employees" table.

2. Using DEFAULT Keyword:

 When certain columns have default values, you can omit them from the
INSERT statement.

 Example:

INSERT INTO products (product_id, product_name) VALUES (1, 'Widget');

 This assumes that other columns, such as the price, have default values
defined.

Customized Prompts:
1. User Input with PROMPT:

 In SQL*Plus or other SQL interfaces, the PROMPT command can be used


to display customized prompts for user input.

 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:

 SQL*Plus allows the use of substitution variables for more dynamic


prompts.

 Example:

DEFINE employee_id = '&1'; DEFINE first_name = '&2';

 These variables can then be used in subsequent SQL statements.

Updating and Deleting an Existing Row/Record:

1. UPDATE Statement:

 The UPDATE statement is used to modify existing data in a table.

 Example:

UPDATE employees SET salary = salary * 1.1 WHERE department_id = 10;

 This example increases the salary of employees in department 10 by


10%.

2. DELETE Statement:

 The DELETE statement is used to remove rows from a table.

 Example:

DELETE FROM products WHERE stock_quantity < 10;

 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:

TRUNCATE TABLE employees;

 This is a more efficient alternative to deleting all rows.

Transaction Control:

1. COMMIT:

 The COMMIT statement is used to make changes made during a


transaction permanent.

 Example:

COMMIT;

 After executing this statement, the changes are saved to the database.

2. ROLLBACK:

 The ROLLBACK statement is used to undo changes made during a


transaction.

 Example:

ROLLBACK;

 This statement can be used to revert to the state of the database before
the transaction began.

Retrieving Data from a Table:

1. SELECT Statement:

 The SELECT statement is used to retrieve data from one or more tables
in a database.

 Example:
SELECT * FROM employees;

 This retrieves all columns from the "employees" table.

2. Column Selection:

 You can specify which columns to retrieve in the SELECT statement.

 Example:

SELECT employee_id, first_name, last_name FROM employees;

 This retrieves only the specified columns from the "employees" table.

3. DISTINCT Keyword:

 The DISTINCT keyword is used to retrieve unique values.

 Example:

SELECT DISTINCT department_id FROM employees;

 This retrieves unique department IDs from the "employees" table.

Arithmetic Operations:

1. Basic Arithmetic:

 Arithmetic operations can be performed in the SELECT statement.

 Example:

SELECT salary, salary * 1.1 AS increased_salary FROM employees;

 This calculates a 10% increase in salary for each employee.

2. Aggregate Functions:

 Aggregate functions like SUM, AVG, MIN, and MAX perform calculations
on sets of rows.

 Example:

SELECT AVG(salary) FROM employees WHERE department_id = 10;


 This calculates the average salary for employees in department 10.

Restricting Data with WHERE Clause:

1. WHERE Clause:

 The WHERE clause is used to filter rows based on specified conditions.

 Example:

SELECT * FROM employees WHERE department_id = 20;

 This retrieves employees only from department 20.

2. Logical Operators:

 Logical operators such as AND, OR, and NOT can be used to combine
conditions in the WHERE clause.

 Example:

SELECT * FROM employees WHERE department_id = 20 AND salary > 50000;

 This retrieves employees from department 20 with a salary greater than


50000.

Sorting:

1. ORDER BY Clause:

 The ORDER BY clause is used to sort the result set based on one or more
columns.

 Example:

SELECT employee_id, first_name, last_name FROM employees ORDER BY


last_name, first_name;

 This retrieves employees and sorts them by last name and then first
name.

2. Sorting Direction:

 Sorting can be done in ascending (ASC) or descending (DESC) order.

 Example:
SELECT employee_id, salary FROM employees ORDER BY salary DESC;

 This retrieves employees sorted by salary in descending order.

3. NULL Values:

 Handling NULL values in sorting can be specified using NULLS FIRST or


NULLS LAST.

 Example:

SELECT employee_id, commission_pct FROM employees ORDER BY


commission_pct NULLS LAST;

 This retrieves employees and sorts them by commission percentage,


with NULL values appearing last.

Revisiting Substitution Variables:

1. Definition:

 Substitution variables in Oracle SQL*Plus are placeholders that allow you


to reuse values throughout a script or session.

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:

SELECT employee_id, first_name, last_name FROM employees WHERE


department_id = &dept_id;

 In this example, &dept_id is a substitution variable that prompts the


user to enter a department ID.

3. Prompting for Values:

 Substitution variables can prompt users for values at runtime, enhancing


script interactivity.

 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:

 The DEFINE command in SQL*Plus is used to create and manage


substitution variables explicitly.

2. Syntax:

 The basic syntax for defining a variable is:

DEFINE variable_name = value;

 Example:

DEFINE dept_id = 20;

 This sets the value of dept_id to 20.

3. Managing Variables:

 DEFINE allows for the creation, modification, and removal of


substitution variables.

 Example:

DEFINE dept_id = 30;

 This changes the value of dept_id to 30.

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;

 This displays the current value of dept_id.


CASE Structure:

1. Definition:

 The CASE structure in SQL is used to perform conditional logic within a


query.

2. Simple CASE Expression:

 A simple CASE expression compares an expression to a set of possible


values and returns a result.

 Example:

SELECT employee_id, first_name, last_name, CASE department_id WHEN 10


THEN 'HR' WHEN 20 THEN 'IT' WHEN 30 THEN 'Sales' ELSE 'Other' END AS
department_name FROM employees;

 This example assigns department names based on the department ID.

3. Searched CASE Expression:

 A searched CASE expression checks multiple conditions and returns a


result for the first true condition.

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

 This example categorizes employees based on their salary.

Functions and Grouping:

Built-in Functions:

1. Aggregate Functions:

 Aggregate functions operate on sets of rows and return a single value.

 Common aggregate functions include COUNT, SUM, AVG, MIN, and


MAX.

 Example:
SELECT AVG(salary) FROM employees;

2. String Functions:

 String functions manipulate character data.

 Examples include CONCAT, SUBSTR, UPPER, LOWER, and LENGTH.

 Example:

SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;

3. Date Functions:

 Date functions handle date and time data.

 Examples include SYSDATE, TO_DATE, MONTHS_BETWEEN, and


ADD_MONTHS.

 Example:

SELECT hire_date, SYSDATE - hire_date AS years_of_service FROM employees;

Grouping Data:

1. GROUP BY Clause:

 The GROUP BY clause is used to group rows based on one or more


columns.

 Example:

SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY


department_id;

2. HAVING Clause:

 The HAVING clause filters grouped results based on aggregate


conditions.

 Example:

SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY


department_id HAVING AVG(salary) > 50000;
3. GROUPING SETS:

 The GROUPING SETS clause allows grouping by multiple sets of columns.

 Example:

SELECT department_id, job_id, AVG(salary) AS avg_salary FROM employees


GROUP BY GROUPING SETS ((department_id), (job_id));

Multiple Tables: Joins and Set Operations:

Join:

1. INNER JOIN:

 An INNER JOIN returns rows where there is a match in both tables.

 Example:

SELECT employees.employee_id, employees.first_name,


departments.department_name FROM employees INNER JOIN departments
ON employees.department_id = departments.department_id;

2. LEFT (OUTER) JOIN:

 A LEFT JOIN returns all rows from the left table and matching rows from
the right table.

 Example:

SELECT employees.employee_id, employees.first_name,


departments.department_name FROM employees LEFT JOIN departments ON
employees.department_id = departments.department_id;

3. RIGHT (OUTER) JOIN:

 A RIGHT JOIN returns all rows from the right table and matching rows
from the left table.

 Example:

SELECT employees.employee_id, employees.first_name,


departments.department_name FROM employees RIGHT JOIN departments
ON employees.department_id = departments.department_id;
4. FULL (OUTER) JOIN:

 A FULL JOIN returns all rows when there is a match in either the left or
right table.

 Example:

SELECT employees.employee_id, employees.first_name,


departments.department_name FROM employees FULL JOIN departments ON
employees.department_id = departments.department_id;

Set Operations:

1. UNION:

 The UNION operator combines the result sets of two or more queries,
removing duplicates.

 Example:

SELECT employee_id, first_name FROM employees UNION SELECT


employee_id, last_name FROM employees;

2. INTERSECT:

 The INTERSECT operator returns common rows between two or more


queries.

 Example:

SELECT employee_id, first_name FROM employees INTERSECT SELECT


employee_id, last_name FROM employees;

3. MINUS (EXCEPT in some databases):

 The MINUS (or EXCEPT) operator returns unique rows from the first
query but not from the second.

 Example:

SELECT employee_id, first_name FROM employees MINUS SELECT


employee_id, last_name FROM employees;
UNIT 4 – Pl/Sql (15 Hours)

PL/SQL: A Programming Language: History – Fundamentals – Block Structure –


Comments – DataTypes–OtherDataTypes–Declaration–Assignmentoperation–
Bindvariables–Substitution Variables – Printing – Arithmetic Operators. Control
Structures and Embedded SQL: Control Structures–NestedBlocks–
SQLinPL/SQL–DataManipulation–TransactionControl statements. PL/SQL
Cursors and Exceptions: Cursors – Implicit & Explicit Cursors and Attributes –
Cursor FOR loops – SELECT…FOR UPDATE – WHERE CURRENT OF clause –
Cursor with Parameters –Cursor Variables – Exceptions – Types of Exceptions.

PL/SQL: A Programming Language

PL/SQL, which stands for Procedural Language/Structured Query Language, is a


programming language developed by Oracle Corporation. It is an extension of
SQL (Structured Query Language) that adds procedural features, allowing for
the creation of robust and efficient database applications. PL/SQL combines
the power of SQL with the flexibility of a procedural language, making it a
powerful tool for developing database-centric applications.

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

1. Variables and Constants:

PL/SQL allows the declaration of variables and constants, providing a way to


store and manipulate data within the program.

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:

PL/SQL includes standard control structures like IF-THEN-ELSE, FOR LOOP,


WHILE LOOP, and CASE statements. These structures help in controlling the
flow of program execution.

4. Exception Handling:

Exception handling is a crucial aspect of PL/SQL. It allows developers to handle


errors and exceptions gracefully, ensuring the stability of the application.

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

-- Declaration of variables and constants

BEGIN

-- PL/SQL executable statements

EXCEPTION

-- Exception handling

END;

DECLARE -- Declaration of variables and constants BEGIN -- PL/SQL executable


statements 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

-- This is a single-line comment

2. Multi-Line Comments:

Multi-line comments are enclosed between /* and */. They can span multiple
lines.

Example

/* This is a multi-line comment */

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:

 Variable-length character strings.

 Example: DECLARE name VARCHAR2(50);

2. NUMBER:

 Numeric data type for integers and floating-point numbers.

 Example: DECLARE age NUMBER(3);

3. DATE:

 Represents date and time information.

 Example: DECLARE birth_date DATE;

4. BOOLEAN:

 Represents binary states (TRUE or FALSE).


 Example: DECLARE is_valid BOOLEAN := TRUE;

Other Data Types

Besides the basic data types, PL/SQL supports other types like:

1. CLOB (Character Large Object):

 For storing large amounts of character data.

 Example: DECLARE description CLOB;

2. BLOB (Binary Large Object):

 For storing binary data like images or documents.

 Example: DECLARE image BLOB;

3. TIMESTAMP:

 Represents date and time with fractional seconds.

 Example: DECLARE last_updated TIMESTAMP;

4. TABLE:

 Represents an entire row of a database table.

 Example: DECLARE emp_record emp_table%ROWTYPE;

Declaration

In PL/SQL, variables must be declared before they can be used. The basic
syntax for variable declaration is as follows:

DECLARE variable_name datatype [:= initial_value]; BEGIN -- PL/SQL executable


statements END;

Example:

DECLARE name VARCHAR2(50) := 'John'; age NUMBER(3); BEGIN age := 30; --


Rest of the PL/SQL code END;

Assignment Operation

Assigning values to variables is a fundamental operation in PL/SQL. The


assignment operator := is used for this purpose.
variable_name := value;

Example:

name := 'Alice'; age := 25;

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.

Example in a PL/SQL block:

DECLARE emp_id NUMBER := 101; BEGIN SELECT employee_name INTO


:emp_name FROM employees WHERE employee_id = emp_id; END;

In this example, :emp_name is a bind variable.

Substitution Variables

Substitution variables are used in SQLPlus, a command-line tool for Oracle


databases, to accept user input or store values for later use. They are preceded
by an ampersand (&) in SQLPlus.

Example:

ACCEPT department_id NUMBER PROMPT 'Enter Department ID: '; SELECT *


FROM employees WHERE department_id = &department_id;

In this example, &department_id is a substitution variable that prompts the


user to enter a value.

Understanding data types, declaration, assignment, bind variables, and


substitution variables is essential for effective PL/SQL programming, as they
form the foundation for handling and manipulating data within the Oracle
database environment.
Printing

In PL/SQL, there are several ways to display output, and one common method
is using the DBMS_OUTPUT package.

Example

DECLARE message VARCHAR2(50) := 'Hello, World!'; BEGIN


DBMS_OUTPUT.PUT_LINE(message); END;

The DBMS_OUTPUT.PUT_LINE procedure is used to print a line of text to the


console. This is particularly useful for debugging and displaying intermediate
results during the development of PL/SQL programs.

Arithmetic Operators

PL/SQL supports standard arithmetic operators for performing mathematical


operations:

1. Addition (+): Adds two numbers.

Example

total := num1 + num2;

2. Subtraction (-): Subtracts the second number from the first.

Example

difference := num1 - num2;

3. Multiplication (*): Multiplies two numbers.

Example

product := num1 * num2;

4. Division (/): Divides the first number by the second.

Example

quotient := num1 / num2;

5. Modulus (%): Returns the remainder of the division.


Example

remainder := num1 % num2;

Control Structures

IF-THEN-ELSE Statement

The IF-THEN-ELSE statement is used for conditional execution.

Example

IF condition THEN -- code to execute if condition is true ELSE -- code to execute


if condition is false END IF;

FOR LOOP

The FOR LOOP is used for iterating a specific number of times.

Example

FOR i IN 1..10 LOOP -- code to be repeated END LOOP;

WHILE LOOP

The WHILE LOOP is used for repeated execution as long as a condition is true.

plsqlCopy code

WHILE condition LOOP -- code to be repeated END LOOP;

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

DECLARE outer_variable NUMBER := 10; BEGIN -- Outer block DECLARE


inner_variable NUMBER := 5; BEGIN -- Inner block -- Both outer_variable and
inner_variable are accessible here END; -- Only outer_variable is accessible
here END;
Embedded SQL in PL/SQL

PL/SQL allows the embedding of SQL statements directly within the procedural
code. This is known as Embedded SQL.

Example

DECLARE emp_name VARCHAR2(50); BEGIN SELECT employee_name INTO


emp_name FROM employees WHERE employee_id = 101; -- Process
emp_name as needed END;

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.

Understanding printing, arithmetic operators, control structures, nested


blocks, and embedded SQL in PL/SQL provides a solid foundation for building
complex and efficient database applications. These concepts are essential for
effective programming in the Oracle database environment.

Data Manipulation

Data manipulation in PL/SQL involves operations on data stored in the


database. The primary Data Manipulation Language (DML) statements are:

1. INSERT:

 Adds new rows to a table.

Example

INSERT INTO employees (employee_id, employee_name) VALUES (101, 'John


Doe');

2. UPDATE:

 Modifies existing data in a table.

Example

UPDATE employees SET salary = 50000 WHERE employee_id = 101;


3. DELETE:

 Removes rows from a table.

Example

DELETE FROM employees WHERE employee_id = 101;

Transaction Control Statements

Transaction control statements in PL/SQL are used to manage the changes


made to the database and ensure data consistency. The primary transaction
control statements are:

1. COMMIT:

 Saves all changes made during the current transaction.

Example

COMMIT;

2. ROLLBACK:

 Undoes changes made during the current transaction.

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:

 Rolls back to a specific 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

Implicit cursors are automatically created by Oracle to process SQL statements


in PL/SQL blocks. They are used for single-row queries.

Example

DECLARE v_employee_name employees.employee_name%TYPE; BEGIN


SELECT employee_name INTO v_employee_name FROM employees WHERE
employee_id = 101; -- Process v_employee_name as needed END;

Explicit Cursors and Attributes

Explicit cursors are declared by the programmer and offer more control,
especially for multi-row queries.

Example

DECLARE CURSOR employee_cursor IS SELECT employee_name FROM


employees WHERE department_id = 10; v_employee_name
employees.employee_name%TYPE; BEGIN OPEN employee_cursor; FETCH
employee_cursor INTO v_employee_name; -- Process v_employee_name as
needed CLOSE employee_cursor; END;

Cursor Attributes:

 %FOUND: Returns TRUE if a row was fetched successfully.

 %NOTFOUND: Returns TRUE if a FETCH statement failed to retrieve a


row.

 %ROWCOUNT: Returns the number of rows affected by the last


operation.
Example

Cursor FOR Loops

A FOR loop can be used with an explicit cursor to iterate through the result set.

FOR employee_rec IN employee_cursor LOOP -- Process


employee_rec.employee_name as needed END LOOP;

This syntax simplifies cursor handling and eliminates the need for explicit
OPEN, FETCH, and CLOSE statements.

Exceptions

In PL/SQL, exceptions are used to handle errors and unexpected situations.


They provide a way to gracefully handle issues that may arise during program
execution.

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.

Understanding data manipulation, transaction control statements, PL/SQL


cursors (both implicit and explicit), and exception handling is crucial for
building robust and reliable database applications. These concepts are
fundamental to effective PL/SQL programming.

The SELECT...FOR UPDATE statement in PL/SQL is used to lock rows in a table


so that they cannot be modified or accessed by other transactions until the
current transaction is committed or rolled back.
Example

DECLARE

v_employee_name employees.employee_name%TYPE;

BEGIN

SELECT employee_name

INTO v_employee_name

FROM employees

WHERE employee_id = 101

FOR UPDATE;

-- The selected row is now locked for updates

-- Perform necessary operations

COMMIT; -- or ROLLBACK to release the lock

END;

The FOR UPDATE clause ensures that the selected rows are locked exclusively
for the transaction that executed the SELECT...FOR UPDATE statement.

WHERE CURRENT OF Clause

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

SELECT employee_id, employee_name FROM employees WHERE


department_id = 10 FOR UPDATE;

v_employee_id employees.employee_id%TYPE;

v_employee_name employees.employee_name%TYPE;
BEGIN

OPEN employee_cursor;

FETCH employee_cursor INTO v_employee_id, v_employee_name;

-- Update the current row

UPDATE employees

SET salary = salary * 1.1

WHERE CURRENT OF employee_cursor;

COMMIT; -- or ROLLBACK to finalize changes

CLOSE employee_cursor;

Cursor with Parameters

PL/SQL allows the use of parameters in cursor declarations, enabling dynamic


queries and more flexible cursor handling.

Example

DECLARE

CURSOR employee_cursor (dept_id NUMBER) IS

SELECT employee_name

FROM employees

WHERE department_id = dept_id;

v_employee_name employees.employee_name%TYPE;

BEGIN

OPEN employee_cursor(10); -- Open cursor with department_id parameter

FETCH employee_cursor INTO v_employee_name;

-- Process v_employee_name as needed

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

TYPE EmpCursorType IS REF CURSOR;

emp_cursor EmpCursorType;

v_employee_name employees.employee_name%TYPE;

BEGIN

OPEN emp_cursor FOR

SELECT employee_name FROM employees WHERE department_id = 20;

FETCH emp_cursor INTO v_employee_name;

-- Process v_employee_name as needed

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

-- Some code that might raise an exception

v_result := 10 / 0; -- This will raise a 'DIVIDE BY ZERO' exception


EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE('Cannot divide by zero.');

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);

END;

Types of Exceptions

PL/SQL provides various predefined exceptions that cover common error


conditions. Some of the common ones include:

 NO_DATA_FOUND: Raised when a SELECT INTO statement returns no


rows.

 TOO_MANY_ROWS: Raised when a SELECT INTO statement returns


more than one row.

 ZERO_DIVIDE: Raised when attempting to divide by zero.

 CURSOR_ALREADY_OPEN: Raised when trying to open a cursor that is


already open.

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)

PL/SQL Composite Data Types: Records–Tables–arrays. Named Blocks:


Procedures–Functions– Packages –Triggers –Data Dictionary Views.

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.

Declaration and Initialization:

Example

DECLARE

TYPE EmployeeRecord IS RECORD (

employee_id NUMBER,

employee_name VARCHAR2(50),

salary NUMBER

);

emp_info EmployeeRecord;

BEGIN

emp_info.employee_id := 101;

emp_info.employee_name := 'John Doe';

emp_info.salary := 50000;

-- Accessing record elements

DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_info.employee_id);

DBMS_OUTPUT.PUT_LINE('Employee Name: ' ||


emp_info.employee_name);
DBMS_OUTPUT.PUT_LINE('Salary: ' || emp_info.salary);

END;

Tables

A PL/SQL table is an ordered collection of elements, each with a unique key. It


is similar to an array, but its size can be extended dynamically. Tables are
particularly useful for working with sets of data.

Declaration and Initialization:

Example

DECLARE

TYPE EmpIDList IS TABLE OF NUMBER;

emp_ids EmpIDList := EmpIDList(101, 102, 103, 104);

TYPE EmployeeRecord IS RECORD (

employee_id NUMBER,

employee_name VARCHAR2(50),

salary NUMBER

);

TYPE EmpInfoList IS TABLE OF EmployeeRecord;

emp_info_list EmpInfoList;

BEGIN

emp_info_list := EmpInfoList(

EmployeeRecord(101, 'John Doe', 50000),

EmployeeRecord(102, 'Alice Smith', 60000),

EmployeeRecord(103, 'Bob Johnson', 55000)

);
-- Accessing table elements

FOR i IN emp_ids.FIRST..emp_ids.LAST LOOP

DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_ids(i));

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.

Variable Arrays (VARRAYs):

Example

DECLARE

TYPE EmpIDArray IS VARRAY(3) OF NUMBER;

emp_ids EmpIDArray := EmpIDArray(101, 102, 103);

TYPE EmployeeRecord IS RECORD (

employee_id NUMBER,

employee_name VARCHAR2(50),

salary NUMBER

);

TYPE EmpInfoArray IS VARRAY(3) OF EmployeeRecord;

emp_info_array EmpInfoArray;

BEGIN

emp_info_array := EmpInfoArray(

EmployeeRecord(101, 'John Doe', 50000),

EmployeeRecord(102, 'Alice Smith', 60000),

EmployeeRecord(103, 'Bob Johnson', 55000)


);

-- Accessing array elements

FOR i IN 1..emp_ids.COUNT LOOP

DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_ids(i));

END LOOP;

END;

In this example, EmpIDArray and EmpInfoArray are VARRAYs (Variable Arrays)


with a fixed size of 3. You can adjust the size as needed.

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

CREATE OR REPLACE PROCEDURE calculate_salary (

emp_id IN NUMBER,

bonus OUT NUMBER

) AS

salary NUMBER;

BEGIN

-- Retrieve employee salary from the database

SELECT salary INTO salary FROM employees WHERE employee_id = emp_id;

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

CREATE OR REPLACE FUNCTION get_employee_name (

emp_id IN NUMBER

) RETURN VARCHAR2 IS

emp_name VARCHAR2(50);

BEGIN

-- Retrieve employee name from the database

SELECT employee_name INTO emp_name FROM employees WHERE


employee_id = emp_id;

RETURN emp_name;

END get_employee_name;

3. Packages

Packages are logical groupings of related procedures, functions, variables, and


other PL/SQL constructs. They provide a way to organize and encapsulate
code.

Example

CREATE OR REPLACE PACKAGE payroll_package AS

PROCEDURE calculate_salary (emp_id IN NUMBER, bonus OUT NUMBER);

FUNCTION get_employee_name (emp_id IN NUMBER) RETURN VARCHAR2;

END payroll_package;
CREATE OR REPLACE PACKAGE BODY payroll_package AS

PROCEDURE calculate_salary (emp_id IN NUMBER, bonus OUT NUMBER) IS

salary NUMBER;

BEGIN

-- Retrieve employee salary from the database

SELECT salary INTO salary FROM employees WHERE employee_id =


emp_id;

-- Calculate bonus

bonus := salary * 0.1;

END calculate_salary;

FUNCTION get_employee_name (emp_id IN NUMBER) RETURN VARCHAR2


IS

emp_name VARCHAR2(50);

BEGIN

-- Retrieve employee name from the database

SELECT employee_name INTO emp_name FROM employees WHERE


employee_id = emp_id;

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.

CREATE OR REPLACE TRIGGER before_employee_insert

BEFORE INSERT ON employees

FOR EACH ROW

BEGIN

-- Trigger code to be executed before an employee is inserted

: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

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

-- Query to find all tables in the database

SELECT table_name

FROM all_tables;

-- Query to find columns of a specific table

SELECT column_name, data_type

FROM all_tab_columns

WHERE table_name = 'EMPLOYEES';


-- Query to find all tables in the database SELECT table_name FROM all_tables;
-- Query to find columns of a specific table SELECT column_name, data_type
FROM all_tab_columns WHERE table_name = 'EMPLOYEES';

Data Dictionary Views allow you to retrieve information about tables, columns,
constraints, privileges, and other database objects.

TEXT BOOKS

1. Database Systems using Oracle, Nilesh Shah,2nd edition,PHI.


2. E-Book: Diana Lorentz, “Oracle® Data base SQL Reference”, ORACLE,
Dec,2005.
3. E-Book: Bill Pribyl, Steven Feuerstein, “Oracle PL/SQL Programming”,
O'Reilly Media, Inc., 6th Edition, February 2014.

REFERENCE BOOKS

1. Database Management Systems, Majumdar & Bhattacharya, 2007, TMH.


2. Database Management Systems, GeraldV.Post, 3rd edition,TMH.

E – LEARNING.

1. https://academy.oracle.com
2. www.udemy.com
3. www.livesql.oracle.com
4. www.w3schools.com
5. www.simplilearn.com

You might also like