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

Database Design and

Programming
Tahaluf Training Center 2021

Tahaluf Training Centre 05 Jul 2021


Chapter 01

1 Overview of Database

2 Introduction of Oracle Database

3 Development Life Cycle SDLC

4 Overview of Database Design

5 Database Design Phases

Tahaluf Training Centre 05 Jul 2021


Overview of Database

A Database is a collection of related data organized in a way that can


make the process of data access, manage and update easier.

Database can be hardware based or software based in order to store


data.

Tahaluf Training Centre 05 Jul 2021


Overview of Database

What is DBMS?

A DBMS is software that allows users to build, create and manipulate


the database, allowing them to process, analyze and store data easily.

DBMS provides a tool or interface to perform different operations


such as storing data, creating and updating it, and creating tables in the
database.

Tahaluf Training Centre 05 Jul 2021


Overview of Database

Examples of popular DBMS used these days:

▪ MySQL.
▪ Oracle.
▪ SQL Server.
▪ IBM DB2.
▪ PostgreSQL.
▪ Amazon SimpleDB (cloud based) etc.

Tahaluf Training Centre 05 Jul 2021


Introduction of Oracle Database

An Oracle database is a combination of data treated as a unit. The


purpose of a database is to retrieve and store related data.

A database server is a key used to solve the problems of information


management.

Tahaluf Training Centre 05 Jul 2021


Introduction of Oracle Database

Oracle Database features

1. Oracle Database is cross-platform.

2. Oracle Database has its networking stack.

3. ACID-compliant.

4. Commitment to open technologies.

Tahaluf Training Centre 05 Jul 2021


Development Life Cycle SDLC

The Software Development Life Cycle (SDLC) is a methodology used


to create a high quality software.

SDLC provides a structured flow of phases that used to help an


organization to produce high quality software quickly.

Tahaluf Training Centre 05 Jul 2021


Development Life Cycle SDLC

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Design methodology is a structured approach that uses techniques,


procedures, tools, and documentation aims to support and make the
process of design easier.

There are many database design phases, such as:

1. Requirement analysis.
2. ER – Diagram.
3. Schema Diagram.
4. Class Diagram.

Tahaluf Training Centre 05 Jul 2021


Database Design Cycle

Problem Statement

ER Diagram Schema Diagram

Create Tables

Add update Delete Data

View Data

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

What is Requirements Analysis?

Requirements Analysis is the process of characterizing the expectations of


the users for an application that is to be built or updated. It contains all
the tasks that are produced to identify the needs of different
stakeholders.

Requirements analysis means to analyze, validate, document and manage


system or software requirements.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Example

In a LMS System, there are many courses teach by a many teachers. Each
course has a name, status, date from and date to. Each course has an
exam. In this system, there are many employees work in different
positions.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Example Solution

Database Name: LMS.


Entities: Course, Teacher, Exam, Employee, Role.
Attributes:
1. Course: name, status, date from and date to.
2. Employees: First Name, Last Name, email, Phone Number … etc.

Note: Attributes determine by a database creator based on System need.

Relationships:
1. Many-to-Many: Course and Teacher.
2. One-to-One: Course and Exam.
3. One-to-Many: Role and Employee.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Exercise

In a hospital System, there are many doctors and other employees work.
Doctors treat patients and provide them with care and medicines. There is
a room for every patient entering the hospital.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Exercise Solution

Database Name: Hospital.


Entities: Room, Medicine, Patient, Employee, Role.
Attributes:
1. Employees: First Name, Last Name, email, Phone Number … etc.

Note: Attributes determine by a database creator based on System need.

Relationships:
1. Many-to-Many: Patient and Medicine.
2. One-to-One: Patient and room.
3. One-to-Many: Role and Employee, Employee and Patient.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

What is ER - Model?

An Entity–relationship model (ER model) describes the structure of a


database with a diagram, which is known as Entity Relationship Diagram
(ER Diagram).

An ER model represent a design of a database that can later be


implemented as a database.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

What is ER - Diagram?

An entity relationship diagram (ERD) displays the relationships of entities


stored in a database.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

ER – Diagram Components

Entities are represented by rectangles.

An entity is an object or thing about used to store information.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

ER – Diagram Components

Relationships are represented by diamond shapes, display how two


entities share a data in the database.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

ER – Diagram Components

Attributes are represented by ovals.


A key attribute is the unique, special characteristic of the entity.
Example: an employee’s have a social security number.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

ER – Diagram Components

Attributes are represented by ovals.


A key attribute is the unique, special characteristic of the entity.
Example: an employee’s have a social security number.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

There are four types of relationships:


1. One to One.
2. One to Many.
3. Many to Many.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Draw ER – Diagram

Click on this link: https://erdplus.com/standalone

ERDPlus is a web-based database modeling tool to create entity


relationship (ER) diagrams, star schemas, relational schemas, and SQL DDL
statements.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Draw ER – Diagram

Example

1. Create an entities.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Draw ER – Diagram

2. Create a relationships.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Draw ER – Diagram

2. Create a relationships.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Draw ER – Diagram

3. Create an attributes.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Exercise

Draw ER – Diagram for the following scenario:


In a hospital System, there are many doctors and other employees work.
Doctors treat patients and provide them with care and medicines. There is
a room for every patient entering the hospital.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Exercise Solution

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Built-in data types


Oracle Database provides a collection of built in data types:

1. VARCHAR2(size [BYTE | CHAR]): Variable-length character string


having maximum length size characters or bytes.

Example:

CREATE TABLE Var2_Example (


VARCHAR2_byte VARCHAR2(1 BYTE),
VARCHAR2_char VARCHAR2(1 CHAR)
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

2. NVARCHAR2(size): Variable-length Unicode character string


having maximum length size characters.

Example:

CREATE TABLE Var2_SizeExample (


VAR2 VARCHAR2(100)
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

3. NUMBER [ (p [, s]) ]: Number having precision p and scale s. The


scale s can range from -84 to 127. The precision p can range from 1 to
38.

Example:

CREATE TABLE Number_Example (


NumberExample NUMBER(8,2)
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

4. FLOAT [(p)]: A subtype of the NUMBER data type having precision p.


A FLOAT value is represented internally as NUMBER.

Example:

CREATE TABLE Float_Example (


FloatExample FLOAT(5)
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

5. LONG: Character data of variable length up to 2 gigabytes, or 231 -1


bytes.

Example:

CREATE TABLE Long_Example (


LongExample LONG
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

6. DATE: Valid date range from January 1, 4712 BC, to December 31,
9999 AD.

Example:

CREATE TABLE Date_Example (


DateExample DATE
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

7. BINARY_FLOAT: 32-bit floating point number. This data type requires


4 bytes.

Example:

CREATE TABLE Binary_Example (


BinaryExample BINARY_FLOAT
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

8. BINARY_DOUBLE: 64-bit floating point number. This data type requires


8 bytes.

Example:

CREATE TABLE BinaryD_Example (


BinaryDExample BINARY_DOUBLE
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

9. TIMESTAMP [(fractional_seconds_precision)]: Year, month, and day


values of date, as well as hour, minute, and second values of time, where
fractional_seconds_precision is the number of digits in the fractional part
of the SECOND datetime field. Accepted values of
fractional_seconds_precision are 0 to 9.

Example:

CREATE TABLE TimeStamp_Example (


TimeStampExample TIMESTAMP
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

10. TIMESTAMP [(fractional_seconds_precision)] WITH LOCAL TIME


ZONE: All values of TIMESTAMP WITH TIME ZONE, with the following
exceptions:
Data is normalized to the database time zone when it is stored in the
database.
Example:

CREATE TABLE TimeStampWithLocalZone_Example (


TimeStampWithLocalZoneExample TIMESTAMP WITH LOCAL
TIME ZONE
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

11. INTERVAL YEAR [(year_precision)] TO MONTH: Stores a period of time


in years and months, where year_precision is the number of digits in the
YEAR datetime field.

Example:

CREATE TABLE Interval_Example (


IntervalExample INTERVAL YEAR TO MONTH
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

12. INTERVAL DAY [(day_precision)] TO SECOND


[(fractional_seconds_precision)]: Stores a period of time in days,
hours, minutes, and seconds.

Example:

CREATE TABLE IntervalD_Example (


IntervalExample INTERVAL DAY (6) TO SECOND (5)
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

13. RAW(size): Raw binary data of length size bytes.

Example:

CREATE TABLE RawExample (


RawExample RAW(10)
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

14. LONG RAW: Raw binary data of variable length up to 2 gigabytes.

Example:

CREATE TABLE LRawExample (


LRawExample LONG RAW

);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

15. ROWID: Base 64 string representing the unique address of a row in its
table.

Example:

CREATE TABLE RowIdExample (


Row_Id ROWID,
Name VARCHAR(20)

);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

16. UROWID [(size)]: Base 64 string representing the logical address of a


row of an index-organized table.

Example:

CREATE TABLE URowIdExample (


URow_Id ROWID,
Name VARCHAR(20)

);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

17. CHAR [(size [BYTE | CHAR])]: Fixed-length character data of length


size bytes or characters.

Example:

CREATE TABLE CharExample (


Name CHAR(3 CHAR)
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

18. NCHAR[(size)]: Fixed-length character data of length size characters.

Example:

CREATE TABLE NCharExample (


Name NCHAR(3)
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

19. CLOB: A character large object containing single-byte or multibyte


characters.

Example:

CREATE TABLE ClobExample (


Name NCHAR(3),
Note CLOB
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

20. NCLOB: A character large object containing Unicode characters.

Example:

CREATE TABLE NClobExample (


Name NCHAR(3),
Note NCLOB
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

21. BLOB: A binary large object.

Example:

CREATE TABLE BlobExample (


Image BLOB
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

21. BFILE: Contains a locator to a large binary file stored outside the
database.

Example:

CREATE TABLE BfileExample (


Document BFILE
);

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

What is Schema Diagram?

Schema diagram contains attributes and entities.

It only display the database design and does not display the actual data of
the database.

Schema can be a single table or more than one table which is related.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Draw Schema Diagram

Example

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Exercise

Draw Schema Diagram for the following scenario:

In a hospital System, there are many doctors and other employees work.
Doctors treat patients and provide them with care and medicines. There is
a room for every patient entering the hospital.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

What is Class Diagram?

A class diagram used in modeling and designing software to describe


classes and relationships.

Class diagrams used to model a software in a high level of abstraction.

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Draw Class Diagram

Example

Tahaluf Training Centre 05 Jul 2021


Database Design Phases

Exercise

Draw a Class Diagram for the following scenario:

In a hospital System, there are many doctors and other employees work.
Doctors treat patients and provide them with care and medicines. There is
a room for every patient entering the hospital.

Tahaluf Training Centre 05 Jul 2021


Chapter 02

1 Structured Query Language SQL

2 Data base Object

3 Constraints

Tahaluf Training Centre 05 Jul 2021


Structured Query Language SQL

SQL is a standardized language for defining and manipulating data in


a relational database.

• SQL stands for Structured Query Language.


• SQL lets you access and manipulate databases.
• SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for Standardization
(ISO) in 1987

Tahaluf Training Centre 05 Jul 2021


Structured Query Language SQL

SQL as we all know is the database language by the use of which we


can perform certain operations on the existing database and also we
can use this language to create a database.

SQL uses certain commands like Create, Drop, Insert etc. to carry out
the required tasks.

Tahaluf Training Centre 05 Jul 2021


Structured Query Language SQL

Tahaluf Training Centre 05 Jul 2021


SQL Data Definition Language DDL

DDL actually consists of the SQL commands that can be used to


define the database schema.

It simply deals with descriptions of the database schema and is used


to create and modify the structure of database objects in database.

Tahaluf Training Centre 05 Jul 2021


SQL Data Definition Language DDL

Examples of DDL commands:

• CREATE – is used to create the database or its objects (like table,


index, function, views, store procedure and triggers).

• DROP – is used to delete objects from the database.

• ALTER – is used to alter the structure of the database.

Tahaluf Training Centre 05 Jul 2021


SQL Data Definition Language DDL

• TRUNCATE – is used to remove all records from a table, including


all spaces allocated for the records are removed.

• COMMENT – is used to add comments to the data dictionary.

• RENAME – is used to rename an object existing in the database

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language DML

DML SQL commands that deals with the manipulation of data present
in database belong to DML or Data Manipulation Language and this
includes most of the SQL statements.

Examples of DML commands:

• INSERT – is used to insert data into a table.


• UPDATE – is used to update existing data within a table.
• DELETE – is used to delete records from a database table.

Tahaluf Training Centre 05 Jul 2021


Data Control Language DCL

DCL includes commands such as GRANT and REVOKE which mainly


deals with the rights, permissions and other controls of the database
system.

Examples of DCL commands:

• GRANT - gives user’s access privileges to database.


• REVOKE - withdraw user’s access privileges given by using the
GRANT command.

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language TCL

TCL commands deals with the transaction within the database.

Examples of TCL commands:

• COMMIT– commits a Transaction.


• ROLLBACK– rollbacks a transaction in case of any error occurs.
• SAVEPOINT– sets a save point within a transaction.
• SET TRANSACTION –specify characteristics for the transaction.

Tahaluf Training Centre 05 Jul 2021


Chapter 02

1 Structured Query Language SQL

2 Data base Object

3 Constraints

Tahaluf Training Centre 05 Jul 2021


Data base Object

A database object is any defined object in a database that is used to


store or reference data.

Anything which we make from create command is known as Database


Object.

It can be used to hold and manipulate the data.

Tahaluf Training Centre 05 Jul 2021


Data base Object

Some of the examples of database objects are :

• Table: basic unit to store data has rows and columns.


• View: logical represent data from table or more .
• Sequence: generate numeric value .
• Index: improve the performance of some query.
• Synonym: Give alternative name to an object.

Tahaluf Training Centre 05 Jul 2021


Create user

Use the CREATE USER statement to create and configure a database


user, which is an account through which you can log in to the
database, and to establish the means by which Oracle Database
permits access by the user.

Steps:
1. Create user username identified by password;
2. Grant permission to username .
3. Connect userename/password .

Tahaluf Training Centre 05 Jul 2021


Create Table

Use the CREATE TABLE statement to create one of the following types
of tables:

1. A relational table, which is the basic structure to hold user data.

2. An object table, which is a table that uses an object type for a


column definition. An object table is explicitly defined to hold
object instances of a particular type.

Tahaluf Training Centre 05 Jul 2021


Create Table

Tables are created with no data unless a subquery is specified. You can add
rows to a table with the INSERT statement.

After creating a table, you can define additional columns, partitions, and
integrity constraints with the ADD clause of the ALTER TABLE statement.

You can change the definition of an existing column or partition with the
MODIFY clause of the ALTER TABLE statement.

Tahaluf Training Centre 05 Jul 2021


Create Table

Table Naming Roles:

1. Begin with a letter.


2. Be 1–30 characters long .
3. Contain only A–Z, a–z, 0–9, _, $, and # .
4. Not duplicate the name of another object owned by the same user.
5. Not be an Oracle server–reserved word.
6. Names are not case-sensitive Department is the same department.

Tahaluf Training Centre 05 Jul 2021


Create Table

Syntax :

CREATE TABLE [schema.]table


(column datatype [DEFAULT expr][, ...]);

Tahaluf Training Centre 05 Jul 2021


Create Table

Example :

CREATE TABLE dept


(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));

Tahaluf Training Centre 05 Jul 2021


Create Table

Tahaluf Training Centre 05 Jul 2021


View

This database object is used to create a view in database.

A view is a logical table based on a table or another view. A view contains no


data of its own but is like a window through which data from tables can be
viewed or changed.

The tables on which a view is based are called base tables. The view is stored
as a SELECT statement in the data dictionary.

Tahaluf Training Centre 05 Jul 2021


View

Example:

CREATE VIEW salv


AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;

Tahaluf Training Centre 05 Jul 2021


Sequence

This database object is used to create a sequence in database.

A sequence is a user created database object that can be shared by multiple


users to generate unique integers.

A typical usage for sequences is to create a primary key value, which must be
unique for each row.

The sequence is generated and incremented (or decremented) by an internal


Oracle routine.

Tahaluf Training Centre 05 Jul 2021


Sequence

Example:

CREATE SEQUENCE dept_deptid_seq


INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;

Tahaluf Training Centre 05 Jul 2021


Index

This database object is used to create a indexes in database.

An Oracle server index is a schema object that can speed up the retrieval of
rows by using a pointer.

Indexes can be created explicitly or automatically. If you do not have an index


on the column, then a full table scan occurs.

Tahaluf Training Centre 05 Jul 2021


Index

An index provides direct and fast access to rows in a table. Its purpose is to
reduce the necessity of disk I/O by using an indexed path to locate data
quickly.

The index is used and maintained automatically by the Oracle server. Once an
index is created, no direct activity is required by the user.

Indexes are logically and physically independent of the table they index. This
means that they can be created or dropped at any time and have no effect on
the base tables or other indexes.

Tahaluf Training Centre 05 Jul 2021


Index

Example :
CREATE INDEX emp_last_name_idx
ON employees(last_name);

Tahaluf Training Centre 05 Jul 2021


Synonym

This database object is used to create a indexes in database.

It simplify access to objects by creating a synonym(another name for an


object). With synonyms, you can Ease referring to a table owned by another
user and shorten lengthy object names.

To refer to a table owned by another user, you need to prefix the table name
with the name of the user who created it followed by a period.

Tahaluf Training Centre 05 Jul 2021


Synonym

Creating a synonym eliminates the need to qualify the object name with the
schema and provides you with an alternative name for a table, view,
sequence, procedure, or other objects.

This method can be especially useful with lengthy object names, such as
views.

Tahaluf Training Centre 05 Jul 2021


Synonym

In the syntax:

• PUBLIC : creates a synonym accessible to all users.


• synonym : is the name of the synonym to be created.
• object : identifies the object for which the synonym is created.

CREATE [PUBLIC] SYNONYM synonym FOR object;

Tahaluf Training Centre 05 Jul 2021


Commands

Syntax:
DESCRIBE tablename

Example:
DESCRIBE DEPT

Tahaluf Training Centre 05 Jul 2021


Commands

Syntax:
Select * from TableName;

Example:
Select * from DEPT;

Tahaluf Training Centre 05 Jul 2021


Data type

• VARCHAR2(size) Variable-length character data (minimum size is 1;


maximum size is 4,000.).
• CHAR(size) Fixed-length character data (minimum size is 1; maximum size
is 2,000) .
• NUMBER(p,s) Variable-length numeric data (from 1 to 38, and scale UP
TO 127.).
• DATE: Date and time values between January 1,4712 B.C., and December
31, 9999 A.D

Tahaluf Training Centre 05 Jul 2021


Data type

• LONG Variable-length character data (up to 2 GB).


• CLOB Character data (up to 4 GB) .
• RAW and LONG Raw binary data .
• BLOB Binary data (up to 4 GB) .
• BFILE Binary data stored in an external file (up to 4 GB).
• ROWID A base-64 number system representing the unique address of a
row in its table
Only one LONG column can be used per table

Tahaluf Training Centre 05 Jul 2021


Chapter 02

1 Structured Query Language SQL

2 Data base Object

3 Constraints

Tahaluf Training Centre 05 Jul 2021


constraint

Use a constraint to define an integrity constraint--a rule that restricts the


values in a database.

Oracle Database lets you create six types of constraints and lets you declare
them in two ways.

Tahaluf Training Centre 05 Jul 2021


constraint

The six types of integrity constraint are described briefly here :

• NOT NULL constraint prohibits a database value from being null.

• unique constraint prohibits multiple rows from having the same value in
the same column or combination of columns but allows some values to
be null.

• primary key constraint combines a NOT NULL constraint and a unique


constraint in a single declaration. That is, it prohibits multiple rows from
having the same value in the same column or combination of columns and
prohibits values from being null.

Tahaluf Training Centre 05 Jul 2021


constraint

• foreign key constraint requires values in one table to match values in


another table.

• check constraint requires a value in the database to comply with a


specified condition.

• REF column by definition references an object in another object type or in


a relational table. A REF constraint lets you further describe the
relationship between the REF column and the object it references.

Tahaluf Training Centre 05 Jul 2021


constraint

You can define constraints syntactically in two ways:

1. As part of the definition of an individual column or attribute. This is called


inline specification.

2. As part of the table definition. This is called out-of-line specification.

NOT NULL constraints must be declared inline. All other constraints can be
declared either inline or out of line.

Tahaluf Training Centre 05 Jul 2021


Example of a column-level constraint

CREATE TABLE employees(


employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name VARCHAR2(20),
PhoneNumber Number(10)
)

Tahaluf Training Centre 05 Jul 2021


Example of a table-level constraint

CREATE TABLE employees(


employee_id NUMBER(6),
first_name VARCHAR2(20),
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));

Tahaluf Training Centre 05 Jul 2021


Foreign Key Constraint Table level

CREATE TABLE employees(


employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
REFERENCES departments(department_id),
CONSTRAINT emp_email_uk UNIQUE(email));

Tahaluf Training Centre 05 Jul 2021


Foreign Key Constraint Column level

CREATE TABLE employees


(...
department_id NUMBER(4) CONSTRAINT emp_deptid_fk
REFERENCES departments(department_id),
...
)

Tahaluf Training Centre 05 Jul 2021


Foreign Key Constraint

A foreign key is a way to enforce referential integrity within your Oracle


database. A foreign key means that values in one table must also appear in
another table.

The referenced table is called the parent table while the table with the
foreign key is called the child table. The foreign key in the child table will
generally reference a primary key in the parent table.

A foreign key can be defined in either a CREATE TABLE statement or an


ALTER TABLE statement

Tahaluf Training Centre 05 Jul 2021


Foreign Key Constraint

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
);

Tahaluf Training Centre 05 Jul 2021


Foreign Key Constraint

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
CONSTRAINT fk_supplier_comp
FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name)
);

Tahaluf Training Centre 05 Jul 2021


Foreign Keys with Cascade Delete

foreign key with cascade delete means that if a record in the parent table is
deleted, then the corresponding records in the child table will automatically
be deleted. This is called a cascade delete in Oracle.

A foreign key with a cascade delete can be defined in either a CREATE TABLE
statement or an ALTER TABLE statement.

Tahaluf Training Centre 05 Jul 2021


Foreign Keys with Cascade Delete

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE
);

Tahaluf Training Centre 05 Jul 2021


Foreign Keys with Cascade Delete

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE
);

Tahaluf Training Centre 05 Jul 2021


Using an ALTER TABLE statement

ALTER TABLE products


ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE;

We could also create a foreign key (with a cascade delete) with more than
one field as in the example below:

ALTER TABLE products


ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name)
ON DELETE CASCADE;

Tahaluf Training Centre 05 Jul 2021


Foreign Keys with Set Null on Delete

A foreign key with "set null on delete" means that if a record in the parent
table is deleted, then the corresponding records in the child table will have
the foreign key fields set to null. The records in the child table will not be
deleted.

A foreign key with a "set null on delete" can be defined in either a CREATE
TABLE statement or an ALTER TABLE statement.

Tahaluf Training Centre 05 Jul 2021


Foreign Keys with Set Null on Delete

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10),
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE SET NULL
);

Tahaluf Training Centre 05 Jul 2021


Foreign Keys with Set Null on Delete

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10),
supplier_name varchar2(50),
CONSTRAINT fk_supplier_comp
FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name)
ON DELETE SET NULL
);

Tahaluf Training Centre 05 Jul 2021


Using an ALTER TABLE statement

In this example, we've created a foreign key "with a set null on delete"
called fk_supplier that references the supplier table based on the
supplier_id field.

ALTER TABLE products


ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE SET NULL;

Tahaluf Training Centre 05 Jul 2021


Using an ALTER TABLE statement

We could also create a foreign key "with a set null on delete" with more
than one field as in the example below:

ALTER TABLE products


ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name)
ON DELETE SET NULL;

Tahaluf Training Centre 05 Jul 2021


Add constraint after table creation

ALTER TABLE location


ADD CONSTRAINT PK_location PRIMARY KEY (lnumber,LName);

ALTER TABLE Department


ADD CONSTRAINT FK_manager
FOREIGN KEY (mg_ssn) REFERENCES employee (SSN);

ALTER TABLE mytable


MODIFY (mynumber NUMBER(8,2) CONSTRAINT
my_cons_name NOT NULL);

ALTER TABLE supplier


ADD CONSTRAINT supplier_unique UNIQUE (supplier_id);

Tahaluf Training Centre 05 Jul 2021


Add constraint after table creation

ALTER TABLE suppliers


ADD CONSTRAINT check_supplier_name
CHECK (supplier_name IN ('IBM', 'Microsoft', NVIDIA'));

Tahaluf Training Centre 05 Jul 2021


View Constraint

select constraint_name,constraint_type,table_name
from user_constraints

Tahaluf Training Centre 05 Jul 2021


Enable and disable Constraint

1- alter table table_name ENABLE constraint


constraint_name;

2- alter table table_name DISABLE constraint


constraint_name;

select constraint_name,constraint_type,table_name, Status


from user_constraints

Tahaluf Training Centre 05 Jul 2021


Drop constraint

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

ALTER TABLE location


DROP CONSTRAINT PK_location;

Tahaluf Training Centre 05 Jul 2021


General Example

Tahaluf Training Centre 05 Jul 2021


ALTER TABLE

• Add a new column


• Modify an existing column definition
• Define a default value for the new column
• Drop a column
• Rename a column
• Change table to read-only status

Tahaluf Training Centre 05 Jul 2021


ALTER TABLE

ALTER TABLE employees READ ONLY

ALTER TABLE employees READ WRITE

Tahaluf Training Centre 05 Jul 2021


ALTER TABLE

1. ALTER TABLE table_name


ADD column_name datatype;

2. ALTER TABLE DROP COLUMN

3. ALTER TABLE table_name


MODIFY column_name datatype;

ALTER TABLE "table_name"


RENAME COLUMN “oldname" TO “newname ”;

Tahaluf Training Centre 05 Jul 2021


Drop table

Use the DROP TABLE statement to move a table or object


table to the recycle bin or to remove the table and all its
data from the database entirely.

DROP TABLE table name

Tahaluf Training Centre 05 Jul 2021


Chapter 03

1 Overview of Data Manipulation Language (DML)

2 Data Manipulation Language (DML) Commands

Tahaluf Training Centre 05 Jul 2021


Overview of DML

Data Manipulation Language (DML) is a language used to select,


insert, update and delete data from a database.

DML used to manipulate and retrieve data in a relational database.

Tahaluf Training Centre 05 Jul 2021


Overview of DML

Insert

Update

Delete

DML Commands

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

DDL commands are as follows:

1. INSERT.
2. UPDATE.
3. DELETE.
4. SELECT.

Note: DML performs read-only queries of data.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise

Create a database for the following scenario:

In an exam system, each course contains a many of exams. Each


course has a name, id, description, start date and end date. Each
exam has name, id, duration, start time.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise Solution

CREATE TABLE Course(


Id NUMBER GENERATED BY DEFAULT AS IDENTITY,
Name VARCHAR2(50) NOT NULL,
Description VARCHAR2(250) NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL,
PRIMARY KEY(Id)
);

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise Solution

CREATE TABLE Exam (


Id NUMBER GENERATED BY DEFAULT AS IDENTITY,
Name VARCHAR2(50) NOT NULL,
Duration TIMESTAMP NOT NULL,
StartTime TIMESTAMP NOT NULL,
CONSTRAINT FKeyCourse_Exam
FOREIGN KEY (Id)
REFERENCES Course (Id)
);

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

INSERT command is used to insert a data into a table.

This command can used to add one or more records to a single table in a
database.

Syntax

INSERT INTO table(column, column...)


VALUES (value, value...);

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

There are many mistakes that users make with the insert statement:

✓ Duplicate value violating any primary or unique key constraint.

✓ Forgetting a mandatory value for a NOT NULL column.

✓ Referential integrity maintained for foreign key constraint.

✓ Any value violating a CHECK constraint.

✓ Values too wide to fit in column or data type mismatches.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Example

Insert a record into course table.

Example Solution

INSERT INTO Course(Name, Description, StartDate,EndDate)


VALUES ('Math101', 'Maths', DATE'2021-01-01', DATE'2021-
10-01');

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise

Insert a three record into Course table. Then, Insert a five record into
Exam table.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise Solution

INSERT INTO Course(Name, Description, StartDate,EndDate)


VALUES ('IT101', 'IT', DATE'2021-02-15', DATE'2023-08-
01');

INSERT INTO Course(Name, Description, StartDate,EndDate)


VALUES ('English101', 'English', DATE'2050-02-09',
DATE'2070-08-01');

INSERT INTO Course(Name, Description, StartDate,EndDate)


VALUES ('English102', 'English', DATE'2000-02-09',
DATE'2010-12-05');

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise Solution

INSERT INTO Exam(Name, Duration, StartTime,Id)


VALUES ('FirstExam',timestamp '2017-10-12 21:22:23',
CURRENT_TIMESTAMP, 2);

INSERT INTO Exam(Name, Duration, StartTime,Id)


VALUES ('FirstExam',timestamp '2021-09-16 01:30:23',
timestamp '2021-09-16 3:22:23', 2);

INSERT INTO Exam(Name, Duration, StartTime,Id)


VALUES ('SecondExam',timestamp '2021-09-16 01:30:23',
timestamp '2021-09-16 3:22:23', 4);

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

UPDATE command is used to modify the records in a table.

This command is used to update existing data changes it of one or more


records in a table.

Syntax

UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Example

Update a course name if the description contains English.

Example Solution

UPDATE Course
SET Name = 'English100'
WHERE Description = 'English';

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise

Update an Exam name to final exam if the course is IT.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise Solution

UPDATE Exam
SET Name = 'Final Exam'
WHERE id = 2;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

DELETE command is used to delete or remove a single record or multiple


records from a table.

Syntax

DELETE FROM table WHERE condition;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Example

Delete a course if the course name is IT 101.

Example Solution

DELETE FROM Course


WHERE Name = 'IT101';

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise

Delete an exam if start time before 16/9/2021.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Exercise Solution

DELETE FROM Exam


WHERE StartTime = '2021-09-16';

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

TRUNCATE TABLE command is used to delete all records from a table.

It is the same command as a DELETE without a WHERE clause.

Warning: If you need to truncate a table, the TRUNCATE TABLE


command can not be rolled back.

Syntax

TRUNCATE TABLE table_name;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Example

Delete all record from course table.

Example Solution

TRUNCATE TABLE Course;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

A SELECT statement retrieves data from database. It is used to:

1. Projection: select the columns in a table that are returned using a


query.

2. Selection: select the rows in a table that are returned using a


query.

3. Joining: bring together data that is stored in different tables.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

SELECT Statement Syntax

SELECT *|{[DISTINCT] column|expression [[AS]


alias],...}

FROM table;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

SELECT Example

SELECT id, name, description, startdate, enddate FROM


Course;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

SELECT * Example

SELECT * FROM Course;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Arithmetic Operators are used to add, negate, multiply, subtract, and


divide numeric values.

1. + - : Unary operators denotes a negative or positive expression.

2. * / : Binary operators represent a multiplies and divides.

3. + - : Binary operators represent adds, subtracts.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Arithmetic Operators Examples

SELECT id, name, description, startdate, enddate FROM


Course;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Arithmetic Operators Examples

SELECT id+5, name, description, startdate, enddate FROM


Course;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Arithmetic Operators Examples

SELECT id-1, name, description, startdate, enddate FROM


Course;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Arithmetic Operators Examples

SELECT id*50, name, description, startdate, enddate FROM


Course;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Arithmetic Operators Examples

SELECT id/10, name, description, startdate, enddate FROM


Course;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Operator Precedence Examples

SELECT name, 5+mark*12, id FROM Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Operator Precedence Examples

SELECT name, (5+mark)*12, id FROM Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Null value

✓ Null value not zero.

✓ Null value unknown, unavailable, unassigned.

✓ Null value not blank space.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Null value Example

SELECT name, (5+mark)*12, id FROM Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

ALIASES Statement is used to create a temporary name for tables or


columns.

COLUMN ALIASES are used to make column names easier to read.

Syntax

column_name AS alias_name

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

COLUMN ALIASES Example

SELECT name, (5+mark)*12 AS IncreaseSalary, id FROM


Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

COLUMN ALIASES Example

SELECT name, (5+mark)*12 "Salary", id FROM Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

TABLE ALIASES are used to make a table easier to read or to perform a


self join.

Syntax

table_name alias_name

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

TABLE ALIASES Example

SELECT name, (5+mark)*12, id FROM Student Std;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

DISTINCT Operator exclude duplicate rows.

Example
SELECT DISTINCT name, startdate, enddate, description
FROM Course;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

WHERE Clause is used to restrict the rows returned.

Example

SELECT * FROM Student WHERE MARK > 80;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

= : equal

Example

SELECT * FROM Student WHERE MARK = 90;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

<> : Not equal

Example

SELECT * FROM Student WHERE MARK <> 90;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

!= : Not equal

Example

SELECT * FROM Student WHERE MARK != 90;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

> : Greater than

Example

SELECT * FROM Student WHERE MARK > 85;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

>= : Greater Than or Equal.

Example

SELECT * FROM Student WHERE MARK >= 85;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

< : Less Than.

Example

SELECT * FROM Student WHERE MARK < 85;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

<= : Less Than or Equal.

Example

SELECT * FROM Student WHERE MARK <= 85;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

IN ( ) : Matches a value in a list.

Example

SELECT * FROM Student WHERE MARK IN (90, 80);

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

NOT: Negates a condition.

Example

SELECT * FROM Student WHERE MARK NOT IN (90, 80);

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

BETWEEN: Within a range (inclusive).

Example

SELECT * FROM Student WHERE MARK BETWEEN 85 AND 90;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

IS NULL: NULL value.

Example

SELECT * FROM Student WHERE MARK IS NULL;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

IS NOT NULL: Non-NULL value.

Example

SELECT * FROM Student WHERE MARK IS NOT NULL;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

LIKE: Pattern matching with % and _.

Example

SELECT * FROM Student WHERE Name LIKE 'a%';

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

LIKE Examples

SELECT * FROM Student WHERE Name LIKE '%i';

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Comparison Operator

LIKE Examples

SELECT * FROM Student WHERE Mark LIKE '8_';

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Logical Conditions combines the results of two conditions to


produce a single result.

1. NOT returns TRUE if the condition is FALSE.

2. AND returns TRUE if both conditions are TRUE.

3. OR returns TRUE if either condition is TRUE.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Logical Conditions Examples

SELECT * FROM Student WHERE name LIKE 'a%' OR mark = 90;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Logical Conditions Examples

SELECT * FROM Student WHERE name LIKE 'a%' AND mark =


90;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Logical Conditions Examples

SELECT * FROM Student WHERE name NOT LIKE'%i';

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

ORDER BY Clause used to specify the order in which rows appear in


the result sed.

SELECT * FROM Student WHERE name NOT LIKE'%i' ORDER BY


ID;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

ORDER BY Clause Examples

SELECT * FROM Student WHERE name NOT LIKE'%i'ORDER BY ID


ASC;

Note: ORDER BY ASC is the default case.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

ORDER BY Clause Examples

SELECT * FROM Student WHERE name NOT LIKE'%i'ORDER BY ID


DESC;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

SQL function

1. Single Row Function.

2. Multiple Row Function.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

SQL function

1. Single Row Function.

✓ Character.
✓ Number.
✓ Date.
✓ Conversion.

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Single Row Function

Character functions example

SELECT INITCAP(name) from Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Single Row Function

Character functions example

SELECT LENGTH(name) from Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Single Row Function

Character functions example

SELECT ROUND(mark) from Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Single Row Function

Character functions example

SELECT TRUNC(mark) from Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Single Row Function

General function NVL

SELECT MOD(mark, id) from Student;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Single Row Function

General function NVL

SELECT NVL(dname, 0) FROM DEPT;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Multiple Row Function

Aggregate function GROUP BY

SELECT name, Min(Mark) AS "Min" FROM student GROUP


BY name;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Multiple Row Function

Aggregate function GROUP BY

SELECT name, Max(Mark) AS "Max" FROM student GROUP


BY name;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Multiple Row Function

Aggregate function GROUP BY

SELECT name, COUNT(*) FROM student GROUP BY name;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Multiple Row Function

Aggregate function GROUP BY

SELECT name, COUNT(*) FROM student WHERE Id= 1


GROUP BY name;

Tahaluf Training Centre 05 Jul 2021


Data Manipulation Language (DML) Commands

Multiple Row Function

Aggregate function GROUP BY

SELECT name FROM student HAVING SUM(mark)>=90


GROUP BY name;

Tahaluf Training Centre 05 Jul 2021


Chapter 04

1 Overview of Transaction Control Language (TCL)

2 Transaction Control Language (TCL) Commands

Tahaluf Training Centre 05 Jul 2021


Overview of Transaction Control Language (TCL)

Transaction Control Language (TCL) commands are used to manage


transactions in the database.

These are used to manage the changes made by Data manipulation


language (DML) commands.

It also allows commands and statements to be grouped together into


logical transactions.

Tahaluf Training Centre 05 Jul 2021


Overview of Transaction Control Language (TCL)

A transaction consists of one of the following:

✓ DML commands constitute one consistent change to the data.

✓ One data control language (DCL) command.

✓ One DDL command.

Tahaluf Training Centre 05 Jul 2021


Overview of Transaction Control Language (TCL)

A transaction starts implicitly when the first SQL command begins,


and it continues until one of the following are met:

✓ COMMIT command used to write the changes to this point on the


database.

✓ ROLLBACK statement to cancel/no write the changes to this point


on the database.

Tahaluf Training Centre 05 Jul 2021


Overview of Transaction Control Language (TCL)

✓ When a user executes DDL commands (CREATE, DROP, ALTER,


…etc), the system first commits any DML commands (INSERT,
UPDATE, DELETE) executed to this point, before executing the DDL
statements.

✓ When a program crashes, all the updates to this point are rolled
back implicitly.

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language (TCL) Commands

Commit Example

INSERT INTO DEPT (DEPTNO, DNAME, LOC)


VALUES(1, 'Admin', 'Irbid');
SELECT * FROM DEPT;
INSERT INTO DEPT (DEPTNO, DNAME, LOC)
VALUES(4, 'Training', 'Irbid');

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language (TCL) Commands

Commit Example

INSERT INTO DEPT (DEPTNO, DNAME, LOC)


VALUES(1, 'Admin', 'Irbid');
SELECT * FROM DEPT;
INSERT INTO DEPT (DEPTNO, DNAME, LOC)
VALUES(4, 'Training', 'Irbid');
COMMIT;

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language (TCL) Commands

ROLLBACK Example

INSERT INTO DEPT (DEPTNO, DNAME, LOC)


VALUES(5, 'Training2', 'Irbid’);
SELECT * FROM DEPT;

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language (TCL) Commands

ROLLBACK Example

ROLLBACK;
SELECT * FROM DEPT;

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language (TCL) Commands

Automatic commit

An automatic commit occurs in the following:

1. A DDL statement issued.

2. A DCL statement issued (GRANT, REVOKE).

3. Normal exit from SQL*Plus or SQL Developer, without explicitly


issuing ROLLBACK or COMMIT commands.

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language (TCL) Commands

Automatic Rollback

An automatic rollback occurs in the following:

1. When there is an abnormal termination of SQL Developer,


SQL*Plus or a system failure.

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language (TCL) Commands

State of the Data After COMMIT

1. Data updates are saved in the database.

2. The previous state of the data is overwritten.

3. All users can display the results.

4. Locks on the affected rows are released;

5. All save points are erased.

6. Rows are available for other users to manipulate.

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language (TCL) Commands

State of the Data After ROLLBACK

Discard all pending updates occurs in the following:

1. Previous state of the data is restored.

2. Data updates are undone.

3. Locks on the affected rows are released.

Tahaluf Training Centre 05 Jul 2021


Transaction Control Language (TCL) Commands

FOR UPDATE Clause in a SELECT Statement

SELECT *
FROM DEPT
WHERE DNAME = 'Admin'
FOR UPDATE
ORDER BY DEPTNO;

Note: Lock is released only when you issue a COMMIT or a ROLLBACK.

Tahaluf Training Centre 05 Jul 2021


Chapter 05

1 Display data from multiple table

2 INNER JOIN

3 LEFT OUTER

4 RIGHT OUTER JOIN

5 FULL OUTER JOIN

6 Queries

Tahaluf Training Centre 05 Jul 2021


Display data from multiple table

The related tables of a large database are linked through the use of
foreign and primary keys or what are often referred to as common
columns.

The ability to join tables will enable you to add more meaning to the
result table that is produced.

Tahaluf Training Centre 05 Jul 2021


Display data from multiple table

For 'n' number tables to be joined in a query, minimum (n-1) join


conditions are necessary.

Based on the join conditions, Oracle combines the matching pair of


rows and displays the one which satisfies the join condition.

Tahaluf Training Centre 05 Jul 2021


Display data from multiple table

Joins are classified as below:

1. INNER JOIN (or sometimes called simple join)


2. LEFT OUTER JOIN (or sometimes called LEFT JOIN)
3. RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
4. FULL OUTER JOIN (or sometimes called FULL JOIN)

Tahaluf Training Centre 05 Jul 2021


INNER JOIN

The INNER join is such a join when equijoins and non equijoins are
performed, rows from the source and target tables are matched using
a join condition formulated with equality and inequality operators,
respectively. These are referred to as inner joins.

Tahaluf Training Centre 05 Jul 2021


INNER JOIN

Syntax:

SELECT table1.column, table2.column


FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Tahaluf Training Centre 05 Jul 2021


INNER JOIN

Tahaluf Training Centre 05 Jul 2021


INNER JOIN

Tahaluf Training Centre 05 Jul 2021


INNER JOIN(Exercise)

Create the following Table :

Tahaluf Training Centre 05 Jul 2021


INNER JOIN(Exercise)

Create the following Table :

Tahaluf Training Centre 05 Jul 2021


INNER JOIN(Exercise)

SELECT a.department_id, a.department_name, b.city


FROM departments a INNER JOIN locations b ON
a.location_id = b.location_id;

Tahaluf Training Centre 05 Jul 2021


LEFT OUTER

A LEFT OUTER JOIN performs an inner join of two tables (supposed


table A which writes before the join keyword and table B which writes
after the join keyword in the SQL statement ) based on the condition
specified after the ON keyword.

It returns all rows from the table A as well as the unmatched rows
from the table B. For all rows in A that have no matching rows in B,
Oracle Database returns null for any select list expressions containing
columns of B.

Tahaluf Training Centre 05 Jul 2021


LEFT OUTER

Syntax:

SELECT table1.column, table2.column


FROM table1
LEFT OUTER JOIN table2
ON (table1.column = table2.column);

Tahaluf Training Centre 05 Jul 2021


LEFT OUTER

Tahaluf Training Centre 05 Jul 2021


LEFT OUTER

Create the following Table :

Tahaluf Training Centre 05 Jul 2021


LEFT OUTER

Create the following Table :

Tahaluf Training Centre 05 Jul 2021


LEFT OUTER

SELECT e.first_name, e.department_id,


d.department_name FROM employees e LEFT OUTER JOIN
departments d ON (e.department_id = d.department_id)
WHERE d.department_name LIKE 'P%';

Tahaluf Training Centre 05 Jul 2021


RIGHT OUTER JOIN

A RIGHT OUTER JOIN performs an inner join of two tables (supposed table A
which writes before the join keyword and table B which writes after the join
keyword in the SQL statement ) based on the condition specified after the ON
keyword.

It returns all rows from the table B as well as the unmatched rows from the
table A. For all rows in B that have no matching rows in A, Oracle Database
returns null for any select list expressions containing columns of A.

Tahaluf Training Centre 05 Jul 2021


RIGHT OUTER JOIN

Syntax:

SELECT table1.column, table2.column


FROM table1
RIGHT OUTER JOIN table2
ON (table1.column = table2.column);

Tahaluf Training Centre 05 Jul 2021


RIGHT OUTER JOIN

Tahaluf Training Centre 05 Jul 2021


RIGHT OUTER JOIN

Create the following Table :

Tahaluf Training Centre 05 Jul 2021


LEFT OUTER

Create the following Table :

Tahaluf Training Centre 05 Jul 2021


LEFT OUTER

SELECT a.department_id, a.department_name,


count(m1.employee_id) employees,
NVL(TO_CHAR(AVG(m1.salary), '99999.99'), '- Nil -
') avg_sal, m2.first_name, m2.salary, m2.job_id
FROM departments a RIGHT OUTER JOIN employees m1
ON a.department_id = m1.department_id RIGHT OUTER
JOIN employees m2 ON a.department_id =
m2.department_id GROUP BY a.department_id,
a.department_name, m2.first_name, m2.salary,
m2.job_id ORDER BY a.department_id, employees;

Tahaluf Training Centre 05 Jul 2021


LEFT OUTER

Tahaluf Training Centre 05 Jul 2021


FULL OUTER JOIN

A full outer join performs a join between two tables that returns the results
of an INNER join as well as the results of a left and right outer join

Tahaluf Training Centre 05 Jul 2021


FULL OUTER JOIN

Syntax:

SELECT table1.column, table2.column


FROM table1
FULL OUTER JOIN table2
ON (table1.column = table2.column);

Tahaluf Training Centre 05 Jul 2021


FULL OUTER JOIN

Tahaluf Training Centre 05 Jul 2021


FULL OUTER JOIN

Create the following Table :

Tahaluf Training Centre 05 Jul 2021


FULL OUTER JOIN

Create the following Table :

Tahaluf Training Centre 05 Jul 2021


FULL OUTER JOIN

SELECT a.first_name, b.department_id,


b.department_name FROM employees a FULL OUTER JOIN
departments b ON (a.department_id = b.department_id);

Tahaluf Training Centre 05 Jul 2021


Queries

Q1: Write a SQL query to display the item name, price, and company name
of all the products.

Tahaluf Training Centre 05 Jul 2021


Queries

Solution:
SELECT item_mast.pro_name, pro_price,
company_mast.com_name FROM item_mast INNER JOIN
company_mast ON item_mast.pro_com =
company_mast.com_id;

Tahaluf Training Centre 05 Jul 2021


Queries

Q2: The following query retrieves all the matching rows in the departments
table, and employees table for the criteria same department_id in both
tables, and also those rows from employees table even if there is no match in
the departments table.

Use The Same Tables that we create before ☺

Tahaluf Training Centre 05 Jul 2021


Queries

Solution:
SELECT e.first_name, e.department_id,
d.department_name FROM employees e RIGHT OUTER JOIN
departments d ON (e.department_id = d.department_id);

Tahaluf Training Centre 05 Jul 2021


Queries

Solution:

Tahaluf Training Centre 05 Jul 2021


Chapter 06

1 Subqueries

2 VIEW

3 Sequences (Auto number)

4 Synonyms

Tahaluf Training Centre 05 Jul 2021


Subqueries

A subquery is best defined as a query within a query. Subqueries


enable you to write queries that select data rows for criteria that are
actually developed while the query is executing at run time.

More formally, it is the use of a SELECT statement inside one of the


clauses of another SELECT statement.

Tahaluf Training Centre 05 Jul 2021


Subqueries

In fact, a subquery can be contained inside another subquery, which


is inside another subquery, and so forth. A subquery can also be
nested inside INSERT, UPDATE, and DELETE statements. Subqueries
must be enclosed within parentheses.

Tahaluf Training Centre 05 Jul 2021


Subqueries

A subquery SELECT statement is very similar to the SELECT statement


used to begin a regular or outer query.

The complete syntax of a subquery is:


( SELECT [DISTINCT] subquery_select_parameter
FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY column_name [,column_name ] ...]
[HAVING search_conditions] )

Tahaluf Training Centre 05 Jul 2021


Subqueries

Types of Subqueries:
• Single Row Sub Query: Sub query which returns single row output. They
mark the usage of single row comparison operators, when used in WHERE
conditions.
• Multiple row sub query: Sub query returning multiple row output. They
make use of multiple row comparison operators like IN, ANY, ALL. There
can be sub queries returning multiple columns also.

Tahaluf Training Centre 05 Jul 2021


Subqueries

• Correlated Sub Query: Correlated subqueries depend on data provided


by the outer query.

This type of subquery also includes subqueries that use the EXISTS operator
to test the existence of data rows satisfying specified criteria.

Tahaluf Training Centre 05 Jul 2021


Subqueries

In the below SELECT query, inner SQL returns only one row i.e. the
minimum salary for the company. It in turn uses this value to
compare salary of all the employees and displays only those, whose
salary is equal to minimum salary.

SELECT first_name, salary, department_id


FROM employees
WHERE salary = (SELECT MIN (salary)
FROM employees);

Tahaluf Training Centre 05 Jul 2021


Subqueries

A HAVING clause is used when the group results of a query need to


be restricted based on some condition. If a subquery's result must be
compared with a group function, you must nest the inner query in the
outer query's HAVING clause.

SELECT department_id, MIN (salary)


FROM employees
GROUP BY department_id
HAVING MIN (salary) < (SELECT AVG (salary)
FROM employees)

Tahaluf Training Centre 05 Jul 2021


VIEW

Use the CREATE VIEW statement to define a view, which is a logical


table based on one or more tables or views. A view contains no data
itself. The tables upon which a view is based are called base tables.

Tahaluf Training Centre 05 Jul 2021


Create VIEW

Syntax:
The syntax for the CREATE VIEW Statement in Oracle/PLSQL is:

CREATE VIEW view_name AS


SELECT columns
FROM tables
WHERE conditions;

Tahaluf Training Centre 05 Jul 2021


Create VIEW

view_name
It specifies the name of the Oracle VIEW that you want to create.

WHERE conditions
Optional. The conditions that must be met for the records to be
included in the VIEW.

Tahaluf Training Centre 05 Jul 2021


Create VIEW

In this example, we are creating two tables suppliers and orders first.

CREATE TABLE "SUPPLIERS"


( "SUPPLIER_ID" NUMBER,
"SUPPLIER_NAME" VARCHAR2(4000),
"SUPPLIER_ADDRESS" VARCHAR2(4000)
)

Tahaluf Training Centre 05 Jul 2021


Create VIEW

CREATE TABLE "ORDERS"


( "ORDER_NO." NUMBER,
"QUANTITY" NUMBER,
"PRICE" NUMBER
)

Tahaluf Training Centre 05 Jul 2021


Create VIEW

Create View Query:

CREATE VIEW sup_orders AS


SELECT suppliers.supplier_id, orders.quantity,
orders.price
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = supplier_id
WHERE suppliers.supplier_name = 'VOJO';

Tahaluf Training Centre 05 Jul 2021


Create VIEW

Display View Query:

SELECT * FROM sup_orders;

Tahaluf Training Centre 05 Jul 2021


Sequences

n Oracle, you can create an auto number field by using sequences. A


sequence is an object in Oracle that is used to generate a number
sequence.

This can be useful when you need to create a unique number to act
as a primary key.

Tahaluf Training Centre 05 Jul 2021


Sequences

Syntax:
The syntax to create a sequence in Oracle is:

CREATE SEQUENCE sequence_name


MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;

Tahaluf Training Centre 05 Jul 2021


Sequences

sequence_name
The name of the sequence that you wish to create.

CREATE SEQUENCE supplier_seq


MINVALUE 1
MAXVALUE 999999999999999999999999999
START WITH 1
INCREMENT BY 1
CACHE 20;

Tahaluf Training Centre 05 Jul 2021


Sequences

This would create a sequence object called supplier_seq.

The first sequence number that it would use is 1 and each


subsequent number would increment by 1 (ie: 2,3,4,...}.

It will cache up to 20 values for performance.

Tahaluf Training Centre 05 Jul 2021


Sequences

If you omit the MAXVALUE option, your sequence will automatically default
to:

MAXVALUE 999999999999999999999999999

Tahaluf Training Centre 05 Jul 2021


Sequences

So you can simplify your CREATE SEQUENCE command as follows:

CREATE SEQUENCE supplier_seq


MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 20;

Tahaluf Training Centre 05 Jul 2021


Sequences

To retrieve the next value in the sequence order, you need to use nextval.

supplier_seq.NEXTVAL;

INSERT INTO suppliers


(supplier_id, supplier_name)
VALUES
(supplier_seq.NEXTVAL, 'Kraft Foods');

Tahaluf Training Centre 05 Jul 2021


Drop Sequence

Once you have created your sequence in Oracle, you might find that you
need to remove it from the database.

Syntax:

DROP SEQUENCE sequence_name;

Tahaluf Training Centre 05 Jul 2021


Sequence

Thinking Question !!

Tahaluf Training Centre 05 Jul 2021


Sequence

Question: While creating a sequence, what does cache and nocache options
mean?
For example, you could create a sequence with a cache of 20 as follows:

CREATE SEQUENCE supplier_seq CREATE SEQUENCE supplier_seq


MINVALUE 1 MINVALUE 1
START WITH 1 START WITH 1
INCREMENT BY 1 INCREMENT BY 1
CACHE 20; NOCACHE;

Tahaluf Training Centre 05 Jul 2021


Sequence

Answer: With respect to a sequence, the cache option specifies how many
sequence values will be stored in memory for faster access.

The downside of creating a sequence with a cache is that if a system failure


occurs, all cached sequence values that have not be used, will be "lost".

This results in a "gap" in the assigned sequence values. When the system
comes back up, Oracle will cache new numbers from where it left off in the
sequence, ignoring the so called "lost" sequence values.

Tahaluf Training Centre 05 Jul 2021


Sequence

Question: How do we set the LASTVALUE value in an Oracle Sequence?

Tahaluf Training Centre 05 Jul 2021


Sequence

Answer: You can change the LASTVALUE for an Oracle sequence, by executing
an ALTER SEQUENCE command.

For example, if the last value used by the Oracle sequence was 100 and you
would like to reset the sequence to serve 225 as the next value. You would
execute the following commands.

ALTER SEQUENCE seq_name


INCREMENT BY 124;
SELECT seq_name.nextval FROM dual;
ALTER SEQUENCE seq_name
INCREMENT BY 1;

Tahaluf Training Centre 05 Jul 2021


Synonyms

synonym is an alternative name for objects such as tables, views, sequences,


stored procedures, and other database objects.

You generally use synonyms when you are granting access to an object from
another schema and you don't want the users to have to worry about
knowing which schema owns the object.

Tahaluf Training Centre 05 Jul 2021


Synonyms

Syntax:

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name


FOR [schema .] object_name [@ dblink];

OR REPLACE:
Allows you to recreate the synonym (if it already exists) without having to
issue a DROP synonym command.

Tahaluf Training Centre 05 Jul 2021


Synonyms

Syntax:

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name


FOR [schema .] object_name [@ dblink];

PUBLIC
It means that the synonym is a public synonym and is accessible to all users.
Remember though that the user must first have the appropriate privileges to
the object to use the synonym.

Tahaluf Training Centre 05 Jul 2021


Synonyms

Syntax:

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name


FOR [schema .] object_name [@ dblink];

schema
The appropriate schema. If this phrase is omitted, Oracle assumes that you
are referring to your own schema.

Tahaluf Training Centre 05 Jul 2021


Synonyms

object_name:
The name of the object for which you are creating the synonym. It can be one
of the following:
• table
• view
• sequence
• stored procedure
• function
• package
• materialized view
• java class schema object
• user-defined object
• synonym

Tahaluf Training Centre 05 Jul 2021


Synonyms

Example:

CREATE PUBLIC SYNONYM suppliers


FOR app.suppliers;

This example demonstrates how to create a synonym called suppliers.

Now, users of other schemas can reference the table called suppliers without
having to prefix the table name with the schema named app.

Tahaluf Training Centre 05 Jul 2021


Synonyms

This example demonstrates how to create a synonym called suppliers:

CREATE PUBLIC SYNONYM suppliers


FOR app.suppliers;

Now, users of other schemas can reference the table called suppliers without
having to prefix the table name with the schema named app:

SELECT *
FROM suppliers;

Tahaluf Training Centre 05 Jul 2021


Synonyms

If this synonym already existed and you wanted to redefine it, you could
always use the OR REPLACE phrase as follows:

CREATE OR REPLACE PUBLIC SYNONYM suppliers


FOR app.suppliers;

Tahaluf Training Centre 05 Jul 2021


Drop synonym

Once a synonym has been created in Oracle, you might at some point need
to drop the synonym.

Syntax:

DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];

Tahaluf Training Centre 05 Jul 2021


Drop synonym

PUBLIC
Allows you to drop a public synonym. If you have specified PUBLIC, then you
don't specify a schema.

force
It will force Oracle to drop the synonym even if it has dependencies. It is
probably not a good idea to use force as it can cause invalidation of Oracle
objects.

Tahaluf Training Centre 05 Jul 2021


Drop synonym

Example:

DROP PUBLIC SYNONYM suppliers;

This DROP statement would drop the synonym called suppliers that we
defined earlier.

Tahaluf Training Centre 05 Jul 2021


Chapter 07

1 PL/SQL

2 Anonymous Block

3 Data Types

4 Variables

5 Comments

Tahaluf Training Centre 05 Jul 2021


PL/SQL

PL/SQL stands for “Procedural Language extensions to the Structured


Query Language”.

SQL is a popular language for both querying and updating data in the
relational database management systems (RDBMS).

Tahaluf Training Centre 05 Jul 2021


PL/SQL

PL/SQL adds many procedural constructs to SQL language to


overcome some limitations of SQL.

Besides, PL/SQL provides a more comprehensive programming


language solution for building mission-critical applications on Oracle
Databases.

Tahaluf Training Centre 05 Jul 2021


PL/SQL

PL/SQL is an embedded language.

PL/SQL only can execute in an Oracle Database. It was not designed


to use as a standalone language like Java, C#, and C++.

In other words, you cannot develop a PL/SQL program that runs on a


system that does not have an Oracle Database.

Tahaluf Training Centre 05 Jul 2021


PL/SQL

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

PL/SQL is a block-structured language whose code is organized into


blocks. A PL/SQL block consists of three sections: declaration,
executable, and exception-handling sections.

In a block, the executable section is mandatory while the declaration


and exception-handling sections are optional.

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

A PL/SQL block has a name. Functions or Procedures is an example of


a named block. A named block is stored into the Oracle Database
server and can be reused later.

A block without a name is an anonymous block. An anonymous block


is not saved in the Oracle Database server, so it is just for one-time
use.

However, PL/SQL anonymous blocks can be useful for testing


purposes.

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

A PL/SQL block has a name. Functions or Procedures is an example of


a named block. A named block is stored into the Oracle Database
server and can be reused later.

A block without a name is an anonymous block. An anonymous block


is not saved in the Oracle Database server, so it is just for one-time
use.

However, PL/SQL anonymous blocks can be useful for testing


purposes.

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

Example :

SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT.put_line ('Hello World!');
END;
/

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

/
Welcome in Tahluf

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

Execute a PL/SQL anonymous block using SQL Developer:

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

DECLARE
l_message VARCHAR2( 255 ) := 'Hello World!';
BEGIN
DBMS_OUTPUT.PUT_LINE( l_message );
END;

Tahaluf Training Centre 05 Jul 2021


Anonymous Block

DECLARE
v_result NUMBER;
BEGIN
v_result := 1 / 0;
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE( SQLERRM );
END;

Tahaluf Training Centre 05 Jul 2021


Data Types

Each value in PL/SQL such as a constant, variable and parameter has


a data type that determines the storage format, valid values, and
allowed operations.

PL/SQL has two kinds of data types: scalar and composite.

Tahaluf Training Centre 05 Jul 2021


Data Types

The scalar types are types that store single values such as number,
Boolean, character, and datetime .

composite types are types that store multiple values, for example,
record and collection

Tahaluf Training Centre 05 Jul 2021


Numeric data types

The numeric data types represent real numbers, integers, and


floating-point numbers. They are stored as NUMBER, IEEE floating-
point storage types (BINARY_FLOAT and BINARY_DOUBLE), and
PLS_INTEGER.

The data types NUMBER, BINARY_FLOAT, and BINARY_DOUBLE are


SQL data types.

The PLS_INTEGER datatype is specific to PL/SQL. It represents signed


32 bits integers that range from -2,147,483,648 to 2,147,483,647.

Tahaluf Training Centre 05 Jul 2021


Numeric data types

Because PLS_INTEGER datatype uses hardware arithmetic, they are


faster than NUMBER operations, which uses software arithmetic.

In addition, PLS_INTEGER values require less storage than NUMBER.

Hence, you should always use PLS_INTEGER values for all calculation
in its range to increase the efficiency of programs.

Tahaluf Training Centre 05 Jul 2021


Numeric data types

The PLS_INTEGER datatype has the following predefined subtypes:

Tahaluf Training Centre 05 Jul 2021


Boolean data type

The BOOLEAN datatype has three data values: TRUE, FALSE, and
NULL. Boolean values are typically used in control flow structure such
as IF-THEN, CASE, and loop statements like LOOP, FOR LOOP, and
WHILE LOOP.

Tahaluf Training Centre 05 Jul 2021


Boolean data type

SQL does not have the BOOLEAN data type, therefore, you cannot:

• Assign a BOOLEAN value to a table column.


• Select the value from a table column into a BOOLEAN variable.
• Use a BOOLEAN value in a SQL function.
• Use a BOOLEAN expression in a SQL statement.
• Use a BOOLEAN value in the DBMS_OUTPUT.PUTLINE and
DBMS_OUTPUT.PUT subprograms.

Tahaluf Training Centre 05 Jul 2021


Character data types

The character data types represent alphanumeric text.

PL/SQL uses the SQL character data types such as CHAR, VARCHAR2,
LONG, RAW, LONG RAW, ROWID, and UROWID.

• CHAR(n) is a fixed-length character type whose length is from 1 to


32,767 bytes.

• VARCHAR2(n) is varying length character data from 1 to 32,767


bytes.

Tahaluf Training Centre 05 Jul 2021


Datetime data types

The datetime data types represent dates, timestamp with or without


time zone and intervals.

PL/SQL datetime data types are DATE, TIMESTAMP, TIMESTAMP


WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL
YEAR TO MONTH, and INTERVAL DAY TO SECOND.

Tahaluf Training Centre 05 Jul 2021


Data type synonyms

Data types have synonyms for compatibility with non-Oracle data


sources such as IBM Db2, SQL Server.

It is not a good practice to use data type synonym unless you are
accessing a non-Oracle Database.

Tahaluf Training Centre 05 Jul 2021


Data type synonyms

Tahaluf Training Centre 05 Jul 2021


Variables

In PL/SQL, a variable is named storage location that stores a value of


a particular data type. The value of the variable changes through the
program. Before using a variable, you must declare it in the
declaration section of a block.

Tahaluf Training Centre 05 Jul 2021


Variables

The syntax for a variable declaration is as follows:

variable_name datatype [NOT NULL] [:= initial_value];

Tahaluf Training Centre 05 Jul 2021


Variables

In the last syntax:

• First, specify the name of the variable. The name of the variable
should be as descriptive as possible, e.g., l_total_sales,
l_credit_limit, and l_sales_revenue.

• Second, choose an appropriate data type for the variable,


depending on the kind of value which you want to store, for
example, number, character, Boolean, and datetime.

• By convention, local variable names should start with l_ and


global variable names should have a prefix of g_ .

Tahaluf Training Centre 05 Jul 2021


Variables

DECLARE
l_total_sales NUMBER(15,2);
l_credit_limit NUMBER (10,0);
l_contact_name VARCHAR2(255);
BEGIN
NULL;
END;

Tahaluf Training Centre 05 Jul 2021


Variables

Default values:

PL/SQL allows you to set a default value for a variable at the


declaration time. To assign a default value to a variable, you use the
assignment operator (:=) or the DEFAULT keyword.

Tahaluf Training Centre 05 Jul 2021


Variables

DECLARE
l_product_name VARCHAR2( 100 ) := 'Laptop';
BEGIN
NULL;
END;

It is equivalent to the following block:

DECLARE
l_product_name VARCHAR2(100) DEFAULT 'Laptop';
BEGIN
NULL;
END;

Tahaluf Training Centre 05 Jul 2021


Variables

NOT NULL constraint:

If you impose the NOT NULL constraint on a value, then the variable
cannot accept a NULL value.

Besides, a variable declared with the NOT NULL must be initialized


with a non-null value.

Note that PL/SQL treats a zero-length string as a NULL value.

Tahaluf Training Centre 05 Jul 2021


Variables

DECLARE
l_shipping_status VARCHAR2( 25 ) NOT NULL := 'Shipped';
BEGIN
l_shipping_status := '';
END;

It is equivalent to the following block:

ORA-06502: PL/SQL: numeric or value error

Tahaluf Training Centre 05 Jul 2021


Variables

Anchored declarations:

Typically, you declare a variable and select a value from a table column to this
variable.

If the data type of the table column changes, you must adjust the program to
make it work with the new type.

PL/SQL allows you to declare a variable whose data type anchor to a table
column or another

Tahaluf Training Centre 05 Jul 2021


Variables

DECLARE
l_name DEPT.DNAME%TYPE;
l_loc DEPT.loc%TYPE;
BEGIN
SELECT
DNAMe, loc
INTO
l_name, l_loc
FROM
DEPT
WHERE
DEPTNO = 3;
DBMS_OUTPUT.PUT_LINE(l_name || ':' || l_loc );
END;
/

Tahaluf Training Centre 05 Jul 2021


Variables

DECLARE
l_Name student.name%TYPE;
l_average_mark student.mark%TYPE;
l_max_mark student.mark%TYPE;
l_min_mark student.mark%TYPE;
BEGIN
-- get credit limits
SELECT
MIN(mark),
MAX(mark),
AVG(mark)
INTO
l_min_mark,
l_max_mark,
l_average_mark
FROM student;
SELECT
name
INTO
l_name
FROM
student
WHERE
id=1;

-- show the credits


dbms_output.put_line('Min mark: ' || l_min_mark);
dbms_output.put_line('Max mark: ' || l_max_mark);
dbms_output.put_line('Avg mark: ' || l_average_mark);

-- show customer credit


dbms_output.put_line('student name: ' || l_name);
END;

Tahaluf Training Centre 05 Jul 2021


Comments

PL/SQL comments allow you to describe the purpose of a line or a block of


PL/SQL code.

When compiling the PL/SQL code, the Oracle precompiler ignores comments.

However, you should always use comments to make your code more
readable and to help you and other developers understand it better in the
future.

Tahaluf Training Centre 05 Jul 2021


Comments

PL/SQL has two comment styles: single-line and multi-line comments:

• Single-line comments: A single-line comment starts with a double hyphen


(--) that can appear anywhere on a line and extends to the end of the
line.
-- valued added tax 10%

• Multi-line comments: A multi-line comment starts with a slash-asterisk


( /* ) and ends with an asterisk-slash ( */ ), and can span multiple lines.
/*
This is a multi-line commet
that can span multiple lines
*/

Tahaluf Training Centre 05 Jul 2021


Chapter 08

1 Conditional control

2 Iterative processing with loops

3 Exception

4 Records

5 Cursors

Tahaluf Training Centre 05 Jul 2021


IF Statement

The IF statement allows you to either execute or skip a sequence of


statements, depending on a condition. The IF statement has the three
forms:

• IF THEN
• IF THEN ELSE
• IF THEN ELSIF

Tahaluf Training Centre 05 Jul 2021


IF Statement

IF THEN statement:
The condition is a Boolean expression that always evaluates to TRUE,
FALSE, or NULL.

If the condition evaluates to TRUE, the statements after the THEN


execute. Otherwise, the IF statement does nothing.

Tahaluf Training Centre 05 Jul 2021


IF Statement

Syntax :

IF condition THEN
statements;
END IF;

Tahaluf Training Centre 05 Jul 2021


IF Statement

Example :

DECLARE n_sales NUMBER := 2000000;


BEGIN
IF n_sales > 100000 THEN
DBMS_OUTPUT.PUT_LINE( 'Sales revenue is greater
than 100K ' );
END IF;
END;

Tahaluf Training Centre 05 Jul 2021


IF Statement

IF THEN ELSE statement:

The IF THEN ELSE statement has the following structure:

IF condition THEN
statements;
ELSE
else_statements;
END IF;

Tahaluf Training Centre 05 Jul 2021


IF Statement

Example :

DECLARE
n_sales NUMBER := 300000;
n_commission NUMBER( 10, 2 ) := 0;
BEGIN
IF n_sales > 200000 THEN
n_commission := n_sales * 0.1;
ELSE
n_commission := n_sales * 0.05;
END IF;
END;

Tahaluf Training Centre 05 Jul 2021


IF Statement

IF THEN ELSIF statement:


The following illustrates the structure of the IF THEN ELSIF statement:

IF condition_1 THEN
statements_1
ELSIF condition_2 THEN
statements_2
[ ELSE
else_statements
]
END IF;

Tahaluf Training Centre 05 Jul 2021


IF Statement

Example :
DECLARE
n_sales NUMBER := 300000;
n_commission NUMBER( 10, 2 ) := 0;
BEGIN
IF n_sales > 200000 THEN
n_commission := n_sales * 0.1;
ELSIF n_sales <= 200000 AND n_sales > 100000 THEN
n_commission := n_sales * 0.05;
ELSIF n_sales <= 100000 AND n_sales > 50000 THEN
n_commission := n_sales * 0.03;
ELSE
n_commission := n_sales * 0.02;
END IF;
END;

Tahaluf Training Centre 05 Jul 2021


IF Statement

Nested IF statement:
You can nest an IF statement within another IF statement as shown
below:
IF condition_1 THEN
IF condition_2 THEN
nested_if_statements;
END IF;
ELSE
else_statements;
END IF;

Tahaluf Training Centre 05 Jul 2021


CASE Statement

The CASE statement chooses one sequence of statements to execute


out of many possible sequences.

The CASE statement has two types: simple CASE statement and
searched CASE statement.

Both types of the CASE statements support an optional ELSE clause.

Tahaluf Training Centre 05 Jul 2021


CASE Statement

Simple CASE statement:


A simple CASE statement evaluates a single expression and compares
the result with some values.

The simple CASE statement has the following structure:


CASE selector
WHEN selector_value_1 THEN
statements_1
WHEN selector_value_1 THEN
statement_2
ELSE
else_statements
END CASE;

Tahaluf Training Centre 05 Jul 2021


CASE Statement

DECLARE
c_grade CHAR( 1 );
c_rank VARCHAR2( 20 );
BEGIN
c_grade := 'B';
CASE c_grade
WHEN 'A' THEN
c_rank := 'Excellent' ;
WHEN 'B' THEN
c_rank := 'Very Good' ;
WHEN 'C' THEN
c_rank := 'Good' ;
WHEN 'D' THEN
c_rank := 'Fair' ;
WHEN 'F' THEN
c_rank := 'Poor' ;
ELSE
c_rank := 'No such grade' ;
END CASE;
DBMS_OUTPUT.PUT_LINE( c_rank );
END;

Tahaluf Training Centre 05 Jul 2021


CASE Statement

Searched CASE statement:

The searched CASE statement evaluates multiple Boolean expressions


and executes the sequence of statements associated with the first
condition that evaluates to TRUE.

Tahaluf Training Centre 05 Jul 2021


CASE Statement

The searched CASE statement has the following structure:

CASE
WHEN condition_1 THEN statements_1
WHEN condition_2 THEN statements_2
...
WHEN condition_n THEN statements_n
[ ELSE
else_statements ]
END CASE;]

Tahaluf Training Centre 05 Jul 2021


CASE Statement

DECLARE
n_sales NUMBER;
n_commission NUMBER;
BEGIN
n_sales := 150000;
CASE
WHEN n_sales > 200000 THEN
n_commission := 0.2;
WHEN n_sales >= 100000 AND n_sales < 200000 THEN
n_commission := 0.15;
WHEN n_sales >= 50000 AND n_sales < 100000 THEN
n_commission := 0.1;
WHEN n_sales > 30000 THEN
n_commission := 0.05;
ELSE
n_commission := 0;
END CASE;

DBMS_OUTPUT.PUT_LINE( 'Commission is ' ||


n_commission * 100 || '%'
);
END;

Tahaluf Training Centre 05 Jul 2021


GOTO statement

The GOTO statement allows you to transfer control to a labeled block


or statement. The following illustrates the syntax of the GOTO
statement:

GOTO label_name;

The label_name is the name of a label that identifies the target statement. In
the program, you surround the label name with double enclosing angle
brackets as shown below:
<<label_name>>;

Tahaluf Training Centre 05 Jul 2021


GOTO statement

Tahaluf Training Centre 05 Jul 2021


GOTO statement

BEGIN
GOTO second_message;

<<first_message>>
DBMS_OUTPUT.PUT_LINE( 'Hello' );
GOTO the_end;

<<second_message>>
DBMS_OUTPUT.PUT_LINE( 'PL/SQL GOTO
Demo' );
GOTO first_message;

<<the_end>>
DBMS_OUTPUT.PUT_LINE( 'and good bye...' );

END;

Tahaluf Training Centre 05 Jul 2021


Iterative processing with loops

DECLARE
l_counter NUMBER := 0;
BEGIN
LOOP
l_counter := l_counter + 1;
IF l_counter > 3 THEN
EXIT;
END IF;
dbms_output.put_line( 'Inside loop: ' || l_counter ) ;
END LOOP;
-- control resumes here after EXIT
dbms_output.put_line( 'After loop: ' || l_counter );
END;

Tahaluf Training Centre 05 Jul 2021


FOR LOOP

PL/SQL FOR LOOP executes a sequence of statements a specified


number of times. The PL/SQL FOR LOOP statement has the following
structure:

FOR index IN lower_bound .. upper_bound


LOOP
statements;
END LOOP;

Tahaluf Training Centre 05 Jul 2021


FOR LOOP

BEGIN
FOR l_counter IN 1..5
LOOP
DBMS_OUTPUT.PUT_LINE( l_counter );
END LOOP;
END;

Tahaluf Training Centre 05 Jul 2021


FOR LOOP

DECLARE
l_step PLS_INTEGER := 2;
BEGIN
FOR l_counter IN 1..5 LOOP
dbms_output.put_line (l_counter*l_step);
END LOOP;
END;

Tahaluf Training Centre 05 Jul 2021


FOR LOOP

DECLARE
l_counter PLS_INTEGER := 10;
BEGIN
FOR l_counter IN 1.. 5 loop
DBMS_OUTPUT.PUT_LINE (l_counter);
end loop;
-- after the loop
DBMS_OUTPUT.PUT_LINE (l_counter);
END;

Tahaluf Training Centre 05 Jul 2021


WHILE loop

Here is the syntax for the WHILE loop statement:

WHILE condition
LOOP
statements;
END LOOP;

Tahaluf Training Centre 05 Jul 2021


WHILE loop

DECLARE
n_counter NUMBER := 1;
BEGIN
WHILE n_counter <= 5
LOOP
DBMS_OUTPUT.PUT_LINE( 'Counter : ' ||
n_counter );
n_counter := n_counter + 1;
END LOOP;
END;

Tahaluf Training Centre 05 Jul 2021


FOR LOOP

WHILE loop example terminated by EXIT WHEN statement:

The following example is the same as the one above except that it has
an additional EXITWHEN statement.

Tahaluf Training Centre 05 Jul 2021


WHILE loop

DECLARE
n_counter NUMBER := 1;
BEGIN
WHILE n_counter <= 5
LOOP
DBMS_OUTPUT.PUT_LINE( 'Counter : ' || n_counter );
n_counter := n_counter + 1;
EXIT WHEN n_counter = 3;
END LOOP;
END;

Tahaluf Training Centre 05 Jul 2021


CONTINUE statement

The CONTINUE statement allows you to exit the current loop iteration
and immediately continue on to the next iteration of that loop.

The CONTINUE statement has a simple syntax:

CONTINUE;

Tahaluf Training Centre 05 Jul 2021


CONTINUE statement

Typically, the CONTINUE statement is used within an IF THEN


statement to exit the current loop iteration based on a specified
condition as shown below:

IF condition THEN
CONTINUE;
END IF;

Tahaluf Training Centre 05 Jul 2021


CONTINUE statement

BEGIN
FOR n_index IN 1 .. 10
LOOP
-- skip odd numbers
IF MOD( n_index, 2 ) = 1 THEN
CONTINUE;
END IF;
DBMS_OUTPUT.PUT_LINE( n_index );
END LOOP;
END;

Tahaluf Training Centre 05 Jul 2021


CONTINUE statement

CONTINUE WHEN statement:

The CONTINUE WHEN statement exits the current loop iteration


based on a condition and immediately continue to the next iteration
of that loop.

The syntax of CONTINUE WHEN statement is:

CONTINUE WHEN condition;

Tahaluf Training Centre 05 Jul 2021


CONTINUE statement

BEGIN
FOR n_index IN 1 .. 10
LOOP
-- skip even numbers
CONTINUE
WHEN MOD( n_index, 2 ) = 0;
DBMS_OUTPUT.PUT_LINE( n_index );
END LOOP;
END;

Tahaluf Training Centre 05 Jul 2021


Exception

PL/SQL treats all errors that occur in an anonymous block, procedure,


or function as exceptions.

The exceptions can have different causes such as coding mistakes,


bugs, even hardware failures.

It is not possible to anticipate all potential exceptions, however, you


can write code to handle exceptions to enable the program to
continue running as normal.

Tahaluf Training Centre 05 Jul 2021


Exception

The code that you write to handle exceptions is called an exception


handler.
BEGIN
-- executable section
...
-- exception-handling section
EXCEPTION
WHEN e1 THEN
-- exception_handler1
WHEN e2 THEN
-- exception_handler1
WHEN OTHERS THEN
-- other_exception_handler
END;

Tahaluf Training Centre 05 Jul 2021


Exception

DECLARE
c_id student.id%type := 2;
c_name student.Name%type;

BEGIN
SELECT name, id INTO c_name, c_id
FROM student
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('id: ' || c_id);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such student!');
WHEN others THEN
dbms_output.put_line('Error!');
END;

Tahaluf Training Centre 05 Jul 2021


Records

A PL/SQL record is a composite data structure which consists of


multiple fields; each has its own value. The following picture shows
an example record that includes first name, last name, email, and
phone number:

Tahaluf Training Centre 05 Jul 2021


Records

PL/SQL record helps you simplify your code by shifting from field-
level to record-level operations.

PL/SQL has three types of records: table-based, cursor-based,


programmer-defined.

Before using a record, you must declare it.

DECLARE
record_name table_name%ROWTYPE;

Tahaluf Training Centre 05 Jul 2021


Records

CREATE TABLE persons (


person_id NUMBER GENERATED BY DEFAULT
AS IDENTITY,
first_name VARCHAR2( 50 ) NOT NULL,
last_name VARCHAR2( 50 ) NOT NULL,
primary key (person_id)
);

Tahaluf Training Centre 05 Jul 2021


Records

DECLARE
r_person persons%ROWTYPE;

BEGIN
-- assign values to person record
r_person.person_id := 1;
r_person.first_name := 'John';
r_person.last_name := 'Doe';

-- insert a new person


INSERT INTO persons VALUES r_person;
END;

Tahaluf Training Centre 05 Jul 2021


Records

DECLARE
r_person persons%ROWTYPE;

BEGIN
-- get person data of person id 1
SELECT * INTO r_person
FROM persons
WHERE person_id = 1;

-- change the person's last name


r_person.last_name := 'Smith';

-- update the person


UPDATE persons
SET ROW = r_person
WHERE person_id = r_person.person_id;
END;

Tahaluf Training Centre 05 Jul 2021


Cursors

A cursor is a pointer that points to a result of a query. PL/SQL has two


types of cursors: implicit cursors and explicit cursors.

Tahaluf Training Centre 05 Jul 2021


Implicit cursors

Whenever Oracle executes an SQL statement such as SELECT INTO,


INSERT, UPDATE, and DELETE, it automatically creates an implicit
cursor.

Oracle internally manages the whole execution cycle of implicit


cursors and reveals only the cursor’s information and statuses such
as:
• SQL%ROWCOUNT
• SQL%ISOPEN
• SQL%FOUND
• SQL%NOTFOUND.

Tahaluf Training Centre 05 Jul 2021


Implicit cursors

The implicit cursor is not elegant when the query returns zero or
multiple rows which cause NO_DATA_FOUND or TOO_MANY_ROWS
exception respectively.

Tahaluf Training Centre 05 Jul 2021


Explicit cursors

An explicit cursor is an SELECT statement declared explicitly in the


declaration section of the current block or a package specification.

For an explicit cursor, you have control over its execution cycle from
OPEN, FETCH, and CLOSE.

Oracle defines an execution cycle that executes an SQL statement and


associates a cursor with it.

Tahaluf Training Centre 05 Jul 2021


Explicit cursors

The following illustration shows the execution cycle of an explicit


cursor:

Tahaluf Training Centre 05 Jul 2021


Explicit cursors

Declare a cursor
Before using an explicit cursor, you must declare it in the declaration
section of a block or package as follows:

CURSOR cursor_name IS query;

In this syntax:

• First, specify the name of the cursor after the CURSOR keyword.
• Second, define a query to fetch data after the IS keyword.

Tahaluf Training Centre 05 Jul 2021


Explicit cursors

Open a cursor
Before start fetching rows from the cursor, you must open it. To open
a cursor, you use the following syntax:

OPEN cursor_name;

In this syntax, the cursor_name is the name of the cursor declared in


the declaration section.

Tahaluf Training Centre 05 Jul 2021


Explicit cursors

Fetch from a cursor


The FETCH statement places the contents of the current row into
variables. The syntax of FETCH statement is as follows:

FETCH cursor_name INTO variable_list;

To retrieve all rows in a result set, you need to fetch each row till the
last one.

Tahaluf Training Centre 05 Jul 2021


Explicit cursors

Closing a cursor
After fetching all rows, you need to close the cursor with the CLOSE
statement:

CLOSE cursor_name;

Closing a cursor instructs Oracle to release allocated memory at an


appropriate time.

Tahaluf Training Centre 05 Jul 2021


Explicit Cursor Attributes

A cursor has four attributes to which you can reference in the


following format:

cursor_name%attribute

where cursor_name is the name of the explicit cursor.

Tahaluf Training Centre 05 Jul 2021


Explicit Cursor Attributes

• %ISOPEN
This attribute is TRUE if the cursor is open or FALSE if it is not.

• %FOUND
This attribute has four values:
1. NULL before the first fetch
2. TRUE if a record was fetched successfully
3. FALSE if no row returned
4. INVALID_CURSOR if the cursor is not opened

Tahaluf Training Centre 05 Jul 2021


Explicit Cursor Attributes

• %NOTFOUND
This attribute has four values:
1. NULL before the first fetch
2. FALSE if a record was fetched successfully
3. TRUE if no row returned
4. INVALID_CURSOR if the cursor is not opened

• %ROWCOUNT
The %ROWCOUNT attribute returns the number of rows fetched from
the cursor. If the cursor is not opened, this attribute returns
INVALID_CURSOR.

Tahaluf Training Centre 05 Jul 2021


cursor example

We will use the orders and order_items tables from the sample
database for the demonstration.

Tahaluf Training Centre 05 Jul 2021


cursor example

creates a view that returns the sales revenues by customers:


CREATE VIEW sales AS
SELECT customer_id,
SUM(unit_price * quantity) total,
ROUND(SUM(unit_price * quantity) * 0.05)
credit
FROM order_items
INNER JOIN orders USING (order_id)
WHERE status = 'Shipped'
GROUP BY customer_id;

Tahaluf Training Centre 05 Jul 2021


cursor example

Suppose you need to develop a anonymous block that:

1. Reset credit limits of all customers to zero.


2. Fetch customers sorted by sales in descending order and gives
them new credit limits from a budget of 1 million.

Tahaluf Training Centre 05 Jul 2021


cursor example

The following anonymous block illustrates the logic:

Tahaluf Training Centre 05 Jul 2021


cursor example

In the declaration section, we declare three variables.

The first one is l_budget whose initial value is 1,000,000.

The second variable is an explicit cursor variable named c_sales


whose SELECT statement retrieves data from the sales view:

CURSOR c_sales IS
SELECT * FROM sales
ORDER BY total DESC;

Tahaluf Training Centre 05 Jul 2021


cursor example

In the execution section, we perform the following:

1. First, reset credit limits of all customers to zero using an UPDATE


statement.
2. Second, open the c_sales cursor.
3. Third, fetch each row from the cursor. In each loop iteration, we
update the credit limit and reduced the budget. The loop
terminates when there is no row to fetch or the budget is
exhausted.
4. Finally, close the cursor.

Tahaluf Training Centre 05 Jul 2021


Chapter 09

1 Overview of Stored Procedure

2 Create Stored Procedure

3 Overview of Function

4 Create Function

5 Overview of Package

6 Create Package

Tahaluf Training Centre 05 Jul 2021


Overview of Stored Procedure

A PL/SQL procedure is a reusable unit used to encapsulate a specific


business logic of the application.

Procedure is a named block stored in the Oracle Database.

Syntax

CREATE [OR REPLACE] PROCEDURE procedure_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

Each parameter can be in either IN, OUT, or INOUT mode.

An IN parameter is read only.

It means that if you do not specify the mode for a parameter


explicitly, Oracle will use the IN mode.

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

OUT parameter is writable.

Setting a returned value for the OUT parameter and return it to call a
program.

Note: A procedure ignores the value supplies an OUT parameter.

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

An INOUT parameter is both writable and readable. The procedure


can modify and read it.

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

Example

CREATE OR REPLACE PROCEDURE TahalufTrainees


AS
BEGIN
dbms_output.put_line('Welcome in Tahaluf');
END;

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

Example

EXECUTE TahalufTrainees;

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

Example

EXECUTE TahalufTrainees;

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

DROP Stored Procedure

DROP PROCEDURE procedure-name;

Example

DROP PROCEDURE TahalufTrainees;

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

Example

DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT
number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
Tahaluf Training Centre 05 Jul 2021
Create Stored Procedure

Example

BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' ||
c);
END;

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

Example

DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;

Tahaluf Training Centre 05 Jul 2021


Create Stored Procedure

Example

Tahaluf Training Centre 05 Jul 2021


Overview of Function

Function is a multi-tenant, fully managed, on-demand, highly scalable


and service platform.

It is built on enterprise grade Cloud Infrastructure and powered by


open source engine.

Using Functions to focus on writing code to meet business needs.

Tahaluf Training Centre 05 Jul 2021


Create Function

Example

CREATE OR REPLACE FUNCTION TotalStudent


RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM student;
RETURN total;
END;

Tahaluf Training Centre 05 Jul 2021


Create Function

Example

DECLARE
c number(2);
BEGIN
c := TotalStudent();
dbms_output.put_line('Total no. of student: ' || c);
END;

Tahaluf Training Centre 05 Jul 2021


Create Function

Example

DECLARE
a number;
b number;
c number;
FUNCTION findMax(x number, y number)
RETURN number
IS
z number;
BEGIN

Tahaluf Training Centre 05 Jul 2021


Create Function

Example
IF x > y THEN
z:= x;
RETURN z;
else
z:=y;
return z;
end if;RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;

Tahaluf Training Centre 05 Jul 2021


Overview of Packages

Packages are objects that groups logically related variables, types,


and subprograms.

A package will have two parts:

✓ Package specification.

✓ Package body or definition.

Tahaluf Training Centre 05 Jul 2021


Overview of Packages

1. Public objects: All objects placed in the specification.

2. private object : Any subprogram not in the package specification.

Tahaluf Training Centre 05 Jul 2021


Create Packages

Example

CREATE PACKAGE std_mark AS


PROCEDURE find_mark(s_id student.id%type);
END std_mark;

Tahaluf Training Centre 05 Jul 2021


Create Packages

The package body has the codes for different ways declared in the
package specification.

Private declarations are hidden from the code outside the package.

Tahaluf Training Centre 05 Jul 2021


Create Packages

Package Body Example

CREATE PACKAGE students_marks AS


PROCEDURE student_marks(std_id student.id%TYPE);
END students_marks ;

CREATE OR REPLACE PACKAGE BODY students_marks AS


PROCEDURE student_marks
(std_id student.id%TYPE) IS
BEGIN
DBMS_OUTPUT.PUT_LINE
('Marks ' || std_id);
END;
END students_marks;

Tahaluf Training Centre 05 Jul 2021


Create Packages

Example

CREATE OR REPLACE PACKAGE students_package AS


PROCEDURE addstudent(std_id student.id%type,
std_name student.name%type,
std_mark student.mark%type);
PROCEDURE delstudent(std_id student.id%TYPE);
END students_package;

Tahaluf Training Centre 05 Jul 2021


Create Packages

Example

CREATE OR REPLACE PACKAGE BODY Package_student AS


PROCEDURE addstudent(std_id student.id%type,
std_name student.name%type,
std_mark student.mark%type);
IS
BEGIN
INSERT INTO student (id,name,mark)
VALUES(std_id,std_name,std_mark);
END addstudent;
PROCEDURE delstudent(std_id student.id%TYPE)IS
BEGIN
DELETE FROM student
WHERE id = std_id;
END delstudent;

Tahaluf Training Centre 05 Jul 2021


Create Packages

Example

DECLARE
code student.id%type:= 1;
BEGIN
Package_student.addstudent(20, 'R', 93);
Package_student.addstudent(50, 'M', 93);
Package_student.delstudent(code);
END;

Tahaluf Training Centre 05 Jul 2021


Overview of Triggers

Triggers are written to be executed in response when any of the


following events occurs:

✓ A database manipulation (DML) commands (DELETE, INSERT, or


UPDATE).

✓ A database definition (DDL) commands (CREATE, ALTER, or


DROP).

✓ A database operation (LOGOFF, SERVERERROR, STARTUP, or


SHUTDOWN).

Tahaluf Training Centre 05 Jul 2021


Overview of Triggers

Benefits of Triggers

1. Generate a some of derived column values automatically.

2. Event storing and logging information on table access.

3. Synchronous replication of tables.

4. Imposing security authorizations.

5. Preventing invalid transactions.

6. Enforcing referential integrity.

7. Auditing.

Tahaluf Training Centre 05 Jul 2021


Overview of Triggers

Syntax

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Tahaluf Training Centre 05 Jul 2021


Create Triggers

Example

CREATE TABLE audits (


audit_id NUMBER GENERATED BY DEFAULT
AS IDENTITY PRIMARY KEY,
table_name VARCHAR2(255),
transaction_name VARCHAR2(10),
by_user VARCHAR2(30),
transaction_date DATE
);

Tahaluf Training Centre 05 Jul 2021


Create Triggers

Example

CREATE OR REPLACE TRIGGER student_audit


AFTER
UPDATE OR DELETE
ON student
FOR EACH ROW
DECLARE
l_transaction VARCHAR2(10);
BEGIN
l_transaction := CASE
WHEN UPDATING THEN 'UPDATE'
WHEN DELETING THEN 'DELETE'
END;

Tahaluf Training Centre 05 Jul 2021


Create Triggers

Example

INSERT INTO audits (table_name, transaction_name,


by_user, transaction_date)
VALUES('CUSTOMERS', l_transaction, USER, SYSDATE);
END;

Tahaluf Training Centre 05 Jul 2021


Create Triggers

Example

AFTER UPDATE OR DELETE ON student

UPDATE
student
SET
name= 'Mohammed'
WHERE
id =1;

Tahaluf Training Centre 05 Jul 2021


Create Triggers

Example

SELECT * FROM audits;

Tahaluf Training Centre 05 Jul 2021


Create Triggers

Example

DELETE FROM student


WHERE id = 2;

Tahaluf Training Centre 05 Jul 2021


Create Triggers

Example

SELECT * FROM audits;

Tahaluf Training Centre 05 Jul 2021


Introduction to Statement-level triggers

A statement-level trigger is fired when a trigger occurs on a


table regardless of number of rows are affected.

A statement-level trigger executes once for each transaction.

Tahaluf Training Centre 05 Jul 2021


Introduction to Statement-level triggers

Syntax

CREATE [OR REPLACE] TRIGGER trigger_name


{BEFORE | AFTER } triggering_event
ON table_name
[FOLLOWS | PRECEDES another_trigger]
[ENABLE / DISABLE ]
[WHEN condition]
DECLARE
declaration statements
BEGIN
executable statements
EXCEPTION
exception_handling statements
END;

Tahaluf Training Centre 05 Jul 2021


Create Statement-level triggers

Example

CREATE OR REPLACE TRIGGER customers_credit_trg


BEFORE UPDATE OF credit_limit
ON customers
DECLARE
l_day_of_month NUMBER;
BEGIN
-- determine the transaction type
l_day_of_month := EXTRACT(DAY FROM sysdate);

IF l_day_of_month BETWEEN 28 AND 31 THEN


raise_application_error(-20100,'Cannot
update customer credit from 28th to 31st');
END IF;
END;

Tahaluf Training Centre 05 Jul 2021


Create Statement-level triggers

Example

UPDATE
customers
SET
credit_limit = credit_limit * 110;

Tahaluf Training Centre 05 Jul 2021


INSTEAD OF Triggers

An INSTEAD OF trigger allows to update data in the tables via their


view which cannot be modified directly through DML statements.

Syntax

CREATE [OR REPLACE] TRIGGER trigger_name


INSTEAD OF {INSERT | UPDATE | DELETE}
ON view_name
FOR EACH ROW
BEGIN EXCEPTION ...
END;

Tahaluf Training Centre 05 Jul 2021


INSTEAD OF Triggers

Example

CREATE VIEW vw_customers AS


SELECT
name,
address,
website,
credit_limit,
first_name,
last_name,
email,
phone
FROM
customers
INNER JOIN contacts USING (customer_id);

Tahaluf Training Centre 05 Jul 2021


INSTEAD OF Triggers

Example

INSERT INTO
vw_customers(
name,
address,
website,
credit_limit,
first_name,
last_name,
email,
phone
)

Tahaluf Training Centre 05 Jul 2021


INSTEAD OF Triggers

Example
VALUES(
'Ahmed',
'Irbid',
'Ahmed.com',
2000,
'Ahmed',
'mohammed',
'ahmedmohammed@gmail.com',
'0782944885'
);

Tahaluf Training Centre 05 Jul 2021


INSTEAD OF Triggers

Example

CREATE OR REPLACE TRIGGER new_customer_trg


INSTEAD OF INSERT ON vw_customers
FOR EACH ROW
DECLARE
l_customer_id NUMBER;
BEGIN
-- insert a new customer first
INSERT INTO customers(name, address, website,
credit_limit)
VALUES(:NEW.NAME, :NEW.address, :NEW.website,
:NEW.credit_limit)
RETURNING customer_id INTO l_customer_id;

Tahaluf Training Centre 05 Jul 2021


INSTEAD OF Triggers

Example

-- insert the contact


INSERT INTO contacts(first_name, last_name, email,
phone, customer_id)
VALUES(:NEW.first_name, :NEW.last_name, :NEW.email,
:NEW.phone, l_customer_id);
END;

Tahaluf Training Centre 05 Jul 2021


INSTEAD OF Triggers

Example

INSERT INTO
vw_customers(
name,
address,
website,
credit_limit,
first_name,
last_name,
email,
phone
)

Tahaluf Training Centre 05 Jul 2021


INSTEAD OF Triggers

Example
VALUES(
'Ahmed',
'Irbid',
'Ahmed.com',
2000,
'Ahmed',
'mohammed',
'ahmedmohammed@gmail.com',
'0782944885'
);

Tahaluf Training Centre 05 Jul 2021


INSTEAD OF Triggers

Example

SELECT * FROM customers;

SELECT * FROM contacts;

Tahaluf Training Centre 05 Jul 2021


References

[1]. https://www.javatpoint.com/oracle-delete
[2]. https://www.techonthenet.com/oracle/truncate.php
[3]. https://en.wikibooks.org/wiki/Oracle_Database/SELECT_Statement
[4]. https://ramkedem.com/en/oracle-where-clause/
[5].https://docs.oracle.com/cd/A87860_01/doc/server.817/a85397/operator.
htm
[6]. https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj13658.html
[7]. https://www.javatpoint.com/oracle-group-by-clause
[8]. PL/SQL Procedure: A Step-by-step Guide to Create a Procedure
(oracletutorial.com)
[9]. Oracle INSTEAD OF Triggers By Practical Examples (oracletutorial.com)
[10]. https://www.studytonight.com/dbms/overview-of-dbms.php

Tahaluf Training Centre 05 Jul 2021


References

[11]. https://strolve.com/what-is-software-development-life-cycle-sdlc/
[12]. https://ecomputernotes.com/database-system/rdbms/phases-of-design-
methodology
[13]. https://www.oracle-dba-online.com/introduction_to_oracle.htm
[14]. https://www.oracletutorial.com/getting-started/what-is-oracle-database/
[15]. https://docs.oracle.com/database/121/SQLRF/sql_elements001.htm#SQLRF0021

Tahaluf Training Centre 05 Jul 2021

You might also like