0% found this document useful (0 votes)
2 views

dbms unit3

Uploaded by

sirisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

dbms unit3

Uploaded by

sirisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

SQL | Join (Inner, Left, Right and Full

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;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
1. Note: We can also write JOIN instead of INNER JOIN. JOIN is same
as INNER JOIN.
1.
Example Queries(INNER JOIN)
1.
 This query will show the names and age of students
enrolled in different courses.

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM


Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
 Output:

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;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
1. Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN,
both are same.

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;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
1. Note: We can also use RIGHT OUTER JOIN instead of RIGHT
JOIN, both are same.

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:

1. FULL JOIN: FULL JOIN creates the result-set by combining result of


both LEFT JOIN and RIGHT JOIN. The result-set will contain all the
rows from both the tables. The rows for which there is no matching,
the result-set will contain NULL values.Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
1.
1.
Example Queries(FULL JOIN):
1.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
1. Output:

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

PL/SQL is a block structured language that enables developers to combine the


power of SQL with procedural statements. All the statements of a block are passed
to oracle engine all at once which increases processing speed and decreases the
traffic.
Structure of PL/SQL Block:

PL/SQL extends SQL by adding constructs found in procedural languages, resulting


in a structural language that is more powerful than SQL. The basic unit in PL/SQL is
a block. All PL/SQL programs are made up of blocks, which can be nested within
each other.

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

There are several PL/SQL identifiers such as variables, constants, procedures,


cursors, triggers etc.
1. Variables:
Like several other programming languages, variables in PL/SQL must be
declared prior to its use. They should have a valid name and data type as well.
Syntax for declaration of variables:
variable_name datatype [NOT NULL := value ];
Example to show how to declare variables in PL/SQL :
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;
BEGIN
null;
END;
/
Output:
PL/SQL procedure successfully completed.
Explanation:
 SET SERVEROUTPUT ON: It is used to display the buffer used by the
dbms_output.
 var1 INTEGER : It is the declaration of variable, named var1 which is of
integer type. There are many other data types that can be used like float,
int, real, smallint, long etc. It also supports variables used in SQL as well
like NUMBER(prec, scale), varchar, varchar2 etc.
 PL/SQL procedure successfully completed.: It is displayed when the
code is compiled and executed successfully.
 Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.

1.1) INITIALISING VARIABLES:


The variables can also be initialised just like in other programming languages.
Let us see an example for the same:
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var1 INTEGER := 2 ;
var3 varchar2(20) := 'I Love DBMS' ;
BEGIN
null;
END; begin

/
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

PL/SQL procedure successfully completed.


Explanation:
 dbms_output.put_line : This command is used to direct the PL/SQL output
to a screen.
Procedures & Functions

"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.

We can pass parameters to procedures in three ways:

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.

A procedure may or may not return any value.

Syntax:

CREATE [OR REPLACE] PROCEDURE procedure_name (<Argument> {IN, OUT,


IN OUT} <Datatype>,…)
IS
Declaration section<variable, constant> ;
BEGIN
Execution section
EXCEPTION
Exception section
END
IS - marks the beginning of the body of the procedure and is similar to DECLARE in
anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE
together the procedure is created if no other procedure with the same name exists or the
existing procedure is replaced with the current code.
How to execute a Procedure?
There are two ways to execute a procedure :

 From the SQL prompt : EXECUTE [or EXEC] procedure_name;


 Within another procedure – simply use the procedure name : procedure_name;

Example:
create table named emp have two column id and salary with number datatype.

CREATE OR REPLACE PROCEDURE p1(id IN NUMBER, sal IN NUMBER)


AS
BEGIN
INSERT INTO emp VALUES(id, sal);
DBMD_OUTPUT.PUT_LINE('VALUE INSERTED.');
END;
/

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.

SQL>select * from emp;


ID SALARY
----- --------
2 5000

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:

CREATE [OR REPLACE] FUNCTION function_name [parameters]


RETURN return_datatype; {IS, AS}
Declaration_section <variable,constant> ;
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;

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.

 As a part of a SELECT statement : SELECT emp_details_func FROM dual;


 In a PL/SQL Statements like, : dbms_output.put_line(emp_details_func);

This line displays the value returned by the function .

Example:

create or replace function getsal (no IN number) return number


is
sal number(5);
begin
select salary into sal from emp where id=no;
return sal;
end;
/

Output:
Run SQL Command Line
SQL>select * from emp;
ID SALARY
----- --------
2 5000

SQL>start D://fun.sql
Function created.

SQL>select getsal(2) from dual;


GETSAL(2)
---------
5000
In the example we are retrieving the ‘salary’ of employee with id 2 to variable ‘sal’.
The return type of the function is number.
Destroying procedure and function :

Syntax:

DROP PROCEDURE/FUNCTION PROCEDURE/FUNCTION_NAME;

Procedures VS Functions:

 A function MUST return a value


 A procedure cannot return a value
 Procedures and functions can both return data in OUT and IN OUT parameters
 The return statement in a function returns control to the calling program and returns
the results of the function
 The return statement of a procedure returns control to the calling program and
cannot return a value
 Functions can be called from SQL, procedure cannot
 Functions are considered expressions, procedure are not

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:

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)
BEGIN
--- sql statements
END;

Each statements are described below :

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:

Create or replace Trigger np before insert on account for each row


Begin
IF :NEW.bal < 0 THEN
DBMS_OUTPUT.PUT_LINE('BALANCE IS NAGATIVE..');
END IF;
End;
/

Output:
Run SQL Command Line
SQL>start D://t.sql
Trigger created.

SQL>insert into account values(1,-100);


BALANCE IS NAGATIVE..
1 row 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.

 Row Level Triggers


 Statement Level Triggers
 Before Triggers
 After Triggers

Row Level Triggers :


Row level triggers execute once for each row in a transaction.
The commands of row level triggers are executed on all rows that are affected by the
command that enables the trigger.
For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired
once for each row affected by the UPDATE statement.
If the triggering statement affects no rows, the trigger is not executed at all.
Row level triggers are created using the FOR EACH ROW clause in the CREATE TRIGGER
command.
Application:
Consider a case where our requirement is to prevent updation of
empno 100 record cannot be updated, then whenever UPDATE statement update records,
there must be PL/SQL block that will be fired automatically by UPDATE statement to check
that it must not be 100, so we have to use Row level Triggers for that type of applications.
Statement Level Triggers :
Statement level triggers are triggered only once for each transaction.
For example when an UPDATE command update 15 rows, the commands contained in the
trigger are executed only once, and not with every processed row.
Statement level trigger are the default types of trigger created via the CREATE TRIGGER
command.

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.

The possible configurations are:

 BEFORE statement Trigger


 BEFORE row Trigger
 AFTER statement Trigger
 AFTER row Trigger

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:

DROP TRIGGER trigger_name;

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.

Recursion is typically characterized by three steps:

1 Initialization

2 Recursion, or repeated iteration of the logic through the hierarchy

3 Termination

Similarly, a recursive query has three execution phases:

1 Create an initial result set.

2 Recursion based on the existing result set.

3 Final query to return the final result set.


You can specify a recursive query by:

Preceding a query with the WITH RECURSIVE clause

Creating a view using the RECURSIVE clause in a CREATE VIEW statement

Consider the following employee table:

CREATE TABLE employee


(employee_number INTEGER
,manager_employee_number INTEGER
,last_name CHAR(20)
,first_name VARCHAR(30));

The table represents an organizational structure containing a hierarchy of employee-manager


data.

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:

WITH RECURSIVE temp_table (employee_number) AS


( SELECT root.employee_number
FROM employee root
WHERE root.manager_employee_number = 801
UNION ALL
SELECT indirect.employee_number
FROM temp_table direct, employee indirect
WHERE direct.employee_number =
indirect.manager_employee_number
)
SELECT * FROM temp_table ORDER BY employee_number;
In the example, temp_table is a temporary named result set that can be referred to in the
FROM clause of the recursive statement.

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

Recursion stops when no new rows are added to temp_table.

The final query is not part of the recursive WITH clause and extracts the employee
information out of temp_table:

SELECT * FROM temp_table ORDER BY employee_number;

Here are the results of the recursive query:

employee_number
---------------
1001
1002
1003
1004
1006
1008
1010
1011
1012
1014
1015
1016
1019

Accessing SQL from a Programming Language

• 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

Advanced SQL 2 JDBC

• 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

• Model for communicating with the database:

• Open a connection

• Create a “statement” object

• Execute queries using the statement object to send queries and fetch results

• Exception mechanism to handle errors J

You might also like