Unit 2
Unit 2
Unit 2
Tuple: It is nothing but a single row of a table, which contains a single record.
Relation Schema: A relation schema represents the name of the relation with its
attributes.
Degree: The total number of attributes in the relation is called the degree of the
relation.
Cardinality: Total number of rows present in the Table.
Column: The column represents the set of values for a specific attribute.
Relation instance: Relation instance is a finite set of tuples in the RDBMS system.
Relation instances never have duplicate tuples.
Relation key: Every row has one, two or multiple attributes, which is called relation
key.
Attribute domain: Every attribute has some pre-defined value and scope which is
known as attribute domain
Advantages of Relational Database Model
Cardinality of a relation: no of rows in a table-3
Degree of a relation: no of columns in a table-3
Schema-Instance Distinction
Both of these help in describing the data available in a database.
Instance: The data which is stored in the database at a particular moment of time is
called an instance of the database.
Schema: The overall design of a database is called schema.
Physical Schema – This schema describes the DB designed at a physical level.
Logical Schema – This schema describes the DB designed at a logical level.
Difference Between Schema and Instance in DBMS
Alterations The schema remains the same for the One can change the instances of
entire database as a whole. data and information in a
database using updation, deletion,
and addition.
Keys are the entity set that is used to identify an entity within its entity set uniquely.
An entity set can have multiple keys, but out of which one key will be the primary
key.
ER Model to Relation Model
Introduction to Relational algebra & Relational
calculus
we discussed the designing of database using the Relational
model and E-R diagram. Now that we have designed the
database, we need to store and retrieve data from the database, for
this purpose we need to understand the concept of Relational
algebra and relational calculus.
Query Language
In simple words, a Language which is used to store and retrieve data
from database is known as query language.
There are two types of query language:
Introduction to Relational algebra & Relational calculus
It supports sub-programs
procedures, functions, packages, triggers
Types of blocks:
1. Anonymous block: It has no name and it cannot be called.
2. Named block: it has a name it can be called.
There are 4 types named blocks:1.Procedure
2. functions 3.packages 4.triggers
PL/SQL block contains 3 sections:
1.Declaration section
2.Executable section
3.Exception section
PL/SQL Introduction
Block structure:
Syntax
Declare
[Variable declaration];
Begin
<executable statements>;
Exception when <exception name> then
<executable statements>;
End
PL/SQL architecture
Example
SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT.PUT_LINE('HELLO WORLD');
DBMS_OUTPUT.PUT_LINE('WELCOME TO
MITS');
DBMS_OUTPUT.PUT_LINE('CSE-D SECTION');
END;
/
OUTPUT
HELLO WORLD
WELCOME TO MITS
CSE-D SECTION
PL/SQL procedure successfully completed.
Example
SET SERVEROUTPUT ON
DECLARE
MESG VARCHAR2(50);
BEGIN
MESG := 'HELLOWORLD';
DBMS_OUTPUT.PUT_LINE('message:'||MESG);
END;
/
OUTPUT:
message:HELLOWORLD
PL/SQL procedure successfully completed.
Example
DECLARE
a integer := 30;
b integer := 40;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 100.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
OUTPUT: value of c :70
value of f:33.3333333333
PL/SQL procedure successfully completed.
Example
SET SERVEROUTPUT ON
DECLARE
MESG VARCHAR(50);
BEGIN
MESG := '&Name';
DBMS_OUTPUT.PUT_LINE('my name is:'||MESG);
END;
/
OUTPUT:
Enter value for name: srinu
old 4: MESG := '&Name';
new 4: MESG := 'srinu';
my name is:srinu
FOR Loop in PL/SQL
FOR <LOOP-VARIABLE> IN
<LOWER-LIMIT> .. <HIGHER-LIMIT>
LOOP
<EXECUTION BLOCK STARTS>
.
.
<EXECUTION BLOCK ENDS>
END LOOP;
LOOP VARIABLE IS SELF INCREMENTAL.
LOOP VARIABLE NO NEED TO BE DECLARED
FOR LOOP EXAMPLE
DECLARE
A INTEGER;
BEGIN
DBMS_OUTPUT.PUT_LINE('PROGRAM STARTS');
FOR A IN 1..5
LOOP
DBMS_OUTPUT.PUT_LINE(A);
END LOOP;
DBMS_OUTPUT.PUT_LINE('PROGRAM ENDS');
END;
OUTPUT:
PROGRAM STARTS
1 2 3 4 5
FUNCTION in PL/SQL
The PL/SQL Function is very similar to PL/SQL Procedure.
The main difference between procedure and a function is, a function must
always return a value, and on the other hand, a procedure may or may not
return a value
Create a function:
Create function adder2(n1 in number, n2 in number)
return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;
/
OUTPUT:
Function created.
FUNCTION in PL/SQL
DECLARE
n3 number(2);
BEGIN
n3 := adder2(11,22);
dbms_output.put_line('Addition is: ' || n3);
END;
/
OUTPUT
Addition is: 33
FUNCTION in PL/SQL
DECLARE
a number;
b number;
c number;
FUNCTION findMax2(x number, y number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax2(a, b);
dbms_output.put_line(' Maximum number is: ' || c);
END;
/
OUTPUT : Maximum number is: 45
FUNCTION in PL/SQL
DECLARE
num number;
factorial number;
FUNCTION fact1(x number)
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact1(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
Difference between SQL and PL/SQL
No. Key SQL PL/SQL
Definition SQL, is Structural Query PL/SQL is a programming language
1 Language for the database. using SQL for a database.
2 Variables SQL has no variables. PL/SQL has variables, data types etc.
Control SQL has no FOR loop, if control PL/SQL has FOR loop, while loop, if
3 Structures and similar structures. controls and other similar structures.
Operations SQL can execute a single operation PL/SQL can perform multiple operation
4 at a time. at a time.
Language SQL is a declarative language. PL/SQL is a procedural language.
5 Type
Embedded SQL can be embedded in a PL/SQL PL/SQL can also be embedded in SQL
6 block. code.
Interaction SQL directly interacts with PL/SQL does not directly interacts with
6 database server. database server.
Orientation SQL is data oriented language. PL/SQL is application oriented
7 language.
Objective SQL is used to write queries, create PL/SQL is used to write program
8 and execute DDL and DML blocks, functions, procedures, triggers
statements. and packages.
ESCAPE clause in LIKE operator
What will be output if you are giving LIKE predicate as '%\_%' ESCAPE '\'
1. SELECT Mname FROM MANAGER WHERE Mname LIKE '%\_%' ESCAPE '\';
Ex: RAM_PATEL
2. SELECT Mname FROM MANAGER WHERE Mname LIKE '%@%ra%' ESCAPE
‘@';
Ex: Courier%rack
Embedded SQL
Embedded SQL is a method of combining the computing power of a programming
language and the database manipulation capabilities of SQL.
Embedded SQL statements are SQL statements written inline with the program source
code of the host language.
Host Language: any conventional language can be a host language, that is a language
which SQL calls are embedded.
Ex: C,C++,JAVA….
Connecting SQL to the Host Language
Preprocessor
Host language + Function calls
Some of the advantages of using SQL embedded in high-level languages are as follows:
Helps to access databases from anywhere.
Allows integrating authentication service for large scale applications.
Provides extra security to database transactions.
Avoids logical errors while performing transactions on our database.
Makes it easy to integrate the frontend and the backend of our application.
Static SQL
Efficiency Static SQL statements are more Dynamic SQL statements are less
faster and efficient. efficient.
Compilation Static SQL statements are compiled at Dynamic SQL statements are compiled at
compile time. run time.
Application Plan Application Plan parsing, validation, Application Plan parsing, validation, optimization
optimization and generation are and generation are run-time activities.
compile time activities.
Use Cases Static SQL is used in case of Dynamic SQL is used in case of non-
uniformly distributed data. uniformly distributed data.
OLD and NEW references are used for record level triggers these are not available for
table level triggers.
In a row level trigger, the trigger fires for each related row. And sometimes it is
required to know the value before and after the DML statement.
Oracle has provided two clauses in the RECORD-level trigger to hold these values.
We can use these clauses to refer to the old and new values inside the trigger body.
:NEW – It holds a new value for the columns of the base table/view during the trigger
execution
:OLD – It holds old value of the columns of the base table/view during the trigger
execution
Use of trigger
Triggers may be used for any of the following reasons
Useful for catching errors.
Prevention of invalid transactions
Imposing security authorizations
To implement any complex business rule, that cannot be implemented using integrity
constraints.
Triggers will be used to audit the process. For example, to keep track of changes made
to a table.
The trigger is used to perform automatic action when another concerned action takes
place.
Example of Statement level Trigger
create trigger csetgr before update on emp
begin
dbms_output.put_line(‘Table Updated');
end;
/
Trigger created.
SQL>update emp set salary=salary+5000 where salary<40000;
Table Updated
3 rows updated.
SQL>update emp set salary=salary+5000 where EID=2;
Table Updated
1 row updated
Example of Row level Trigger
create trigger emp before update on emp for each row
begin
dbms_output.put_line('Table Updated');
end;
/
Trigger created.
SQL> update emp set salary=salary+10000 where salary<50000;
Table Updated
Table Updated
Table Updated
Table Updated
4 rows updated.
SQL>update emp set salary=salary+10000 where eid=105;
Table Updated
Active Databases
A database with a set of associated triggers is generally called an active database.
It is a set of triggers, making it quite difficult to maintain.
Whenever a change is made to the database trigger gets activated. The action may in
turn activate other triggers or may activate the same trigger that initialized this action.
Such type of trigger that activates itself is called a recursive trigger
DBMS executes such chains of triggers in the same pre-defined manner but it affects
the concept of understanding the collection of triggers
Triggers maintain data integrity in the database
Triggers identify unusual events that occur in the database
Triggers are used for security checks and also for auditing
Stored Procedures
The PL/SQL stored procedure is a PL/SQL block which performs one or more
specific tasks.
It is just like procedures in other programming languages.
A procedure can be compiled and stored in the database as a schema object.
It promote reusability and maintainability
The procedure contains a header and a body.
Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
Body: The body contains a declaration section, execution section and exception
section similar to a general PL/SQL block.
Stored Procedure Syntax
CREATE [OR REPLACE] PROCEDURE
procedure_name [ (parameter1 [mode 1]) datatype,… ]
IS / AS
[declaration_section]
BEGIN
executable_section
[exception_section]
END [procedure_name];
Stored Procedure Example
Table creation:
create table user1(id number(10),name varchar(10));
Create Procedure Code:
create or replace procedure insertuser(id in number, name in varchar)
is
begin
insert into user1 values(id, name);
end;
/
Output: Procedure created.
Stored Procedure Example
Calling a Procedure:
1.SQL> EXECUTE insertuser(101,'Rahul');
Output: PL/SQL procedure successfully completed.
2.
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully');
END;
/
Output: record inserted successfully
PL/SQL procedure successfully completed.
DROP PROCEDURE:
DROP PROCEDURE procedure_name;
PL/SQL - Cursors
Oracle creates a memory area, known as the context area, for processing an SQL
statement, which contains all the information needed for processing the statement.
A cursor is a pointer to this context area. PL/SQL controls the context area through
a cursor.
A cursor holds the rows (one or more) returned by a SQL statement. The set of
rows the cursor holds is referred to as the active set.
Types of Cursors
There are two types of cursors:
Implicit cursors: Implicit cursors are
automatically created by Oracle whenever an
SQL statement is executed
Explicit cursors: Explicit cursors are
programmer-defined cursors for gaining more
control over the context area.
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement.
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.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor,
which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT.
Attributes & Description
%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.
%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.
%ISOPEN: Always returns FALSE for implicit cursors, because
Oracle closes the SQL cursor automatically after executing its
associated SQL statement.
%ROWCOUNT: Returns the number of rows affected by an
INSERT, UPDATE, or DELETE statement, or returned by a SELECT
INTO statement.
Any SQL cursor attribute will be accessed as sql%attribute_name.
Example of Implicit Cursors
DECLARE
total_rows number(2);
BEGIN
UPDATE customers 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;
/
OUTPUT:
6 customers selected
PL/SQL procedure successfully completed.
Explicit Cursors
Explicit cursors are programmer-defined cursors for
gaining more control over the context area. An explicit cursor
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.
Declaring the Cursor: Declaring the cursor defines the cursor with a name and the
associated SELECT statement.
Syntax: CURSOR c1 IS SELECT Id,Name from Emp;
Opening the Cursor: Opening the cursor allocates the memory for the cursor and
makes it ready for fetching the rows returned by the SQL statement into it.
Syntax: OPEN c1;
Fetching the Cursor: Fetching the cursor involves accessing one row at a time
Syntax: FETCH c1 INTO Eid,Ename;
Closing the Cursor: Closing the cursor means releasing the allocated memory.
Syntax: CLOSE c1;
Example of Explicit Cursors
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
OUTPUT:
1 Ashrith BKK
2 Harshini MPL
PL/SQL procedure successfully completed.
Introduction to JDBC
JDBC stands for “Java Data Base Connectivity”.
It is an API(Application Programming Interface) that defines how a java
programmer can access the database in tabular format from java code.
All direct interactions with a specific database happen through a database-specific
driver.
A driver is a software program that translates the ODBC or JDBC calls into
database-specific system calls.
The drivers translates the SQL commands from the application into database
commands.
Drivers are managed by driver managers
Architecture of JDBC
Architecture of JDBC
Application: The application initiates and terminates the connection with a
database.
JDBC API: The JDBC API allows java programs to execute SQL statements and
retrieve results.
Driver Manager: Load JDBC drivers and pass the JDBC function calls from the
application to the correct driver.
JDBC Drivers: intelligently communicates with the database.
Features of JDBC
JDBC is an API, using we can communicate with any database without rewriting
our java application.
Most of the JDBC drivers are implemented in JAVA. Hence JDBC is known as
platform-independent technology.
Using JDBC API we can able to perform all basic database operations easily.
Relational Calculus
Relational calculus is a non-procedural query language that tells the system what
data is to be retrieved but doesn’t tell how to retrieve it.
1. Tuple Relational Calculus
(TRC)
Tuple relational calculus is used for selecting those tuples that satisfy the given
condition.
Tuple Relational Calculus in DBMS uses a tuple variable (t) that goes to each row
of the table and checks if the predicate is true or false for the given row. Depending
on the given predicate condition, it returns the row or part of the row.
Tuple Relational Calculus expression Syntax
{T | P (T)} or {T | Condition (T)}
Where t is the tuple variable that runs over every Row, and P(t) is the predicate
logic expression or condition.
Example: Table Name: customer
Customer_id Name Zip code
1 Rohit 12345
2 Rahul 13245
3 Rohit 56789
4 Amit 12345.
Example 1: Write a TRC query to get all the data of a
customer whose zip code is 12345.
TRC Query: {t \| Customer(t) ∧ t[Zipcode] = 12345 }
1 Rohit 12345
4. Amit 12345
Domain Relational Calculus
(DRC)
In domain relational calculus the records are filtered based on the domains.
Domain Relational Calculus uses Domain variables to get the column values
required from the database based on the predicate expression or condition.
The Domain relational calculus expression syntax:
{ x1, x2, x3, ..., xn | P (x1, x2, x3, ... ,xn)}
x1, x2 are attributes and P is predicate expression or condition.
Example: Table Name: customer
Customer_id Name Zip code
1 Rohit 12345
2 Rahul 13245
3 Rohit 56789
4 Amit 12345.
Example 1: Write a DRC query to get all the data of customer
whose zip code is 12345.
DRC query: {<x1,x2,x3> | <x1,x2> ∈ Customer ∧ x3 = 12345 }
1 Rohit 12345
4. Amit 12345