Professional Documents
Culture Documents
Theory
Theory
– SELECT Syntax
• WHERE Syntax
• BETWEEN Syntax
• SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
• Example
• Example
• Example
• SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
• The following SQL statement selects all
customers with a CustomerName that starts
with "a" and are at least 3 characters in
length:
• Example
• SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
• The following SQL statement selects all
customers with a ContactName that starts
with "a" and ends with "o":
• Example
• UNION Syntax
• COUNT() Syntax
• SELECT COUNT(column_name)
FROM table_name
WHERE condition;
• The AVG() function returns the average value
of a numeric column.
• AVG() Syntax
• SELECT AVG(column_name)
FROM table_name
WHERE condition;
• The SUM() function returns the total sum of a
numeric column.
• SUM() Syntax
• SELECT SUM(column_name)
FROM table_name
WHERE condition;
SQL JOIN
• A JOIN clause is used to combine rows from
two or more tables, based on a related
common column between them.
From --------------------------
WHERE ---------------(<,>,<=,>=,<>)
Sub=Query
HAVING ----------------(IN/ANY/ALL)
Syntax
SELECT select_list
FROM table
• ALL
• This multiple row operator used to check that
a given tuple in main memory satifies given
condition for all values in range
EXISTS
• TO check whether a subquery has any tuples
in the result set or not.
Set Membership
IN
-Equal to any member in the list
ANY
-Compare value to at least one value returned by
the subquery in range
ALL
-Compare value to all value returned by the
subquery in range
EXISTS
- Checks whether sub query returns a value or
not
EMP_ID FNAME DESIGNATION SALARY
SELECT emp_id,fname,designation,salary
FROM employees
WHERE salary NOT IN
AND job_id <> ‘Manager’
PL/SQL
(Procedural Language extension to Structured
Query Language)
In Oracle database management, PL/SQL is a
procedural language extension to Structured
Query Language (SQL). The purpose of PL/SQL
is to combine database language and
procedural programming language. The basic
unit in PL/SQL is called a block and is made up
of three parts: a Declarative part, an
Executable part and an Exception-building
part.
• Because PL/SQL enables users to mix SQL
statements with procedural constructs, it is
possible to use PL/SQL blocks and
subprograms to group SQL statements before
sending them to Oracle for execution. Without
PL/SQL, Oracle must process SQL statements
one at a time. In a network environment, this
can affect traffic flow and slow down response
time. PL/SQL blocks can be compiled once
and stored in executable form to improve
response time.
• A PL/SQL program that is stored in a database
in compiled form and can be called by name is
referred to as a stored procedure. A PL/SQL
stored procedure that is implicitly started
when an INSERT, UPDATE or DELETE statement
is issued against an associated table is called
a trigger.
How PL/SQL works
• PL/SQL blocks are defined by the keywords
DECLARE, BEGIN, EXCEPTION and END, which
divide the block into a declarative part, an
executable part and an exception-building
part, respectively. The declaration section of
the block is used to define and initialize
constants and variables; if a variable is not
initialized, it will default to NULL value. Blocks
can be nested and submitted to interactive
tools, like SQL*Plus.
• PL/SQL is designed to compute and return a
single scalar value or a single collection, such
as a nested table or VARRAY. Users can create
their own functions to supplement those
provided by Oracle. While functions can be
used in an SQL statement, procedures cannot.
PL/SQL - Basic Syntax
The PL/SQL programs are divided and written in
logical blocks of code. Each block consists of
three sub-parts
Declarations
This section starts with the keyword DECLARE. It
is an optional section and defines all variables,
cursors, subprograms, and other elements to
be used in the program.
• Executable Commands
• This section is enclosed between the
keywords BEGIN and END and it is a
mandatory section. It consists of the
executable PL/SQL statements of the program.
It should have at least one executable line of
code, which may be just a NULL command to
indicate that nothing should be executed.
• Exception Handling
• This section starts with the
keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the
program.
• Every PL/SQL statement ends with a
semicolon (;).
• PL/SQL blocks can be nested within other
PL/SQL blocks using BEGIN and END.
Following is the basic structure of a PL/SQL block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
• The PL/SQL Delimiters
• A delimiter is a symbol with a special meaning.
Following is the list of delimiters in PL/SQL
Delimiter Description
+, -, *, / Addition,
subtraction/negation,
multiplication, division
% Attribute indicator
. Component selector
, Item separator
Delimiter Description
= Relational operator
; Statement terminator
:= Assignment operator
Delimiter Description
|| Concatenation operator
** Exponentiation operator
.. Range operator
– IF <condition> THEN
<Statements>
ELSE
<Statements>
END IF;
DECLARE
sales NUMBER := 300000;
commission NUMBER( 10, 2 ) := 0;
BEGIN
IF sales > 200000 THEN
commission := sales * 0.1;
ELSE
commission := sales * 0.05;
END IF;
END;
IF condition_1 THEN
statements_1
ELSIF condition_2 THEN
statements_2
[ ELSIF condition_3 THEN
statements_3
]
...
[ ELSE
else statements
]
END IF;
DECLARE
sales NUMBER := 300000;
commission NUMBER( 10, 2 ) := 0;
BEGIN
IF sales > 200000 THEN
commission := _sales * 0.1;
ELSIF sales <= 200000 AND 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;
• Iterative Constructs Loops
• LOOP
• WHILE-LOOP
• FOR-LOOP
LOOP Constructs
LOOP
<Sequence of statements>
END LOOP;
LOOP with EXIT
LOOP
<statements>
IF <condition> THEN
Exit;
END IF;
END LOOP;
LOOP
counter =counter + 1;
Exit;
END IF;
END LOOP;
LOOP using EXIT WHEN
LOOP
<Sequence of statements>
END LOOP;
WHILE-LOOP
WHILE <Condition> LOOP
<Sequence of statements>
END LOOP;
FOR -LOOP
Stored Procedure
• A stored procedure in SQL is a group of SQL
statements that are stored together in
a database. Based on the statements in the
procedure and the parameters you pass, it can
perform one or multiple DML operations on
the database, and return value, if any. Thus, it
allows you to pass the same statements
multiple times, thereby, enabling reusability.
Benefits of using a Stored Procedure in SQL?
DELIMITER $$
CREATE FUNCTION fun_name(fun_parameter(s))
RETURNS datatype
[NOT] {Characteristics}
fun_body;
CURSOR
• Cursor is a Temporary Memory or Temporary
Work Station. It is Allocated by Database
Server at the Time of Performing DML(Data
Manipulation Language) operations on Table
by User. Cursors are used to store Database
Tables.
• An area of memory(Context) allocated for the
processing of SQL statements.
• Cursor is a handle or pointer to the context
area.
• Cursor in SQL
To execute SQL statements, a work area is used
by the Oracle engine for its internal processing
and storing the information. This work area is
private to SQL’s operations. The ‘Cursor’ is the
PL/SQL construct that allows the user to name
the work area and access the stored
information in it.
• Use of cursor
The major function of a cursor is to retrieve
data, one row at a time, from a result set,
unlike the SQL commands which operate on
all the rows in the result set at one time.
Cursors are used when the user needs to
update records in a singleton fashion or in a
row by row manner, in a database table.
• The Data that is stored in the Cursor is called
the Active Data Set. Oracle DBMS has another
predefined area in the main memory Set,
within which the cursors are opened. Hence
the size of the cursor is limited by the size of
this pre-defined area.
• Cursor Actions
• Declare Cursor: A cursor is declared by
defining the SQL statement that returns a
result set.
• Open: A Cursor is opened and populated by
executing the SQL statement defined by the
cursor.
• Fetch: When the cursor is opened, rows can
be fetched from the cursor one by one or in a
block to perform data manipulation.
• Cursor Actions
• Declare Cursor: A cursor is declared by
defining the SQL statement that returns a
result set.
• Open: A Cursor is opened and populated by
executing the SQL statement defined by the
cursor.
• Fetch: When the cursor is opened, rows can
be fetched from the cursor one by one or in a
block to perform data manipulation.
• Close: After data manipulation, close the
cursor explicitly.
• Deallocate: Finally, delete the cursor
definition and release all the system resources
associated with the cursor.
• Types of Cursors
Cursors are classified depending on the
circumstances in which they are opened.
• Implicit Cursor: If the Oracle engine opened a
cursor for its internal processing it is known as
an Implicit Cursor. It is created “automatically”
for the user by Oracle when a query is
executed and is simpler to code.
• Explicit Cursor: A Cursor can also be opened
for processing data through a PL/SQL block, on
demand. Such a user-defined cursor is known
as an Explicit Cursor.
• Explicit cursor
An explicit cursor is defined in the declaration
section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than
one row. A suitable name for the cursor.
• General syntax for creating a cursor:
• CURSOR cursor_name IS select_statement;
• cursor_name – A suitable name for the cursor.
select_statement – A select query which
returns multiple rows
• How to use Explicit Cursor?
• There are four steps in using an Explicit Cursor.
• DECLARE the cursor in the Declaration section.
• OPEN the cursor in the Execution Section.
• FETCH the data from the cursor into PL/SQL
variables or records in the Execution Section.
• CLOSE the cursor in the Execution Section
before you end the PL/SQL Block.
• Syntax:
DECLARE variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
Triggers
• 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).
• Triggers can be defined on the table, view, schema,
or database with which the event is associated.
Benefits of Triggers
• 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
• CREATE [OR REPLACE] TRIGGER trigger_name
− Creates or replaces an existing trigger with
the trigger_name.
( NOT EXISTS (