dbms unit3
dbms unit3
Joins)
A SQL Join statement is used to combine data or rows from two or more
tables based on a common field between them. Different types of Joins are:
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
Consider the two tables below:
Student
StudentCourse
The simplest Join is INNER JOIN.
1. INNER JOIN: The INNER JOIN keyword selects all rows from both
the tables as long as the condition satisfies. This keyword will create
the result-set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
1. LEFT JOIN: This join returns all the rows of the table on the left side
of the join and matching rows for the table on the right side of join.
The rows for which there is no matching row on right side, the result-
set will contain null. LEFT JOIN is also known as LEFT OUTER
JOIN.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
1.
Example Queries(LEFT JOIN):
1.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
1. Output:
1. RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns
all the rows of the table on the right side of the join and matching
rows for the table on the left side of join. The rows for which there is
no matching row on left side, the result-set will contain null. RIGHT
JOIN is also known as RIGHT OUTER JOIN.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
1.
Example Queries(RIGHT JOIN):
1.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
1. Output:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
PL/SQL Introduction
Typically, each block performs a logical action in the program. A block has the
following structure:
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
Declare section starts with DECLARE keyword in which variables, constants,
records as cursors can be declared which stores data temporarily. It basically
consists definition of PL/SQL identifiers. This part of the code is optional.
Execution section starts with BEGIN and ends with END keyword.This is a
mandatory section and here the program logic is written to perform any task like
loops and conditional statements. It supports
all DML commands, DDL commands and SQL*PLUS built-in functions as well.
Exception section starts with EXCEPTION keyword.This section is optional
which contains statements that are executed when a run-time error occurs. Any
exceptions can be handled in this section.
PL/SQL identifiers
/
Output:
PL/SQL procedure successfully completed.
Explanation:
Assignment operator (:=) : It is used to assign a value to a variable.
2. Displaying Output:
The outputs are displayed by using DBMS_OUTPUT which is a built-in package
that enables the user to display output, debugging information, and send
messages from PL/SQL blocks, subprograms, packages, and triggers.
Let us see an example to see how to display a message using PL/SQL :
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var varchar2(40) := 'I love DBMS' ;
BEGIN
dbms_output.put_line(var);
END;
/
Output:
I love DBMS
"A procedures or function is a group or set of SQL and PL/SQL statements that perform a
specific task."
A function and procedure is a named PL/SQL Block which is similar . The major difference
between a procedure and a function is, a function must always return a value, but a
procedure may or may not return a value.
Procedures:
A procedure is a named PL/SQL block which performs one or more specific task. This is
similar to a procedure in other programming languages. A procedure has a header and a
body.
The header consists of the name of the procedure and the parameters or variables passed
to the procedure.
The body consists or declaration section, execution section and exception section similar to
a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it is
named for repeated usage.
Parameters Description
IN type These types of parameters are used to send values to stored procedures.
OUT type These types of parameters are used to get values from stored procedures.
This is similar to a return type in functions.
IN OUT These types of parameters are used to send values and get values from
type stored procedures.
Syntax:
Example:
create table named emp have two column id and salary with number datatype.
Output:
Run SQL Command Line
SQL>set serveroutput on
SQL>start D://pr.sql
Procedure created.
SQL>exec p1(5,4);
VALUE INSERTED.
PL/SQL procudere successfully completed.
Functions:
A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a
procedure may or may not return a value.
Syntax:
RETURN TYPE: The header section defines the return type of the function. The return
datatype can be any of the oracle datatype like varchar, number etc.
The execution and exception section both should return a value which is of the datatype
defined in the header section.
How to execute a Function?
A function can be executed in the following ways.
Example:
Output:
Run SQL Command Line
SQL>select * from emp;
ID SALARY
----- --------
2 5000
SQL>start D://fun.sql
Function created.
Syntax:
Procedures VS Functions:
Triggers
A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete,
Update is executed on a database table. A trigger is triggered automatically when an
associated DML statement is executed.
Syntax:
Statement Description
CREATE [OR This clause creates a trigger with the given name or overwrites an
REPLACE ] TRIGGER existing trigger with the same name.
trigger_name
{BEFORE | AFTER | This clause indicates at what time the trigger should get fired. i.e for
INSTEAD OF } example: before or after updating a table. INSTEAD OF is used to
create a trigger on a view. before and after cannot be used to create
a trigger on a view.
{INSERT [OR] | This clause determines the triggering event. More than one
UPDATE [OR] | triggering events can be used together separated by OR keyword.
DELETE} The trigger gets fired at all the specified triggering event.
[OF col_name] This clause is used with update triggers. This clause is used when you
want to trigger an event only when a specific column is updated.
CREATE [OR This clause creates a trigger with the given name or overwrites an
REPLACE ] TRIGGER existing trigger with the same name.
trigger_name
[ON table_name] This clause identifies the name of the table or view to which the
trigger is associated.
[REFERENCING OLD This clause is used to reference the old and new values of the data
AS o NEW AS n] being changed. By default, you reference the values as
:old.column_name or :new.column_name. The reference names can
also be changed from old (or new) to any other user-defined name.
You cannot reference old values when inserting a record, or new
values when deleting a record, because they do not exist.
[FOR EACH ROW] This clause is used to determine whether a trigger must fire when
each row gets affected ( i.e. a Row Level Trigger) or just once when
the entire sql statement is executed(i.e.statement level Trigger).
WHEN (condition) This clause is valid only for row level triggers. The trigger is fired only
for rows that satisfy the condition specified.
Example:
Output:
Run SQL Command Line
SQL>start D://t.sql
Trigger created.
Types of Triggers
A trigger's type is defined by the type of triggering transaction and by the level at which the
trigger is executed. Oracle has the following types of triggers depending on the different
applications.
Application:
Consider a case where our requirement is to prevent the DELETE operation
during Sunday. For this whenever DELETE statement deletes records, there must be PL/SQL
block that will be fired only once by DELETE statement to check that day must not be
Sunday by referencing system date, so we have to use Statement level Trigger for which
fires only once for above application.
Before Trigger :
Since triggers are executed by events, they may be set to occur immediately before or after
those events.
When a trigger is defined, you can specify whether the trigger must occur before or after
the triggering event i.e. INSERT, UPDATE, or DELETE commands.
BEFORE trigger execute the trigger action before the triggering statement.
These types of triggers are commonly used in the following situation:
1. BEFORE triggers are used when the trigger action should determine whether or not
the triggering statement should be allowed to complete.
2. By using a BEFORE trigger, you can eliminate unnecessary processing of the
triggering statement.
3. For example: To prevent deletion on Sunday, for this we have to use Statement level
before trigger on DELETE statement.
4. BEFORE triggers are used to derive specific column values before completing a
triggering INSERT or UPDATE statement.
After Trigger :
AFTER trigger executes the trigger action after the triggering statement is executed.
AFTER triggers are used when you want the triggering statement to complete before
executing the trigger action.
For example: To perform cascade delete operation, it means that user delete the record fro
one table, but the corresponding records in other tables are delete automatically by a
trigger which fired after the execution of delete statement issued by the user.
When combining the different types of triggering actions, there are mainly 4 possible Valid
trigger types available to us.
Dropping Triggers :
Triggers may be dropped via the drop trigger command. In order to drop a trigger, you must
either own the trigger or have the DROP ANY TRIGGER system privilege.
Syntax:
Example:
Run SQL Command Line
SQL>DROP TRIGGER emp;
Trigger dropped.
ecursive Queries
A recursive query is a way to query hierarchies of data, such as an organizational structure,
bill-of-materials, and document hierarchy.
1 Initialization
3 Termination
The following figure depicts what the employee table looks like hierarchically.
The following recursive query retrieves the employee numbers of all employees who directly
or indirectly report to the manager with employee_number 801:
The initial result set is established in temp_table by the nonrecursive, or seed, statement and
contains the employees that report directly to the manager with an employee_number of 801:
SELECT root.employee_number
FROM employee root
WHERE root.manager_employee_number = 801
The recursion takes place by joining each employee in temp_table with employees who
report to the employees in temp_table. The UNION ALL adds the results to temp_table.
SELECT indirect.employee_number
FROM temp_table direct, employee indirect
WHERE direct.employee_number =
indirect.manager_employee_number
The final query is not part of the recursive WITH clause and extracts the employee
information out of temp_table:
employee_number
---------------
1001
1002
1003
1004
1006
1008
1010
1011
1012
1014
1015
1016
1019
• A database programmer must have access to a general-purpose programming language for at least
two reasons
• Not all queries can be expressed in SQL, since SQL does not provide the full expressive power of a
general-purpose language
• Non-declarative actions – such as printing a report, interacting with a user, or sending the results
of a query to a graphical user interface – cannot be done from within SQL
• There are two approaches to accessing SQL from a general-purpose programming language
• A general-purpose program – can connect to and communicate with a database server using a
collection of functions
• Embedded SQL – provide a means by which a program can interact with a database server
• The SQL statements are translated at compile time into function calls
• At runtime, these function calls connect to the database using an API that provides dynamic SQL
facilities
• JDBC is a Java API for communicating with database systems supporting SQL
• JDBC supports a variety of features for querying and updating data, and for retrieving query results
• JDBC also supports metadata retrieval, such as querying about relations present in the database
and the names and types of relation attributes
• Open a connection
• Execute queries using the statement object to send queries and fetch results