Dbms Unit3
Dbms Unit3
Dbms Unit3
In the outer query, we use the OR logical connective to retrieve a PROJECT tuple if the PNUMBER
value of that tuple is in the result of either nested query
Some queries require that existing values in the database be fetched and then used in a
comparison condition
Nested queries, which are complete select-from-where blocks within the WHERE clause of another
query .That other query is called the outer query.
The comparison operator IN, which compares a value v with a set (or multiset) of values V and
evaluates to TRUE if v is one of the elements in V
4
Cont..
Note: If a nested query returns a single attribute and a single tuple, the query result will
be a single (scalar) value. In such cases, it is permissible to use = instead of IN
In general, the nested query will return a table (relation), which is a set or multiset of
tuples.
5
Cont..
This query will select the Essns of all employees who work the same (project, hours)
combination on some project that employee ‘John Smith’ (whose Ssn = ‘123456789’) works on
The = ANY (or = SOME) operator returns TRUE if the value v is equal to some value in the set V
and is hence equivalent to IN. The two keywords ANY and SOME have the same effect
The keyword ALL can also be combined with each of these operators.
6
Cont..
The names of employees whose salary is greater than the salary of all the
employees in department 5
Retrieve the name of each employee who has a dependent with the same first
name and is the same sex as the employee.
7
Cont..
A condition in the WHERE clause of a nested query references some attribute of a relation
declared in the outer query, the two queries are said to be correlated.
The EXISTS and UNIQUE Functions in SQL
The EXISTS function in SQL is used to check whether the result of a correlated nested query is
empty (contains no tuples) or not.
The result of EXISTS is a Boolean value TRUE if the nested query result contains at least one
tuple, or FALSE if the nested query result contains no tuples.
8
Cont..
Subqueries with the UPDATE & DELETE 9
Statements
It is also possible to use an explicit set of values in the WHERE clause, rather than a nested
query.
Retrieve the Social Security numbers of all employees who work on project numbers 1, 2,
or 3.
Named
A block of code which has name. A “Sub Program” is a named block can be called and take arguments
A Procedure is a subprogram that can perform an action
A Function is a subprogram that returns a value
A package is formed from a group procedures and functions
A trigger is a block that is called implicitly by a DML Statements
12
Block Structure in PL/SQL
[Declare]
declaration of constants and variables , cursors and Exceptions]
BEGIN
Executable PL/SQL and SQL statements
[Exception
Actions for error conditions]
END;
Comments
Single line Comment: -- this is single line Comment
Multi Line Comment : /* This is a multiline Comment */
14
Cont..
Code block start with a declaration section, in which memory variables, constants,
cursors and other oracle objects can be declared and if required initialized.
Begin section which describe processes that have to be applied to table data.
Actual data manipulation, retrieval, looping and branching constructs are specified
in this section.
Exception section: This section deals with handling errors that arise during execution
data manipulation statements, which make up PL/SQL code block
User-defined Identifiers
Spaces are not allowed ,Other special characters are not allowed
Name should not be the same as the name of a column used in the block
16
Data Types
Date
17
Variable Declaration
Variables can have any SQL datatype, such as CHAR, DATE, or NUMBER, or any PL/SQL
datatype
part_no NUMBER(4);
in_stock BOOLEAN;
Anchored Declaration
It Uses %Type
Variablename typeAttribute%Type [value assignment]
Example :
num1 number(3); num2 num1%Type
Emp_sal Employee.salary%Type
Dept_name Dept.Dname%Type
18
Assigning values
The first way uses the assignment operator (:=), a colon followed by an equal sign
valid_id := FALSE;
The second way to assign values to a variable is by selecting (or fetching) database
values into it
SELECT sal * 0.10 INTO bonus FROM emp WHERE empno = emp_id;
19
Cont..
The third way to assign values to a variable is by passing it as an OUT or IN OUT parameter to a
subprogram.
DECLARE
my_sal REAL(7,2);
BEGIN
Declaring a constant is like declaring a variable except that you must add the
keyword CONSTANT and immediately assign a value to the constant.
Bind Variable
These are declared at SQL* PLUS Environment and are accessed by a PL/SQL Block
Anonymous blocks don’t take any arguments ,host variables are accessed by prefixed
with :
Substitution Variables
There are no Explicit Input/Output Statements , but Substitution variables
of SQL are available in PL/SQL
A Standard Prompt for “variables” appears on the screen for users to type
in a value for it
SET VERIFY OFF
PRINT
23
Cont..
While Loop : [ label ] WHILE condition LOOP statements END LOOP [ label ];
The label must be unique in its scope and must precede an executable statement or a
PL/SQL block. When run, the GOTO statement transfers control to the labeled statement or
block
The EXIT statement exits the current iteration of a loop unconditionally and transfers
control to the end of either the current loop or an enclosing labeled loop.
The EXIT WHEN statement exits the current iteration of a loop when the condition in
its WHEN clause is true, and transfers control to the end of either the current loop or an
enclosing labeled loop.
The CONTINUE statement exits the current iteration of a loop unconditionally and transfers
control to the next iteration of either the current loop or an enclosing labeled loop.
The CONTINUE WHEN statement exits the current iteration of a loop when the condition in
its WHEN clause is true, and transfers control to the next iteration of either the current loop
or an enclosing labeled loop.
29
SQL in PL/SQL
DECLARE
n1 NUMBER := &num1;
BEGIN
-- test if the number provided by the user is even
IF MOD(n1,2) = 0 THEN
DBMS_OUTPUT.PUT_LINE ('The number. '||n1||' is even number');
ELSE
DBMS_OUTPUT.PUT_LINE ('The number '||n1||' is odd number.');
END IF;
DBMS_OUTPUT.PUT_LINE ('Done Successfully');
END;
/
31
DECLARE Good');
grd CHAR(1); ELSIF grd = 'D' THEN
BEGIN dbms_output. Put_line('Your Grade is:
Average');
-- Accept value for grade
ELSIF grd = 'F' THEN
grd := '&new_grd';
dbms_output.Put_line('Your Grade is: Poor');
IF grd = 'A' THEN
ELSE
dbms_output.Put_line('Your Grade is:
Outstanding'); dbms_output.Put_line('No such grade in the
list.');
ELSIF grd = 'B' THEN
END IF;
dbms_output.Put_line('Your Grade is:
Excellent'); END;
ELSIF grd = 'C' THEN /
dbms_output.Put_line('Your Grade is: Very
32
Searched Case
DECLARE
grd CHAR(1);
BEGIN
-- Accept value for grade
grd := '&new_grd';
CASE grd
WHEN 'A' THEN dbms_output.Put_line('Your Grade is: Outstanding');
WHEN 'B' THEN dbms_output.Put_line('Your Grade is: Excellent');
WHEN 'C' THEN dbms_output.Put_line('Your Grade is: Very Good');
WHEN 'D' THEN dbms_output. Put_line('Your Grade is: Average');
WHEN 'F' THEN dbms_output.Put_line('Your Grade is: Poor');
ELSE dbms_output.Put_line('No such grade in the list.');
END CASE;
END;
/
34
Loop
DECLARE
n NUMBER := 0;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ('The value of n inside the loop is: ' || n);
n := n + 1;
IF n > 5 THEN
EXIT;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('The value of n outside the loop is: ' || n);
END;
/
35
EXIT WHEN
DECLARE
n NUMBER := 0;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('The value of n inside the loop is: ' || TO_CHAR(n));
n := n + 1;
EXIT WHEN n > 5;
END LOOP;
DBMS_OUTPUT.PUT_LINE('The value of n after exit from the loop is: ' || TO_CHAR(n));
END;
/
36
Continue when
DECLARE
n NUMBER := 0;
BEGIN
LOOP -- After CONTINUE statement, control resumes here
DBMS_OUTPUT.PUT_LINE ('The value inside the loop: n = ' || TO_CHAR(n));
n := n + 1;
CONTINUE WHEN n < 4;
DBMS_OUTPUT.PUT_LINE('The value inside loop, after CONTINUE: n = ' || TO_CHAR(n));
EXIT WHEN n = 6;
END LOOP;
DBMS_OUTPUT.PUT_LINE ('The value after exit from the loop: n = ' || TO_CHAR(n));
END;
/
37
For loop
DECLARE
n number:= &first_n_number;
BEGIN
DBMS_OUTPUT.PUT_LINE ('The first '||n||' numbers are: ');
for i in reverse 1..n loop
dbms_output.put(i||' ');
END LOOP;
dbms_output.new_line;
END;
/
38
Procedure
A procedure is created with the CREATE OR procedure-name specifies the name of the procedure.
DECLARE z:= y;
a number; END IF;
b number; END;
c number; BEGIN
PROCEDURE findMin(x IN number, y IN number, z a:= 23;
OUT number)
b:= 45;
IS
findMin(a, b, c);
BEGIN
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
IF x < y THEN
END;
z:= x;
ELSE
42
Cont..
A function is same as a procedure except that it returns a function-name specifies the name of the function.
value.. [OR REPLACE] option allows the modification of an
existing function.
A function is created using the CREATE
The optional parameter list contains name, mode and
FUNCTION statement.
types of the parameters. IN represents the value that
CREATE [OR REPLACE] FUNCTION function_name will be passed from outside and OUT represents the
parameter that will be used to return a value outside of
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
the procedure.
RETURN return_datatype The function must contain a return statement.
{IS | AS} The RETURN clause specifies the data type you are
going to return from the function.
BEGIN
function-body contains the executable part.
< function_body > END [function_name]; The AS keyword is used instead of the IS keyword for
43
Cont..
• To use a function, you will have to call that function to perform the defined task.
• When a program calls a function, the program control is transferred to the called function.
• A called function performs the defined task and when its return statement is executed or when the last
end statement is reached, it returns the program control back to the main program.
• To call a function, you simply need to pass the required parameters along with the function name and if
the function returns a value, then you can store the returned value. Following program calls the
function totalCustomers from an anonymous block
44
Function Creation
DECLARE END;
a number; BEGIN
b number; a:= 23;
c number; b:= 45;
FUNCTION findMax(x IN number, y IN c := findMax(a, b);
number)RETURN number dbms_output.put_line(' Maximum of a and b is ' || c);
IS END;
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE z:= y;
END IF;
RETURN z;
45
Recursive Functions
The set of rows the cursor holds is referred to as the active set.
PL/SQL implicitly declares a cursor for all SQL data manipulation statements, including queries
that return only one row.
For queries that return more than one row, you can explicitly declare a cursor to process the rows
individually.
The set of rows returned by a multi-row query is called the result set.
Its size is the number of rows that meet your search criteria.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to
be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
DECLARE
CURSOR c1 IS
SELECT ename, sal, hiredate, deptno FROM emp;
BEGIN
FOR emp_rec IN c1 LOOP
... salary_total := salary_total + emp_rec.sal;
END LOOP;
49
Cursor FOR Loops
You can simplify coding by using a cursor FOR loop instead of the OPEN, FETCH,
and CLOSE statements
A cursor FOR loop implicitly declares its loop index as a record that represents a row
fetched from the database.
Next, it opens a cursor, repeatedly fetches rows of values from the result set into fields
in the record, then closes the cursor when all rows have been processed.
In the following example, the cursor FOR loop implicitly declares emp_rec as a
record:DECLARE
50
1 %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.
2 %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.
3 %ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
4 %ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
52
Cont..
DECLARE
total_rows number(2);
BEGIN
UPDATE pgm SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
53
Exception
DECLARE exception2-handling-statements
<declarations section> WHEN exception3 THEN
BEGIN exception3-handling-statements
<executable command(s)> ........
EXCEPTION WHEN others THEN
<exception handling goes here > exception3-handling-statements
WHEN exception1 THEN END;
exception1-handling-statements
WHEN exception2 THEN
54
Cont..
It is convenient to specify the type of action to be taken when certain events occur and when
certain conditions are satisfied.
Other actions may be specified, such as executing a specific stored procedure or triggering other
updates.
Suppose we want to check whenever an employee’s salary is greater than the salary of his or her
direct supervisor in the COMPANY database
The event(s)
The condition
The action
57
Cont..
These are usually database update operations that are explicitly applied to the
database
It may be necessary to write more than one trigger to cover all possible cases
These events are specified after the keyword BEFORE - which means that the trigger
should be executed before the triggering operation is executed
Use the keyword AFTER, which specifies that the trigger should be executed after the
operation specified in the event is completed.
Once the triggering event has occurred, an optional condition may be evaluated.
58
Cont..
If no condition is specified, the action will be executed once the event occurs. If a
condition is specified, it is first evaluated, and only if it evaluates to true will the rule
action be executed. The condition is specified in the WHEN clause of the trigger
The action is usually a sequence of SQL statements, but it could also be a database
transaction or an external program that will be automatically executed