SlideShare a Scribd company logo
1 of 18
Download to read offline
ORACLE
v Oracle is an Object-Relational Database Management System. It is the leading RDBMS
vendor worldwide. Nearly half of RDBMS worldwide market is owned by Oracle.
ORACLE DATABASE
v Every Oracle Database Contains Logical and Physical Structures. Logical Structures are
table spaces, Schema objects, extents and segments. Physical Structures are Data files,
Redo Log Files, and Control File.
v A database is divided into logical storage units called table spaces, which group related
logical structures together. Each Table space in turn consists of one are more data files.
v In relational database system all the information is stored in form of tables. A table
consists of rows and columns
v All the tables and other objects in Oracle are stored in table space logically, but physically
they are stored in the data files associated with the table space.
v Every Oracle database has a set of two or more redo log files. The set of redo log files for
a database is collectively known as the database's redo log. A redo log is made up of redo
entries (also called redo records).
v The primary function of the redo log is to record all changes made to data. If a failure
prevents modified data from being permanently written to the data files, the changes can
be obtained from the redo log so work is never lost.
v Every Oracle database has a control file. A control file contains the database name and
locations of all data files and redo log files.
v Every Oracle database also has a Parameter File. Parameter file contains the name of the
Database, Memory Settings and Location of Control file.
SQL
v SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in relational database.
v SQL is the standard language for Relation Database System. All relational database
management systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and
SQL Server use SQL as standard database language.
History:
¸ 1970 -- Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational
databases. He described a relational model for databases.
¸ 1974 -- Structured Query Language appeared.
¸ 1978 -- IBM worked to develop Codd's ideas and released a product named System/R.
¸ 1986 -- IBM developed the first prototype of relational database and standardized by
ANSI. The first relational database was released by Relational Software and its later
becoming Oracle.
SQL Process:
v When you are executing an SQL command for any RDBMS, the system determines
the best way to carry out your request and SQL engine figures out how to interpret the
task.
v There are various components included in the process. These components are Query
Dispatcher, Optimization Engines, Classic Query Engine and SQL Query Engine, etc.
Classic query engine handles all non-SQL queries but SQL query engine won't handle
logical files.
v Following is a simple diagram showing SQL Architecture:
SQL Commands:
v The standard SQL commands to interact with relational databases are CREATE,
SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be
classified into groups based on their nature:
DDL - Data Definition Language:
v DDL deals with database schemas and descriptions, of how the data should reside in
the database
Command Description
CREATE To create database and its objects like (table, index, view, store
procedure, function, and trigger
ALTER Alters the structure of existing database
DROP Delete objects from database
TRUNCATE Remove all records from a table including all spaces allocated for the
records are removed
COMMENT Add commends to the data dictionary
RENAME Rename an object
DML - Data Manipulation Language:
v DML deals with data manipulation and includes most common SQL statements such
SELECT, INSERT,UPDATE, DELETE etc, and it is used to store, modify, retrieve, delete
and update data in database
Command Description
SELECT Retrieves certain records from one or more tables
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records
DCL - Data Control Language:
v DCL which includes commands such as GRANT, and mostly concerned with rights,
permissions and other controls of the database system.
Command Description
GRANT Gives a privilege to user
REVOKE Takes back privileges granted from user
TCL : Transaction Control Language
v TCL deals with Transaction within a database
INTEGRITY CONSTRAINTS (KEYS)
v A key is a single or combination of multiple fields in a table. It is used to fetch
or retrieve records/data-rows from data table according to the condition/requirement. Keys
are also used to create relationship among different database tables or views.
Types of SQL Keys
v We have following types of keys in SQL which are used to fetch records
from tables and to make relationship among tables or views.
Command Description
COMMIT Commits a transaction
ROLLBACK
Rollback a transaction in case of
any error occurs
SAVEPOINT
To rollback the transaction make in
points within groups
SET TRANSACTION
Specify characteristics for the
transaction
1. Super key 2. Candidate key
3. Primary key 4. Foreign key
1. Super Key
v Super key is a set of one or more than one keys that can be used to identify a
record uniquely in a table.
v Example: Primary key, Unique key, Alternate key are subset of Super Keys.
2. Candidate Key
v A Candidate Key is a set of one or more fields/columns that can identify a
record uniquely in a table. There can be multiple Candidate Keys in one table. Each
Candidate Key can work as Primary Key.
Example: In below diagram ID, RollNo and EnrollNo are Candidate Keys
since all these three fields can be work as Primary Key.
3. Primary Key
v The PRIMARY KEY constraint uniquely identifies each record in a database
table.
v Primary keys must contain UNIQUE values.
v A primary key column cannot contain NULL values.
v Most tables should have a primary key, and each table can have only ONE
primary key.
4. Foreign Key
v A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
v Foreign Key is a field in database table that is Primary key in another table.
It can accept multiple null, duplicate values.
v Example : We can have a DeptID column in the Employee table which is
pointing to DeptID column in a department table where it a primary key.
Example program
PL/SQL
ÿ PL/SQL is a combination of SQL along with the procedural features of programming
languages. It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL.
ÿ PL/SQL is one of three key programming languages embedded in the Oracle
Database, along with SQL itself and Java.
ÿ The PL/SQL programming language was developed by Oracle Corporation in the late
1980s as procedural extension language for SQL and the Oracle relational database.
Following are notable facts about PL/SQL:
¸ PL/SQL is a completely portable, high-performance transaction-processing
language.
¸ PL/SQL provides a built-in interpreted and OS independent programming
environment.
¸ PL/SQL can also directly be called from the command-line SQL*Plus interface.
¸ Direct call can also be made from external programming language calls to
database.
¸ PL/SQL's general syntax is based on that of ADA and Pascal programming
language.
¸ Apart from Oracle, PL/SQL is available in TimesTen in-memory database and
IBM DB2.
Features of PL/SQL
PL/SQL has the following features:
¸ PL/SQL is tightly integrated with SQL.
¸ It offers extensive error checking.
¸ It offers numerous data types.
¸ It offers a variety of programming structures.
¸ It supports structured programming through functions and procedures.
¸ It supports object-oriented programming.
¸ It supports developing web applications and server pages.
Advantages of PL/SQL
PL/SQL has the following advantages:
¸ SQL is the standard database language and PL/SQL is strongly integrated with SQL.
PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations
and transaction control from PL/SQL block. Dynamic SQL is SQL allows embedding
DDL statements in PL/SQL blocks.
¸ PL/SQL allows sending an entire block of statements to the database at one time. This
reduces network traffic and provides high performance for the applications.
¸ PL/SQL gives high productivity to programmers as it can query, transform, and
update data in a database.
¸ PL/SQL saves time on design and debugging by strong features, such as exception
handling, encapsulation, data hiding, and object-oriented data types.
¸ Applications written in PL/SQL are fully portable.
¸ PL/SQL provides high security level.
¸ PL/SQL provides access to predefined SQL packages.
¸ PL/SQL provides support for Object-Oriented Programming.
¸ PL/SQL provides support for Developing Web Applications and Server Pages.
PL/SQL block structure
v PL/SQL program units organize the code into blocks. A block without a name is
known as an anonymous block. The anonymous block is the simplest unit in PL/SQL.
It is called anonymous block because it is not saved in the Oracle database.
v An anonymous block is an only one-time use and useful in certain situations such as
creating test units. The following illustrates anonymous block syntax:
Let’s examine the PL/SQL block structure in greater detail.
PL/SQL Block Structure
DECLARE
v Variables and constants are declared, initialized within this section.
v Variables and Constants: In this block, declare and initialize variables (and constants).
You must have to declare variables and constants in declarative block before
referencing them in procedural statement.
v Declare Variables and Assigning values: You can define variable name, data type of a
variable and its size. Date type can be: CHAR, VARCHAR2, DATE, NUMBER, INT
or any other.
v Declare Constants and Assigning values: Constants are declared same as variable but
you have to add the CONSTANT keyword before defining data type. Once you define
a constant value you can't change the value.
BEGIN
v BEGIN block is procedural statement block which will implement the actual
programming logic. This section contains conditional statements (if...else), looping
statements (for, while) and Branching Statements (goto) etc.
EXCEPTION
v PL/SQL easily detects user defined or predefined error condition. PL/SQL is famous
for handling errors in smart way by giving suitable user friendly messages. Errors can
be rise due to wrong syntax, bad logical or not passing a validation rules.
You can also define exception in your declarative block and later you can execute it by
RAISE statement.
A PL/SQL function is same as a procedure except that it returns a value. Therefore, all the
discussions of the previous chapter are true for functions too.
PROCEDURE
v A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the
'Modular design'.
v A subprogram can be invoked by another subprogram or program which is called the
calling program.
DECLARE
check_exist EXCEPTION; -- declare exception type
...
BEGIN
....
RAISE check_exist; -- Raise exception
....
EXCEPTION
WHEN check_exist THEN -- execute raise exception
.....
END;
/
PL/SQL provides two kinds of subprograms:
¸ Functions: these subprograms return a single value, mainly used to compute and
return a value.
¸ Procedures: these subprograms do not return a value directly, mainly used to perform
an action.
Creating a Procedure
v A procedure is created with the CREATE OR REPLACE PROCEDURE statement.
The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as
follows:
Where,
¸ procedure-name specifies the name of the procedure.
¸ [OR REPLACE] option allows modifying an existing procedure.
¸ The optional parameter list contains name, mode and types of the parameters. IN
represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
¸ procedure-body contains the executable part.
¸ The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
Example program
FUNCTION
v A PL/SQL function is same as a procedure except that it returns a value.
Creating a Function
v A standalone function is created using the CREATE FUNCTION statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as
follows:
CREATE [OR REPLACE] FUNCTION function_name [(parameter_name
[IN | OUT | IN OUT] type [, ...])] RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS |
AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
¸ function-name specifies the name of the function.
¸ [OR REPLACE] option allows modifying an existing function.
¸ The optional parameter list contains name, mode and types of the parameters. IN
represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
¸ The function must contain a return statement.
¸ RETURN clause specifies that data type you are going to return from the function.
¸ function-body contains the executable part.
¸ The AS keyword is used instead of the IS keyword for creating a standalone function.
Calling a Function
v While creating a function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task. When a
program calls a function, program control is transferred to the called function.
v A called function performs defined task and when its return statement is executed or
when it last end statement is reached, it returns program control back to the main
program.
v To call a function you simply need to pass the required parameters along with
function name and if function returns a value then you can store returned value.
Following program calls the function totalCustomers from an anonymous block:
When the above code is executed at SQL prompt, it produces the following result:
Example program
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
Total no. of Customers: 6
PL/SQL procedure successfully completed.
SQL CURSOR
v A cursor is a temporary work area created in the system memory when a SQL
statement is executed.
v A cursor contains information on a select statement and the rows of data accessed
by it. A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor.
v This temporary work area is used to store the data retrieved from the database, and
manipulate this data.
v A cursor can hold more than one row, but can process only one row at a time. The
set of rows the cursor holds is called the active set.
v A cursor is basically a set of rows that you can access one at a time.
v These are created by default when DML statements like, INSERT, UPDATE, and
DELETE statements are executed. They are also created when a SELECT
statement that returns just one row is executed.
v A cursor holds the rows (one or more) returned by a SQL statement. The set of
rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the
rows returned by the SQL statement, one at a time. There are two types of cursors:
¸ Implicit cursors
¸ Explicit cursors
Implicit Cursors
v Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement. Programmers cannot control
the implicit cursors and the information in it.
v When you execute DML statements like Delete, Insert, Update and Select statements,
implicit statements are created to process these statements. Oracle provides few attributes
called as implicit cursor attributes to check the status of DML operations.
v The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and
%ISOPEN. The values of the cursor attributes always refer to the most recently executed
SQL statement. Before Oracle opens the SQL cursor, the implicit cursor attributes yield
NULL.
Attribute Description
%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected
one or more rows or a SELECT INTO statement returned one or more
rows. Otherwise, it returns FALSE.
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT,
UPDATE, or DELETE statement affected no rows, or a SELECT INTO
statement returned no rows. Otherwise, it returns FALSE
%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the
SQL cursor automatically after executing its associated SQL statement.
%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or
DELETE statement, or returned by a SELECT INTO statement.
Explicit Cursors
v Explicit cursors are programmer defined cursors for gaining more control over the
context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one
row.
The syntax for creating an explicit cursor is :
Working with an explicit cursor involves four steps:
¸ Declaring the cursor for initializing in the memory
¸ Opening the cursor for allocating memory
¸ Fetching the cursor for retrieving data
¸ Closing the cursor to release allocated memory
Declaring the Cursor
v Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example:
Opening the Cursor
v Opening the cursor allocates memory for the cursor and makes it ready for fetching
the rows returned by the SQL statement into it. For example, we will open above-
defined cursor as follows:
Fetching the Cursor
v Fetching the cursor involves accessing one row at a time. For example we will fetch
rows from the above-opened cursor as follows:
CURSOR c_customers IS
SELECT id, name, address FROM customers;
OPEN c_customers;
CURSOR cursor_name IS select_statement;
FETCH c_customers INTO c_id, c_name, c_addr;
Closing the Cursor
v Closing the cursor means releasing the allocated memory. For example, we will close
above-opened cursor as follows:
Example program
TRIGGER
v Triggers are stored programs, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the
following events:
¸ A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
¸ A database definition (DDL) statement (CREATE, ALTER, or DROP).
¸ A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
v Triggers could be defined on the table, view, schema, or database with which the
event is associated.
Benefits of Triggers: Triggers can be written for the following purposes:
¸ Generating some derived column values automatically
¸ Enforcing referential integrity
¸ Event logging and storing information on table access
¸ Auditing
¸ Synchronous replication of tables
¸ Imposing security authorizations
¸ Preventing invalid transactions
Creating Triggers:
The syntax for creating a trigger is:
CLOSE c_customers;
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
Where,
ÿ CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing
trigger with the trigger_name.
ÿ {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be
executed. The INSTEAD OF clause is used for creating trigger on a view.
ÿ {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
ÿ [OF col_name]: This specifies the column name that would be updated.
ÿ [ON table_name]: This specifies the name of the table associated with the trigger.
ÿ [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old
values for various DML statements, like INSERT, UPDATE, and DELETE.
ÿ [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
ÿ WHEN (condition): This provides a condition for rows for which the trigger would
fire. This clause is valid only for row level triggers.
Example Program
Here following two points are important and should be noted carefully:
ÿ OLD and NEW references are not available for table level triggers, rather you can use
them for record level triggers.
ÿ If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
ÿ Above trigger has been written in such a way that it will fire before any DELETE or
INSERT or UPDATE operation on the table, but you can write your trigger on a
single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using DELETE operation on the table.
EXCEPTION HANDLING
v An error condition during a program execution is called an exception in PL/SQL.
PL/SQL supports programmers to catch such conditions using EXCEPTION block in
the program and an appropriate action is taken against the error condition. There are
two types of exceptions:
¸ System-defined exceptions
¸ User-defined exceptions
Syntax for Exception Handling
The General Syntax for exception handling is as follows. Here you can list down as many as
exceptions you want to handle. The default exception will be handled using WHEN others
THEN:
Raising Exceptions
v Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
command RAISE. Following is the simple syntax of raising an exception:
v You can use above syntax in raising Oracle standard exception or any user-defined
exception. Next section will give you an example on raising user-defined exception,
similar way you can raise Oracle standard exceptions as well.
Example Program
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........... ...........
WHEN others THEN
exception3-handling-statements
END;
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
User-defined Exceptions
v PL/SQL allows you to define your own exceptions according to the need of your
program. A user-defined exception must be declared and then raised explicitly, using
either a RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is:
Pre-defined Exceptions
v PL/SQL provides many pre-defined exceptions, which are executed when any database
rule is violated by a program. For example, the predefined exception
NO_DATA_FOUND is raised when a SELECT INTO statement returns no rows. The
following table lists few of the important pre-defined exceptions:
Exception Description
LOGIN_DENIED
It is raised when s program attempts to log on to the
database with an invalid username or password.
NO_DATA_FOUND
It is raised when a SELECT INTO statement returns no
rows.
NOT_LOGGED_ON
It is raised when a database call is issued without being
connected to the database.
PROGRAM_ERROR It is raised when PL/SQL has an internal problem.
VALUE_ERROR
It is raised when an arithmetic, conversion, truncation, or
size-constraint error occurs.
ZERO_DIVIDE
It is raised when an attempt is made to divide a number by
zero.
DECLARE
my-exception EXCEPTION;
RELATIONAL QUERY LANGUAGES
v Relational query languages use relational algebra to break the user
requests and instruct the DBMS to execute the requests. It is the language by which user
communicates with the database. These relational query languages can be procedural or non-
procedural.
Procedural Query Language
v A procedural query language will have set of queries instructing the
DBMS to perform various transactions in the sequence to meet the user request.
v For example, get_CGPA procedure will have various queries to get the
marks of student in each subject, calculate the total marks, and then decide the CGPA based
on his total marks.
v This procedural query language tells the database what is required
from the database and how to get them from the database. Relational algebra is a procedural
query language.
Non-Procedural Query Language
v Non-procedural queries will have single query on one or more tables to
get result from the database. For example, get the name and address of the student with
particular ID will have single query on STUDENT table. Relational Calculus is a non
procedural language which informs what to do with the tables, but doesn’t inform how to
accomplish this.
v These query languages basically will have queries on tables in the
database. In the relational database, a table is known as relation.
v Records / rows of the table are referred as tuples. Columns of the table
are also known as attributes. All these names are used interchangeably in relational database.

More Related Content

What's hot

Oracle 11G Development Training noida Delhi NCR
Oracle 11G Development Training noida Delhi NCROracle 11G Development Training noida Delhi NCR
Oracle 11G Development Training noida Delhi NCRShri Prakash Pandey
 
Sql server lesson3
Sql server lesson3Sql server lesson3
Sql server lesson3Ala Qunaibi
 
Lecture 2 - Using XML for Many Purposes
Lecture 2 - Using XML for Many PurposesLecture 2 - Using XML for Many Purposes
Lecture 2 - Using XML for Many Purposesphanleson
 
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...Massimo Cenci
 
Introduction DBMS, RDBMS and SQL
Introduction DBMS, RDBMS and SQLIntroduction DBMS, RDBMS and SQL
Introduction DBMS, RDBMS and SQLMurageppa-QA
 
Data Warehouse and Business Intelligence - Recipe 1
Data Warehouse and Business Intelligence - Recipe 1Data Warehouse and Business Intelligence - Recipe 1
Data Warehouse and Business Intelligence - Recipe 1Massimo Cenci
 
Concepts of NonStop SQL/MX: Part 4 - Storage.
Concepts of NonStop SQL/MX: Part 4 - Storage.Concepts of NonStop SQL/MX: Part 4 - Storage.
Concepts of NonStop SQL/MX: Part 4 - Storage.Frans Jongma
 
Intro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionIntro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionMedhat Dawoud
 
Oracle11gdevtrainingindelhincr
Oracle11gdevtrainingindelhincrOracle11gdevtrainingindelhincr
Oracle11gdevtrainingindelhincrducat1989
 

What's hot (19)

Atl aug99 gltech
Atl aug99 gltechAtl aug99 gltech
Atl aug99 gltech
 
Oracle 11G Development Training noida Delhi NCR
Oracle 11G Development Training noida Delhi NCROracle 11G Development Training noida Delhi NCR
Oracle 11G Development Training noida Delhi NCR
 
Sql - Structured Query Language
Sql - Structured Query LanguageSql - Structured Query Language
Sql - Structured Query Language
 
Sql server lesson3
Sql server lesson3Sql server lesson3
Sql server lesson3
 
Xmll
XmllXmll
Xmll
 
Lecture 2 - Using XML for Many Purposes
Lecture 2 - Using XML for Many PurposesLecture 2 - Using XML for Many Purposes
Lecture 2 - Using XML for Many Purposes
 
SQL/MED and PostgreSQL
SQL/MED and PostgreSQLSQL/MED and PostgreSQL
SQL/MED and PostgreSQL
 
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
 
Full xml
Full xmlFull xml
Full xml
 
paper about xml
paper about xmlpaper about xml
paper about xml
 
Introduction DBMS, RDBMS and SQL
Introduction DBMS, RDBMS and SQLIntroduction DBMS, RDBMS and SQL
Introduction DBMS, RDBMS and SQL
 
Database Presentation
Database PresentationDatabase Presentation
Database Presentation
 
Data Warehouse and Business Intelligence - Recipe 1
Data Warehouse and Business Intelligence - Recipe 1Data Warehouse and Business Intelligence - Recipe 1
Data Warehouse and Business Intelligence - Recipe 1
 
PHP XML
PHP XMLPHP XML
PHP XML
 
XML Bible
XML BibleXML Bible
XML Bible
 
Concepts of NonStop SQL/MX: Part 4 - Storage.
Concepts of NonStop SQL/MX: Part 4 - Storage.Concepts of NonStop SQL/MX: Part 4 - Storage.
Concepts of NonStop SQL/MX: Part 4 - Storage.
 
D B M S Animate
D B M S AnimateD B M S Animate
D B M S Animate
 
Intro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionIntro to T-SQL – 2nd session
Intro to T-SQL – 2nd session
 
Oracle11gdevtrainingindelhincr
Oracle11gdevtrainingindelhincrOracle11gdevtrainingindelhincr
Oracle11gdevtrainingindelhincr
 

Similar to Oracle Introduction

Similar to Oracle Introduction (20)

Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
 
DEE 431 Introduction to Mysql Slide 3
DEE 431 Introduction to Mysql Slide 3DEE 431 Introduction to Mysql Slide 3
DEE 431 Introduction to Mysql Slide 3
 
Pl sql content
Pl sql contentPl sql content
Pl sql content
 
DATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMDATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEM
 
Database Management Lab -SQL Queries
Database Management Lab -SQL Queries Database Management Lab -SQL Queries
Database Management Lab -SQL Queries
 
Sqlite
SqliteSqlite
Sqlite
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
Oracle SQL Part1
Oracle SQL Part1Oracle SQL Part1
Oracle SQL Part1
 
PHP Oracle
PHP OraclePHP Oracle
PHP Oracle
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdf
 
Sql project ..
Sql project ..Sql project ..
Sql project ..
 
SQL for interview
SQL for interviewSQL for interview
SQL for interview
 
Intro
IntroIntro
Intro
 
sql-commands.pdf
sql-commands.pdfsql-commands.pdf
sql-commands.pdf
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql commands
Sql commandsSql commands
Sql commands
 

Recently uploaded

Forest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are importantForest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are importantadityabhardwaj282
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRlizamodels9
 
Welcome to GFDL for Take Your Child To Work Day
Welcome to GFDL for Take Your Child To Work DayWelcome to GFDL for Take Your Child To Work Day
Welcome to GFDL for Take Your Child To Work DayZachary Labe
 
Twin's paradox experiment is a meassurement of the extra dimensions.pptx
Twin's paradox experiment is a meassurement of the extra dimensions.pptxTwin's paradox experiment is a meassurement of the extra dimensions.pptx
Twin's paradox experiment is a meassurement of the extra dimensions.pptxEran Akiva Sinbar
 
Neurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trNeurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trssuser06f238
 
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tantaDashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tantaPraksha3
 
Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫qfactory1
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfSwapnil Therkar
 
‏‏VIRUS - 123455555555555555555555555555555555555555
‏‏VIRUS -  123455555555555555555555555555555555555555‏‏VIRUS -  123455555555555555555555555555555555555555
‏‏VIRUS - 123455555555555555555555555555555555555555kikilily0909
 
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptxRESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptxFarihaAbdulRasheed
 
insect anatomy and insect body wall and their physiology
insect anatomy and insect body wall and their  physiologyinsect anatomy and insect body wall and their  physiology
insect anatomy and insect body wall and their physiologyDrAnita Sharma
 
Temporomandibular joint Muscles of Mastication
Temporomandibular joint Muscles of MasticationTemporomandibular joint Muscles of Mastication
Temporomandibular joint Muscles of Masticationvidulajaib
 
Harmful and Useful Microorganisms Presentation
Harmful and Useful Microorganisms PresentationHarmful and Useful Microorganisms Presentation
Harmful and Useful Microorganisms Presentationtahreemzahra82
 
Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024AyushiRastogi48
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxNandakishor Bhaurao Deshmukh
 
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...lizamodels9
 
Cytokinin, mechanism and its application.pptx
Cytokinin, mechanism and its application.pptxCytokinin, mechanism and its application.pptx
Cytokinin, mechanism and its application.pptxVarshiniMK
 

Recently uploaded (20)

Forest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are importantForest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are important
 
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort ServiceHot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
 
Welcome to GFDL for Take Your Child To Work Day
Welcome to GFDL for Take Your Child To Work DayWelcome to GFDL for Take Your Child To Work Day
Welcome to GFDL for Take Your Child To Work Day
 
Twin's paradox experiment is a meassurement of the extra dimensions.pptx
Twin's paradox experiment is a meassurement of the extra dimensions.pptxTwin's paradox experiment is a meassurement of the extra dimensions.pptx
Twin's paradox experiment is a meassurement of the extra dimensions.pptx
 
Neurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trNeurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 tr
 
Engler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomyEngler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomy
 
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tantaDashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
 
Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
 
‏‏VIRUS - 123455555555555555555555555555555555555555
‏‏VIRUS -  123455555555555555555555555555555555555555‏‏VIRUS -  123455555555555555555555555555555555555555
‏‏VIRUS - 123455555555555555555555555555555555555555
 
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptxRESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
 
insect anatomy and insect body wall and their physiology
insect anatomy and insect body wall and their  physiologyinsect anatomy and insect body wall and their  physiology
insect anatomy and insect body wall and their physiology
 
Temporomandibular joint Muscles of Mastication
Temporomandibular joint Muscles of MasticationTemporomandibular joint Muscles of Mastication
Temporomandibular joint Muscles of Mastication
 
Harmful and Useful Microorganisms Presentation
Harmful and Useful Microorganisms PresentationHarmful and Useful Microorganisms Presentation
Harmful and Useful Microorganisms Presentation
 
Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
 
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
 
Cytokinin, mechanism and its application.pptx
Cytokinin, mechanism and its application.pptxCytokinin, mechanism and its application.pptx
Cytokinin, mechanism and its application.pptx
 

Oracle Introduction

  • 1. ORACLE v Oracle is an Object-Relational Database Management System. It is the leading RDBMS vendor worldwide. Nearly half of RDBMS worldwide market is owned by Oracle. ORACLE DATABASE v Every Oracle Database Contains Logical and Physical Structures. Logical Structures are table spaces, Schema objects, extents and segments. Physical Structures are Data files, Redo Log Files, and Control File. v A database is divided into logical storage units called table spaces, which group related logical structures together. Each Table space in turn consists of one are more data files. v In relational database system all the information is stored in form of tables. A table consists of rows and columns v All the tables and other objects in Oracle are stored in table space logically, but physically they are stored in the data files associated with the table space.
  • 2. v Every Oracle database has a set of two or more redo log files. The set of redo log files for a database is collectively known as the database's redo log. A redo log is made up of redo entries (also called redo records). v The primary function of the redo log is to record all changes made to data. If a failure prevents modified data from being permanently written to the data files, the changes can be obtained from the redo log so work is never lost. v Every Oracle database has a control file. A control file contains the database name and locations of all data files and redo log files. v Every Oracle database also has a Parameter File. Parameter file contains the name of the Database, Memory Settings and Location of Control file. SQL v SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in relational database. v SQL is the standard language for Relation Database System. All relational database management systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL as standard database language. History: ¸ 1970 -- Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational databases. He described a relational model for databases. ¸ 1974 -- Structured Query Language appeared. ¸ 1978 -- IBM worked to develop Codd's ideas and released a product named System/R. ¸ 1986 -- IBM developed the first prototype of relational database and standardized by ANSI. The first relational database was released by Relational Software and its later becoming Oracle. SQL Process: v When you are executing an SQL command for any RDBMS, the system determines the best way to carry out your request and SQL engine figures out how to interpret the task. v There are various components included in the process. These components are Query Dispatcher, Optimization Engines, Classic Query Engine and SQL Query Engine, etc. Classic query engine handles all non-SQL queries but SQL query engine won't handle logical files. v Following is a simple diagram showing SQL Architecture:
  • 3. SQL Commands: v The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into groups based on their nature:
  • 4. DDL - Data Definition Language: v DDL deals with database schemas and descriptions, of how the data should reside in the database Command Description CREATE To create database and its objects like (table, index, view, store procedure, function, and trigger ALTER Alters the structure of existing database DROP Delete objects from database TRUNCATE Remove all records from a table including all spaces allocated for the records are removed COMMENT Add commends to the data dictionary RENAME Rename an object DML - Data Manipulation Language: v DML deals with data manipulation and includes most common SQL statements such SELECT, INSERT,UPDATE, DELETE etc, and it is used to store, modify, retrieve, delete and update data in database Command Description SELECT Retrieves certain records from one or more tables INSERT Creates a record UPDATE Modifies records DELETE Deletes records
  • 5. DCL - Data Control Language: v DCL which includes commands such as GRANT, and mostly concerned with rights, permissions and other controls of the database system. Command Description GRANT Gives a privilege to user REVOKE Takes back privileges granted from user TCL : Transaction Control Language v TCL deals with Transaction within a database INTEGRITY CONSTRAINTS (KEYS) v A key is a single or combination of multiple fields in a table. It is used to fetch or retrieve records/data-rows from data table according to the condition/requirement. Keys are also used to create relationship among different database tables or views. Types of SQL Keys v We have following types of keys in SQL which are used to fetch records from tables and to make relationship among tables or views. Command Description COMMIT Commits a transaction ROLLBACK Rollback a transaction in case of any error occurs SAVEPOINT To rollback the transaction make in points within groups SET TRANSACTION Specify characteristics for the transaction
  • 6. 1. Super key 2. Candidate key 3. Primary key 4. Foreign key 1. Super Key v Super key is a set of one or more than one keys that can be used to identify a record uniquely in a table. v Example: Primary key, Unique key, Alternate key are subset of Super Keys. 2. Candidate Key v A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key. Example: In below diagram ID, RollNo and EnrollNo are Candidate Keys since all these three fields can be work as Primary Key. 3. Primary Key v The PRIMARY KEY constraint uniquely identifies each record in a database table. v Primary keys must contain UNIQUE values. v A primary key column cannot contain NULL values. v Most tables should have a primary key, and each table can have only ONE primary key. 4. Foreign Key v A FOREIGN KEY in one table points to a PRIMARY KEY in another table. v Foreign Key is a field in database table that is Primary key in another table. It can accept multiple null, duplicate values. v Example : We can have a DeptID column in the Employee table which is pointing to DeptID column in a department table where it a primary key. Example program
  • 7. PL/SQL ÿ PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL. ÿ PL/SQL is one of three key programming languages embedded in the Oracle Database, along with SQL itself and Java. ÿ The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as procedural extension language for SQL and the Oracle relational database. Following are notable facts about PL/SQL: ¸ PL/SQL is a completely portable, high-performance transaction-processing language. ¸ PL/SQL provides a built-in interpreted and OS independent programming environment. ¸ PL/SQL can also directly be called from the command-line SQL*Plus interface. ¸ Direct call can also be made from external programming language calls to database. ¸ PL/SQL's general syntax is based on that of ADA and Pascal programming language. ¸ Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2. Features of PL/SQL PL/SQL has the following features: ¸ PL/SQL is tightly integrated with SQL. ¸ It offers extensive error checking. ¸ It offers numerous data types. ¸ It offers a variety of programming structures. ¸ It supports structured programming through functions and procedures. ¸ It supports object-oriented programming. ¸ It supports developing web applications and server pages. Advantages of PL/SQL PL/SQL has the following advantages: ¸ SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and transaction control from PL/SQL block. Dynamic SQL is SQL allows embedding DDL statements in PL/SQL blocks. ¸ PL/SQL allows sending an entire block of statements to the database at one time. This reduces network traffic and provides high performance for the applications.
  • 8. ¸ PL/SQL gives high productivity to programmers as it can query, transform, and update data in a database. ¸ PL/SQL saves time on design and debugging by strong features, such as exception handling, encapsulation, data hiding, and object-oriented data types. ¸ Applications written in PL/SQL are fully portable. ¸ PL/SQL provides high security level. ¸ PL/SQL provides access to predefined SQL packages. ¸ PL/SQL provides support for Object-Oriented Programming. ¸ PL/SQL provides support for Developing Web Applications and Server Pages. PL/SQL block structure v PL/SQL program units organize the code into blocks. A block without a name is known as an anonymous block. The anonymous block is the simplest unit in PL/SQL. It is called anonymous block because it is not saved in the Oracle database. v An anonymous block is an only one-time use and useful in certain situations such as creating test units. The following illustrates anonymous block syntax: Let’s examine the PL/SQL block structure in greater detail. PL/SQL Block Structure DECLARE v Variables and constants are declared, initialized within this section. v Variables and Constants: In this block, declare and initialize variables (and constants). You must have to declare variables and constants in declarative block before referencing them in procedural statement.
  • 9. v Declare Variables and Assigning values: You can define variable name, data type of a variable and its size. Date type can be: CHAR, VARCHAR2, DATE, NUMBER, INT or any other. v Declare Constants and Assigning values: Constants are declared same as variable but you have to add the CONSTANT keyword before defining data type. Once you define a constant value you can't change the value. BEGIN v BEGIN block is procedural statement block which will implement the actual programming logic. This section contains conditional statements (if...else), looping statements (for, while) and Branching Statements (goto) etc. EXCEPTION v PL/SQL easily detects user defined or predefined error condition. PL/SQL is famous for handling errors in smart way by giving suitable user friendly messages. Errors can be rise due to wrong syntax, bad logical or not passing a validation rules. You can also define exception in your declarative block and later you can execute it by RAISE statement. A PL/SQL function is same as a procedure except that it returns a value. Therefore, all the discussions of the previous chapter are true for functions too. PROCEDURE v A subprogram is a program unit/module that performs a particular task. These subprograms are combined to form larger programs. This is basically called the 'Modular design'. v A subprogram can be invoked by another subprogram or program which is called the calling program. DECLARE check_exist EXCEPTION; -- declare exception type ... BEGIN .... RAISE check_exist; -- Raise exception .... EXCEPTION WHEN check_exist THEN -- execute raise exception ..... END; /
  • 10. PL/SQL provides two kinds of subprograms: ¸ Functions: these subprograms return a single value, mainly used to compute and return a value. ¸ Procedures: these subprograms do not return a value directly, mainly used to perform an action. Creating a Procedure v A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows: Where, ¸ procedure-name specifies the name of the procedure. ¸ [OR REPLACE] option allows modifying an existing procedure. ¸ The optional parameter list contains name, mode and types of the parameters. IN represents that value will be passed from outside and OUT represents that this parameter will be used to return a value outside of the procedure. ¸ procedure-body contains the executable part. ¸ The AS keyword is used instead of the IS keyword for creating a standalone procedure. Example program FUNCTION v A PL/SQL function is same as a procedure except that it returns a value. Creating a Function v A standalone function is created using the CREATE FUNCTION statement. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows: CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN | OUT | IN OUT] type [, ...])] RETURN return_datatype {IS | AS} BEGIN < function_body > CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS} BEGIN < procedure_body > END procedure_name;
  • 11. Where, ¸ function-name specifies the name of the function. ¸ [OR REPLACE] option allows modifying an existing function. ¸ The optional parameter list contains name, mode and types of the parameters. IN represents that value will be passed from outside and OUT represents that this parameter will be used to return a value outside of the procedure. ¸ The function must contain a return statement. ¸ RETURN clause specifies that data type you are going to return from the function. ¸ function-body contains the executable part. ¸ The AS keyword is used instead of the IS keyword for creating a standalone function. Calling a Function v While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, program control is transferred to the called function. v A called function performs defined task and when its return statement is executed or when it last end statement is reached, it returns program control back to the main program. v To call a function you simply need to pass the required parameters along with function name and if function returns a value then you can store returned value. Following program calls the function totalCustomers from an anonymous block: When the above code is executed at SQL prompt, it produces the following result: Example program DECLARE c number(2); BEGIN c := totalCustomers(); dbms_output.put_line('Total no. of Customers: ' || c); END; / Total no. of Customers: 6 PL/SQL procedure successfully completed.
  • 12. SQL CURSOR v A cursor is a temporary work area created in the system memory when a SQL statement is executed. v A cursor contains information on a select statement and the rows of data accessed by it. A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. v This temporary work area is used to store the data retrieved from the database, and manipulate this data. v A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set. v A cursor is basically a set of rows that you can access one at a time. v These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. v A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set. You can name a cursor so that it could be referred to in a program to fetch and process the rows returned by the SQL statement, one at a time. There are two types of cursors: ¸ Implicit cursors ¸ Explicit cursors Implicit Cursors v Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it. v When you execute DML statements like Delete, Insert, Update and Select statements, implicit statements are created to process these statements. Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. v The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN. The values of the cursor attributes always refer to the most recently executed SQL statement. Before Oracle opens the SQL cursor, the implicit cursor attributes yield NULL. Attribute Description %FOUND Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE. %NOTFOUND The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE
  • 13. %ISOPEN Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated SQL statement. %ROWCOUNT Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a SELECT INTO statement. Explicit Cursors v Explicit cursors are programmer defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row. The syntax for creating an explicit cursor is : Working with an explicit cursor involves four steps: ¸ Declaring the cursor for initializing in the memory ¸ Opening the cursor for allocating memory ¸ Fetching the cursor for retrieving data ¸ Closing the cursor to release allocated memory Declaring the Cursor v Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example: Opening the Cursor v Opening the cursor allocates memory for the cursor and makes it ready for fetching the rows returned by the SQL statement into it. For example, we will open above- defined cursor as follows: Fetching the Cursor v Fetching the cursor involves accessing one row at a time. For example we will fetch rows from the above-opened cursor as follows: CURSOR c_customers IS SELECT id, name, address FROM customers; OPEN c_customers; CURSOR cursor_name IS select_statement; FETCH c_customers INTO c_id, c_name, c_addr;
  • 14. Closing the Cursor v Closing the cursor means releasing the allocated memory. For example, we will close above-opened cursor as follows: Example program TRIGGER v Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events: ¸ A database manipulation (DML) statement (DELETE, INSERT, or UPDATE). ¸ A database definition (DDL) statement (CREATE, ALTER, or DROP). ¸ A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN). v Triggers could be defined on the table, view, schema, or database with which the event is associated. Benefits of Triggers: Triggers can be written for the following purposes: ¸ Generating some derived column values automatically ¸ Enforcing referential integrity ¸ Event logging and storing information on table access ¸ Auditing ¸ Synchronous replication of tables ¸ Imposing security authorizations ¸ Preventing invalid transactions Creating Triggers: The syntax for creating a trigger is: CLOSE c_customers; 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
  • 15. Where, ÿ CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing trigger with the trigger_name. ÿ {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The INSTEAD OF clause is used for creating trigger on a view. ÿ {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation. ÿ [OF col_name]: This specifies the column name that would be updated. ÿ [ON table_name]: This specifies the name of the table associated with the trigger. ÿ [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various DML statements, like INSERT, UPDATE, and DELETE. ÿ [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger. ÿ WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause is valid only for row level triggers. Example Program Here following two points are important and should be noted carefully: ÿ OLD and NEW references are not available for table level triggers, rather you can use them for record level triggers. ÿ If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state. ÿ Above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using DELETE operation on the table. EXCEPTION HANDLING v An error condition during a program execution is called an exception in PL/SQL. PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an appropriate action is taken against the error condition. There are two types of exceptions: ¸ System-defined exceptions ¸ User-defined exceptions
  • 16. Syntax for Exception Handling The General Syntax for exception handling is as follows. Here you can list down as many as exceptions you want to handle. The default exception will be handled using WHEN others THEN: Raising Exceptions v Exceptions are raised by the database server automatically whenever there is any internal database error, but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is the simple syntax of raising an exception: v You can use above syntax in raising Oracle standard exception or any user-defined exception. Next section will give you an example on raising user-defined exception, similar way you can raise Oracle standard exceptions as well. Example Program DECLARE <declarations section> BEGIN <executable command(s)> EXCEPTION <exception handling goes here > WHEN exception1 THEN exception1-handling-statements WHEN exception2 THEN exception2-handling-statements WHEN exception3 THEN exception3-handling-statements ........... ........... WHEN others THEN exception3-handling-statements END; DECLARE exception_name EXCEPTION; BEGIN IF condition THEN RAISE exception_name; END IF; EXCEPTION WHEN exception_name THEN statement; END;
  • 17. User-defined Exceptions v PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined exception must be declared and then raised explicitly, using either a RAISE statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR. The syntax for declaring an exception is: Pre-defined Exceptions v PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated by a program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT INTO statement returns no rows. The following table lists few of the important pre-defined exceptions: Exception Description LOGIN_DENIED It is raised when s program attempts to log on to the database with an invalid username or password. NO_DATA_FOUND It is raised when a SELECT INTO statement returns no rows. NOT_LOGGED_ON It is raised when a database call is issued without being connected to the database. PROGRAM_ERROR It is raised when PL/SQL has an internal problem. VALUE_ERROR It is raised when an arithmetic, conversion, truncation, or size-constraint error occurs. ZERO_DIVIDE It is raised when an attempt is made to divide a number by zero. DECLARE my-exception EXCEPTION;
  • 18. RELATIONAL QUERY LANGUAGES v Relational query languages use relational algebra to break the user requests and instruct the DBMS to execute the requests. It is the language by which user communicates with the database. These relational query languages can be procedural or non- procedural. Procedural Query Language v A procedural query language will have set of queries instructing the DBMS to perform various transactions in the sequence to meet the user request. v For example, get_CGPA procedure will have various queries to get the marks of student in each subject, calculate the total marks, and then decide the CGPA based on his total marks. v This procedural query language tells the database what is required from the database and how to get them from the database. Relational algebra is a procedural query language. Non-Procedural Query Language v Non-procedural queries will have single query on one or more tables to get result from the database. For example, get the name and address of the student with particular ID will have single query on STUDENT table. Relational Calculus is a non procedural language which informs what to do with the tables, but doesn’t inform how to accomplish this. v These query languages basically will have queries on tables in the database. In the relational database, a table is known as relation. v Records / rows of the table are referred as tuples. Columns of the table are also known as attributes. All these names are used interchangeably in relational database.