0% found this document useful (0 votes)
3 views73 pages

DBMSPPTModule 3

The document provides an overview of SQL and PL/SQL, detailing their functionalities, syntax, and key components. It covers various SQL statements, operators, and functions, as well as the structure and control mechanisms of PL/SQL. Additionally, it explains exception handling and the types of PL/SQL blocks, emphasizing the procedural aspects of database programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views73 pages

DBMSPPTModule 3

The document provides an overview of SQL and PL/SQL, detailing their functionalities, syntax, and key components. It covers various SQL statements, operators, and functions, as well as the structure and control mechanisms of PL/SQL. Additionally, it explains exception handling and the types of PL/SQL blocks, emphasizing the procedural aspects of database programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

Module - 3

SQL & PL/SQL

1
SQL
• SQL is a database computer language designed for the
retrieval and management of data in a relational
database.
• SQL stands for Structured Query Language which is
used to store, manipulate and retrieve data stored in a
relational database.
• SQL is the standard language for Relational Database
System.
• All the RDMS like SQL Server, MySQL, MS Access, Oracle,
Sybase, Informix use SQL as their standard database
language.

2
Basic SQL Query
• SQL statements tell the database what operation you
want to perform on the structured data and what
information you would like to access from the database.
• Example:
-SELECT "column_name" FROM "table_name";
-select * from Student
where SID=101

3
Distinct Statement
• The Distinct statement is used to return only distinct
(different) values.
• Syntax:
SELECT DISTINCT column1, column2, ...
FROM table_name;
• Example:
select distinct Sname from Sailors

4
Like Operator
• The Like operator is used in a Where clause to search
for a specified pattern in a column.
• There are two wildcards often used in conjunction with
the Like operator:
 The percent sign (%) represents zero, one, or multiple
characters
 The underscore sign (_) represents one, single character
• Example:
select * from Sailors where SName like ‘p%’
select * from Sailors where SName like ‘__%’
select * from Sailorswhere SName like 'p_%'

5
AND, OR and NOT Operators
• The where clause can be combined with AND, OR, and
NOT operators.
• The AND and OR operators are used to filter records
based on more than one condition:
 The AND operator displays a record if all the conditions
separated by AND are TRUE.
 The OR operator displays a record if any of the conditions
separated by OR is TRUE.
• The NOT operator displays a record if the condition(s) is
not true.

6
Aggregate functions
• The COUNT() function returns the number of rows that
matches a specified criterion.
• The AVG() function returns the average value of a
numeric column.
• The SUM() function returns the total sum of a numeric
column.
• The MIN() function returns the smallest value of the
selected column.
• The MAX() function returns the largest value of the
selected column.

7
Order by Statement
• The Order by keyword is used to sort the result-set in
ascending or descending order.
• The Order by keyword sorts the records in ascending
order by default. To sort the records in descending
order, use the desc keyword.
• Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

8
Group by Statement
• The Group by statement groups rows that have the
same values into summary rows.
• This statement is often used with aggregate functions to
group the result-set by one or more columns.
• Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

9
Having Clause
• The Having clause was added to SQL because the Where
keyword cannot be used with aggregate functions.
• Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

10
Union Operator
• The UNION operator is used to combine the result-set of
two or more SELECT statements.
• Every SELECT statement within UNION must have the
same number of columns.
• The columns must also have similar data types.
• The columns in every SELECT statement must also be in
the same order.
• The UNION operator selects only distinct values by
default.
• To allow duplicate values, use UNION ALL.

11
Date and Time functions
• GetDate()
• DateDiff()
• DatePart()
• DateName()
• Day(), Month(), Year()
• DateAdd()
• EOMonth()

12
String functions
• Upper() • Ltrim()
• Lower() • Rtrim()
• Left() • SubString()
• Rigth() • Replace()
• Length() • Space()
• Reverse() • Concat()
• Trim()

13
Comparison Operators
• = Equal to
• > Greater than
• < Less than
• >= Greater than or equal to
• <= Less than or equal to
• <> Not equal to

14
Logical Operators
Operator Description
ALL TRUE if all of the subquery values meet the
condition
AND TRUE if all the conditions separated by AND
is TRUE
ANY TRUE if any of the subquery values meet the
condition
BETWEEN TRUE if the operand is within the range of
comparisons
EXISTS TRUE if the subquery returns one or more
records
IN TRUE if the operand is equal to one of a list
of expressions
LIKE TRUE if the operand matches a pattern
NOT Displays a record if the condition(s) is NOT
TRUE
OR TRUE if any of the conditions separated by
OR is TRUE
SOME TRUE if any of the subquery values meet the 15
condition
Null Values
• A field with a NULL value is a field with no value.
• A NULL value is different from a zero value or a field
that contains spaces.
• A field with a NULL value is one that has been left
blank during record creation.
• It is not possible to test for NULL values with
comparison operators, such as =, <, or <>.
• We will have to use the IS NULL and IS NOT NULL
operators instead.

16
Sub Query
• A Subquery is a query within another SQL query and
embedded within the where clause.
• A subquery is a query within another query. The outer
query is known as the main query, and the inner query
is known as a subquery.
• You can use Subquery with Select, Update, Insert,
Delete statements along with the operators like =, <, >,
>=, <=, in, between, etc.

17
Correlated Subquery
• It is similar to loop in a loop concept.
• The execution is from top to bottom.
• Inner query is dependent on outer query.
• One value by one value is sent from outer to sub query.
• In this subquery is dependent query.

18
T-SQL
• T-SQL (Transact SQL) is designed for both beginners and
professionals.
• T-SQL expands the SQL to include procedural
programming, local variables, string processing and
data processing.
• T-SQL is the extension of SQL language.

19
Introduction
• PL/SQL stands for “Procedural
Language extensions to the
Structured Query Language”.
• PL/SQL is a highly structured and
readable language.
• PL/SQL is a standard and portable
language for Oracle Database
development.
• PL/SQL is an embedded language.
• PL/SQL only can execute in an Oracle
Database.
20
Cont.
• It was not designed to use as a
standalone language like Java,
C#, and C++.
• In other words, we cannot develop
a PL/SQL program that runs on a
system that does not have an
Oracle Database.
• PL/SQL is a high-performance and
highly integrated database
language.
21
PL/SQL Block
• PL/SQL is a block-structured language
whose code is organized into blocks.
• A PL/SQL block consists of three
sections:
1.Declaration section
2.Execution section
3.Exception-Handling section
• In a block, the executable section is
mandatory while the declaration and
exception-handling sections are
optional.
22
Cont.

23
Cont.
DECLARE --optional
<declarations>

BEGIN --mandatory
<executable statements. At least one executable
statement is mandatory>

EXCEPTION --optional
<exception handles>

END; --mandatory
/
Note: A block should always be followed by '/'
which sends the information to the compiler about
the end of the block.
24
Types of PL/SQL block
PL/SQL blocks are of mainly two types.
1.Anonymous blocks
2.Named Blocks

Anonymous blocks:
• These are PL/SQL blocks which do not
have any names assigned to them.
• They need to be created and used in
the same session because they will
not be stored in the server as
database objects.

25
Cont.
Named blocks
• These have a specific and
unique name for them. They
are stored as the database
objects in the server.
• Since they are available as
database objects, they can be
referred to or used as long as
it is present on the server.
26
PL/SQL Data Types
• PL/SQL divides the scalar data
types into four families:
•Number
•Boolean
•Character
•Datetime

27
Control Structure
PL/SQL 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
28
Control Structure
PL/SQL 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
 Searched CASE statement
• Both types of the CASE
29
statements support an
Cont.
• The PL/SQL CASE statement facilitates us to
execute a sequence of statements based on
a selector.
• A selector can be anything such as variable,
function or an expression that the CASE
statement checks to a Boolean value.
• The CASE statement works like the IF
statement, only using the keyword WHEN.
• A CASE statement is evaluated from top to
bottom.
• If it get the condition TRUE, then the
corresponding THEN clause is executed and
the execution goes to the END CASE clause.
30
Cont.
Simple CASE statement:
Syntax:
CASE [ expression ]
WHEN condition_1 THEN result_1;
WHEN condition_2 THEN result_2;
...
WHEN condition_n THEN result_n;
ELSE result;
END CASE;

31
Cont.
Searched CASE statement:
• The SEARCHED CASE statement is
similar to the CASE statement, rather
than using the selector to select the
alternative, SEARCHED CASE will
directly have the expression defined in
the WHEN clause.
• The first WHEN clause that satisfies the
condition will be executed, and the
controller will skip the remaining
alternatives.

32
Cont.
Syntax:
CASE
WHEN <expression1> THEN
action_block1;
WHEN <expression2> THEN
action_block2;
WHEN <expression3> THEN
action_block3;
ELSE action_block_default; 33
Cont.
Example:
CASE
WHEN salary >= 10000 AND salary <=20000
THEN
give_bonus(employee_id, 1500);
WHEN salary > 20000 AND salary <= 40000 THEN
give_bonus(employee_id, 1000);
WHEN salary > 40000 THEN
give_bonus(employee_id, 500);
ELSE
give_bonus(employee_id, 0);
END CASE;

34
Control Structure
Iterative Control
• Iterative control indicates the ability to
repeat or skip sections of a code block.
• A loop marks a sequence of
statements that has to be repeated.
• The keyword loop has to be placed
before the first statement in the
sequence of statements to be
repeated, while the keyword end loop
is placed immediately after the last
statement in the sequence.
35
Cont.
Simple Loop:
In simple loop, the key word loop
should be placed before the first
statement in the sequence and the
keyword end loop should be written at
the end of the sequence to end the loop.
Syntax:
Loop
< Sequence of statements >
End loop;

36
Cont.
• This structure is the most basic
of all the loop constructs
including FOR LOOP and WHILE
LOOP.
• The LOOP statement executes
the statements in its body and
returns control to the top of the
loop.
• Typically, the body of the loop
contains at least one EXIT or
EXIT WHEN statement for 37
Cont.
FOR Loop:
• The FOR loop can be used when the
number of iterations to be executed
are known.
Syntax:
FOR index IN lower_bound ..
upper_bound
LOOP
statements;
END LOOP;
38
Cont.
• The index is an implicit variable. It
is local to the FOR LOOP
statement.
• In other words, we cannot refer it
outside the loop.
• Inside the loop, we can refer index
but we cannot change its value.
• After the FOR LOOP statement
executes, the index becomes
undefined.
• Both lower_bound and 39
Cont.
WHILE Loop:
• The while loop executes commands
in its body as long as the condition
remains true
Syntax:
WHILE condition
LOOP
statements;
END LOOP;
40
Cont.
• The condition in the WHILE is a
Boolean expression that
evaluates to TRUE, FALSE or
NULL.
• The WHILE loop statement
continues to execute the
statements between the LOOP
and END LOOP as long as the
condition in the WHILE clause
evaluates to TRUE.
• PL/SQL evaluates the condition 41
Cont.
• If the condition is TRUE, then
the loop body executes. In case
it is FALSE or NULL, the loop
terminates.
• If the condition is FALSE before
entering the loop, the WHILE
loop does not execute at all.
• This behavior is different from
the LOOP statement whose loop
body always executes once.
42

PL/SQL Select INTO statement
• PL/SQL SELECT INTO statement is
the simplest and fastest way to
fetch a single row from a table
into variables.
Syntax:
SELECT column1, column2…. Column
n
INTO variable1, variable2… Variable n
FROM table_name
WHERE <expression>;

43
Exception Handling in PL/SQL
• An exception is an error which
disrupts the normal flow of
program instructions.
• PL/SQL provides us the
exception block which raises
the exception thus helping the
programmer to find out the
fault and resolve it.
• There are two types of
exceptions defined in PL/SQL
44
1. Pre/System defined exceptions.
Cont.
Syntax:
BEGIN
<execution block>
……
EXCEPTION
WHEN <exceptionl_name>
THEN
<Exception handling code for the “exception 1
_name’’ >
WHEN OTHERS
THEN
<Default exception handling code for all exceptions >
END;

45
Cont.
• When other keyword should be
used only at the end of the
exception handling block as no
exception handling part present
later will get executed as the
control will exit from the block
after executing the WHEN
OTHERS.
• Raising Exceptions: In the case
of any internal database error,
exceptions are raised by the
database server automatically. But 46
Cont.
Syntax for raising an exception:
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;

47
Cont.
PL/SQL Pre-defined Exceptions:
There are many pre-defined
exception in PL/SQL which are
executed when any database rule is
violated by the programs.
Example: NO_DATA_FOUND is a pre-
defined exception which is raised
when a SELECT INTO statement
returns no rows.

48
Cont.
Exception Oracle SQL Description Exception Oracle SQL Description
Error Code Error Code

ACCESS_INTO_NULL 06530 -6530 I t is raised when a NULL object is LOGI N_DENI ED 01017 -1017 I t is raised when s program

automatically assigned a value. attempts to log on to the


database with an invalid
CASE_NOT_FOUND 06592 -6592 I t is raised when none of the username or password.

choices in the "WHEN" clauses of a


NO_ DATA_ FOUND 01403 +100 I t is raised when a select into
CASE statement is selected, and
statement returns no rows.
there is no else clause.
NOT_LOGGED_ON 01012 -1012 I t is raised when a database call
COLLECTI ON_ I S_ NULL 06531 -6531 I t is raised when a program is issued without being

attempts to apply collection connected to the database.

methods other than exists to an


PROGRAM_ ERROR 06501 -6501 I t is raised when PL/SQL has an
uninitialized nested table or internal problem.
varray, or the program attempts
to assign values to the elements of ROWTYPE_ MI SMATCH 06504 -6504 I t is raised when a cursor
fetches value in a variable
an uninitialized nested table or
having incompatible data type.
varray.
SELF_I S_ NULL 30625 -30625 I t is raised when a member
DUP_ VAL_ON_I NDEX 00001 -1 I t is raised when duplicate values method is invoked, but the
are attempted to be stored in a instance of the object type was
column with unique index. not initialized.

I NVALID_ CURSOR 01001 -1001 I t is raised when attempts are STORAGE_ ERROR 06500 -6500 I t is raised when PL/SQL ran out
of memory or memory was
made to make a cursor operation
corrupted.
that is not allowed, such as closing
an unopened cursor. TOO_MANY_ROWS 01422 -1422 I t is raised when a SELECT INTO
statement returns more than
I NVALID_ NUMBER 01722 -1722 I t is raised when the conversion of one row.
a character string into a number
ZERO_ DI VIDE 01476 1476 I t is raised when an attempt is
fails because the string does not
made to divide a number by
represent a valid number.
zero.

49
Cont.
PL/SQL User defined exceptions:
This type of users can create their own
exceptions according to the need and to raise
these exceptions explicitly raise command is
used.
Syntax:
DECLARE
< ExceptionName > EXCEPTION ;
BEGIN
IF < Condition > THEN
RAISE <ExceptionName>;
END IF;
EXCEPTION
WHEN <ExceptionName>THEN {User Defined Action To
Be Taken};
END;
50
Procedures and
Functions in PL/SQL
• PL/SQL subprograms are
named PL/SQL blocks that
can be invoked with a set of
parameters.
• PL/SQL provides two kinds of
subprograms :
1. Functions: These
subprograms return a single
value; mainly used to
compute and return a value.
51
Procedures in
PL/SQL
• A Procedure in PL/SQL is a subprogram unit
that consists of a group of PL/SQL statements
that can be called by name.
• Each procedure in PL/SQL has its own unique
name by which it can be referred to and
called.
• This subprogram unit in the Oracle database
is stored as a database object.
• Subprogram is nothing but a procedure, and
it needs to be created manually as per the
requirement. Once created they will be stored
as database objects.

52
Cont.
• It is mainly used to execute a process in PL/SQL.
• The values can be passed into Oracle procedure
or fetched from the procedure through
parameters.
• These parameters should be included in the
calling statement.
• A Procedure in SQL can have a RETURN statement
to return the control to the calling block, but it
cannot return any values through the RETURN
statement.
• Procedures cannot be called directly from SELECT
statements. They can be called from another
block or through EXEC keyword.

53
Cont.
Syntax:
CREATE [OR REPLACE] PROCEDURE
procedure_name
(parameter_name [IN | OUT | IN OUT]
type, ........)
{IS | AS}
BEGIN
< procedure_body >
END;

54
Functions in
PL/SQL
• Functions is a standalone PL/SQL
subprogram.
• Like PL/SQL procedure, functions
have a unique name by which it
can be referred.
• These are stored as PL/SQL
database objects.
• Functions are a standalone block
that is mainly used for calculation
purpose.
55
Cont.

• A Function should either return a


value or raise the exception, i.e.
return is mandatory in functions.
• The values can be passed into the
function or fetched from the
procedure through the
parameters.
• A PLSQL function can also return
the value through OUT parameters
other than using RETURN. 56
Cont.
Syntax:
CREATE [OR REPLACE] FUNCTION
function_name
(parameter_name [IN | OUT | IN OUT]
type, .....)
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END
57
PL/SQL
Cursors
• When an SQL statement is
processed, Oracle creates a
memory area known as context
area.
• A cursor is a pointer to this
context area.
• It contains all information needed
for processing the statement.
• In PL/SQL, the context area is
controlled by Cursor.
58
Cont.
• A cursor is used to referred to a
program to fetch and process the
rows returned by the SQL
statement, one at a time.
• There are two types of cursors:
1. Implicit Cursors
2. Explicit Cursors

59
Cont.
PL/SQL Implicit Cursors:
• The implicit cursors are automatically
generated by Oracle while an SQL
statement is executed, if you don't
use an explicit cursor for the
statement.
• These are created by default to
process the statements when DML
statements like INSERT, UPDATE,
DELETE etc. are executed.
60
Cont.
Oracle provides some attributes
known as Implicit cursor's attributes
to check the status of DML
operations. Some of them are:
• %FOUND
• %NOTFOUND
• %ROWCOUNT
• %ISOPEN.

61
Cont.
PL/SQL Explicit Cursors:
• The Explicit cursors are defined by
the programmers to gain more
control over the context area.
• These cursors 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.

62
Cont.
Steps to follow while
working with explicit cursor:
• Declare the cursor to initialize in
the memory.
• Open the cursor to allocate
memory.
• Fetch the cursor to retrieve data.
• Close the cursor to release
allocated memory.

63
Cont.
Declare the cursor:
It defines the cursor with a
name and the associated SELECT
statement.
Syntax:

CURSOR <cursor-name> IS
SELECT statement;
Example:

CURSOR c1 IS SELECT sid,


sname, age FROM sailors;
64
Cont.
Open the cursor:
It is used to allocate memory for the
cursor and make it easy to fetch the rows
returned by the SQL statements into it.
Syntax:

OPEN <cursor-name>;
Example:

OPEN c1;

65
Cont.
Fetch the cursor:
It is used to access one row at a
time. We can fetch rows from the
opened cursor as follows:
Syntax:

FETCH <cursor_name> INTO


<variable_list>;
Example:

FETCH c1 INTO id, name, age;

66
Cont.
Close the cursor:
After fetching all rows, we need
to close the cursor with the CLOSE
statement.
Syntax:

CLOSE <cursor_name>;
Example:

CLOSE c1;

67
PL/SQL
Triggers
• A trigger is a named PL/SQL block
stored in the Oracle Database and
executed automatically when a
triggering event takes place.
• These events can be:
• DDL statements (CREATE, ALTER,
DROP, TRUNCATE)
• DML statements (INSERT, SELECT,
UPDATE, DELETE)
• Database operation like connecting
or disconnecting to oracle (LOGON,
68
LOGOFF, SHUTDOWN)
Cont.
• Triggers could be defined on the table, view,
schema, or database with which the event is
associated.

Benefits of Triggers:
• Control DML
• Implementing Complex Business Rules
• Enforcing referential integrity
• Auditing
• Synchronous replication of tables
• Preventing invalid transactions
• Granting authorization and providing security
to database.
69
Cont.
Types of Triggers:
• Triggers can be classified into three
categories:
1. Level Triggers
2. Event Triggers
3. Timing Triggers

Level Triggers:
There are 2 different types of level
triggers, they are:
• Row Level Triggers
• Statement Level Triggers
70
Cont.
Event Triggers:
There are 3 different types of event
triggers, they are:
• DDL Event Trigger
• DML Event Trigger
• Database Event Trigger

Timing Triggers:
There are 2 different types of timing
triggers, they are:
• Before Trigger
71
• After Trigger
Syntax for creating Triggers:
Cont.
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
72
END;
T-SQL Data types
• Number
• Boolean
• Character
• Datetime

73

You might also like