0% found this document useful (0 votes)
20 views104 pages

Introduction to Relational Algebra

The document provides an overview of relational algebra, including its purpose, fundamental operations such as selection, projection, and various join types. It also discusses embedded SQL, JDBC, and the steps for establishing a connection to a database using Java. Key concepts include the use of cursors for data manipulation and the execution of SQL statements through different interfaces in JDBC.

Uploaded by

jaysondmello04
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)
20 views104 pages

Introduction to Relational Algebra

The document provides an overview of relational algebra, including its purpose, fundamental operations such as selection, projection, and various join types. It also discusses embedded SQL, JDBC, and the steps for establishing a connection to a database using Java. Key concepts include the use of cursors for data manipulation and the execution of SQL statements through different interfaces in JDBC.

Uploaded by

jaysondmello04
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

MODULE 3

RELATIONAL ALGEBRA
Introduction to relation algebra
•Relational Algebra is a procedural query language.
•Relational algebra mainly provides a theoretical foundation for
relational databases and SQL.
•The main purpose of using Relational Algebra is to define operators
that transform one or more input relations into an output relation.
•Relational algebra operations are performed recursively on a relation
•The output of these operations is a new relations, which might be
formed from one or more relation
WHY STUDY RELATIONAL ALGEBRA
Fundamental operations in
relational algebra
Selection Operator (σ sigma)
•Selection Operator (σ) performs a selection operation.
•It selects those rows or tuples from the table which satisfies the
selection condition.
•It works with rows(tuples)
Syntax
σ<selection_condition>(R)
Selection Condition
• Simple selection condition:
<attribute> operator <constant/attribute>
•Consider this student table
Example 1
Select tuples from a relation “Student” where subject is “Physics”
σsubject = “Physics” (Student)
Example 2
Select tuples from a relation “STUDENT” where Name is “Ali” and age
is “20”
σName = “Ali” AND age = 20 (STUDENT)
Selection Condition - Examples
Projection Operator (π pie)
•Projection Operator (π) displays the columns of a table based
on the specified attributes.
•It just works on Columns
Syntax
π<attribute list>(R)
•Consider this student table
Example 1
• Display the id and name of students
πID, Name(Student)
Example 2
•Display the name of students
πName(Student)
Rename Operation (ρ rho)
• To rename relation the rename operation is used which allows us to rename the
output relation
• ’Rename’ operation is denoted with rho(ρ)

Syntax:
ρ x (R)
Where the result of current table with expression R is saved with new table name
of x.
Example 1
•change the name of above table to “STD_Result” Table: Student
ρ STD_Result (Student)
•Consider this student table
Example 1
•Change the Name of Output table Select ID, Name from “Student”
table where Subject is “Physics” and rename the output table to
STD_Result as well

ρ STD_Result (πID, Name (σsubject = “Physics” (Student)))


Example 2
Find the name of all instructors in the physics department
CLASS WORK
Convert the sql query to relational algebra expression
1. SELECT name , age FROM dogs WHERE age = 1 2;
2. SELECT name , age FROM dogs WHERE age = 12 AND name =
‘Timmy ’ ;
CLASS WORK
Union operators (u) or (|)
•Let A and B be two relations.

Then

•A ∪ B is the set of all tuples belonging to either A or B or both.


•In A ∪ B, duplicates are automatically removed.
•Union operation is both commutative and associative.
Example
Example
Example
Intersection Operator (∩) or (&)
•Intersection operator is the reverse of Union operator. So, this Operator
can derive from Union Operator. This operator can define as follows

Let A and B two relations.

Then

•A∩ B is the set of all tuples belonging to both A and B.


•In A∩ B, duplicates are automatically removed.
•Intersection operation is both commutative and associative.
Example
Example
Example
CLASS WORK
1. Consider a query to find the set of all courses taught in the fall 2009
semester, the spring 2010 semester, or both

2. To find the set of all courses taught in the particular year we


Difference Operator (-)
•Let A and B be two relations.

•Then

•A – B is the set of all tuples belonging to A and not to B.


•In A – B, duplicates are automatically removed.
•Difference operation is associative but not commutative.
Example
example 2
Exercise 1

Assume the following relations:


BOOKS(DocId, Title, Publisher, Year)
STUDENTS(StId, StName, Major, Age)
AUTHORS(AName, Address)
borrows(DocId, StId, Date)
has-written(DocId, AName)
describes(DocId, Keyword)
1. List the year and title of each book.
2. List all information about students whose major is CS.
3. List all books published by McGraw-Hill before 1990.
4. List the name of those authors who are living in Davis.
5. List the name of students who are older than 30 and who are not
studying CS
6. Rename AName in the relation AUTHORS to Name.
cartesian product Binary operator
• If R and S are two relations,
R XS is the set of all concatenated tuples <x,y>,
where x is a tuple in R and y is a tuple in S
CLASS WORK

1. List all students with the books they can borrow.


2. List the names of all students who have borrowed a book and who
are CS majors.
Join operator ⋈ Binary operator

R ⋈<𝑗𝑜𝑖𝑛 𝑐𝑜𝑛𝑑𝑖𝑡𝑖𝑜𝑛>S

• where join condition is a Boolean expression involving attributes from both


operand relations
• Like cross product, combine tuples from two relations into single “longer”
tuples, but only those that satisfy matching condition
• Formally, a combination of cross product and select
Join operation = select operation + cartesian product operation

𝑅 ⋈<𝑗𝑜𝑖𝑛 𝑐𝑜𝑛𝑑𝑖𝑡𝑖𝑜𝑛> 𝑆 = 𝜎<𝑗𝑜𝑖𝑛 𝑐𝑜𝑛𝑑𝑖𝑡𝑖𝑜𝑛> (𝑅 × S)


variants of join
EQUIJOIN
NATURAL JOIN
OUTER JOIN
NATURAL JOIN (*)
When join operation is performed on
two tables having a common attribute
with the same name, it is known as
natural join.
Consider the following two tables. Let
them be named as R and S .
EQUIJOIN(⋈)
Equijoin(⋈): Equijoin is a special case of conditional join where only
equality condition holds between a pair of attributes.
• As values of two attributes will be equal in result of equijoin, only one
attribute will be appeared in result.
• This equality is indicated with an equal sign (=) as the comparison operator
1. List all employee names and the department names they work for?
π Dname,fname,lname(EMPLOYEE ⋈dno=dnumberDEPARTMENT)

2. What are the names and salaries of all department managers?


π Dname,fname,lname(DEPARTMENT ⋈mgr_ssn=ssnEMPLOYEE)
OUTER JOIN
• Outer Join in Relational algebra returns all the attributes of both the table
depending on the condition.
• If some attribute value is not present for any one of the tables it returns
NULL in the respective row of the table attribute.
Left outer join ( ⟕ )

Here all the tuples of A will be projected. If


some value of a common attribute is missing
in table B, we add the tuples from A but keep
NULL in tuples from table B.
In the left join all the tuples of table A are
present, but not necessarily all the tuples
from B.
Right outer join( ⟖ )
The right outer join is going to contain
all the tuples from table B.
Here since there is no student with
stud_id=105 in table A, the value in the
corresponding stud_name is NULL .
Full outer join ( ⟗ )
The full outer join contains all tuples
from both tables.
CLASS WORK
Consider the two tables T1 and T2. Show the results of the following
operations
Division Operator (÷): Binary operator

•Returns every tuples from R that matches all tuples in S


• The division operator is used for queries which involve the ‘all’.
embedded sql
• Embedded SQL is the one which combines the high level language with the
DB language like SQL.
• It allows the application languages to communicate with Data Base and get
requested result.
• The high level languages which supports embedding SQLs within it are
also known as host language.
• There are different host languages which support embedding SQL within it
like C, C++, ADA, Pascal, FORTRAN, Java etc. When SQL is embedded
within C or C++, then it is known as Pro*C/C++ or simply Pro*C
language.
embedded sql

• High-level programming language compilers cannot interpret, SQL


statements
• Hence source code files containing embedded SQL statements must be
preprocessed before compiling.
embedded sql
• Thus each SQL statement coded in a high-level programming
language source code file must be prefixed with the keywords EXEC
SQL and terminated with either a semicolon or the keywords
END_EXEC
• The Database Manager cannot work directly with high-level
programming language variables.
• Instead, it must use special variables known as host variables to move
data between an application and a database.
• Two types of Host variables:-
1. Input Host Variables – Transfer data to database
2. Output Host Variables – receives data from database
EXAMPLE
embedded sql
Variables used must be declared within DECLARE section
embedded sql
embedded sql
Connecting to a Database
Connection (multiple connections are possible but only one is
active)
CONNECT TO server-name AS connection-name
AUTHORIZATION user-account-info;

Change from an active connection to another one


SET CONNECTION connection-name;
Disconnection
DISCONNECT connection-name;
example
communication variables(sqlcode &
sqlstate )
SQLCODE and SQLSTATE communication variables
Used by DBMS to communicate exception or error conditions
SQLCODE variable
0 = statement executed successfully
100 = no more data available in query result
< 0 = indicates some error has occurred (e.g., -803 means "duplicate key")
communication variables(sqlcode
& sqlstate )
SQLSTATE
String of five characters
‘00000’ = no error or exception
Other values indicate various errors or exceptions
For example, ‘02000’ indicates ‘no more data’ when using SQLSTATE
EXAMPLE
EXAMPLE
CURSOR
cursor is a database object used to retrieve and manipulate data row by row
from a result set returned by a query.
Cursors provide a way to sequentially process a set of rows in a controlled
manner, which is especially useful when dealing with large datasets or when
row-by-row processing is required.
Declaring a Cursor:
The cursor is declared with a SQL query that defines the result set. This
does not execute the query; it just sets up the cursor with the specified SQL
statement.

DECLARE cursor_name CURSOR FOR


SELECT column1, column2 FROM table_name
WHERE condition;
Opening a Cursor:
The OPEN statement executes the query associated with the
cursor and positions the cursor before the first row of the result
set.

OPEN cursor_name;
EXAMPLE
Fetching Rows:
The FETCH statement retrieves the next row from the result set
and stores it in the host variables. This operation can be repeated to
fetch subsequent rows.

FETCH cursor_name INTO :host_variable1, :host_variable2;


Closing a Cursor:
The CLOSE statement deallocates the cursor and frees up any resources
associated with it.

CLOSE cursor_name;
EXAMPLE
DYNAMIC SQL
Dynamic SQL refers to the technique of generating and executing SQL
statements at runtime, rather than hard-coding them into a program at compile
time.
This approach allows for flexibility in constructing SQL queries based on
varying conditions, user inputs, or runtime information.

EXAMPLE IN PDF
WHAT IS JDBC
JDBC is an API (Application Programming Interface) provided by Java
that allows Java applications to connect to and interact with databases.
JDBC DRIVER
A JDBC driver is a software component that allows Java applications to interact
with a specific type of database or data source.
Each JDBC driver translates JDBC API calls into specific commands or protocols
understood by the respective DBMS or data source.
Types of JDBC Driver
JDBC : TYPE 1 driver(JDBC-ODBC Bridge
Driver)
JDBC : TYPE 2 driver(Native API Driver)
JDBC : TYPE 3 driver(Network Protocol
Driver)
JDBC : TYPE 4 driver(Thin Driver)
JDBC PROGRAMMING STEPS
IMPORT PACKAGES
import [Link].*;
This package provides classes and interfaces to perform most of the JDBC
functions like creating and executing SQL queries.
LOAD THE JDBC DRIVER
First, we should load/register the driver in the program before connecting to the
Database. You need to register it only once per database in the program.

We can load the driver in the following 2 ways:

1. [Link]()
2. [Link]()
(i) [Link]()
In this way, the driver’s class file loads into the memory at runtime. It implicitly
loads the driver. While loading, the driver will register with JDBC automatically .
LOAD THE JDBC DRIVER
(ii) [Link]()
DriverManager is an inbuilt class that is available in the [Link] package. It
acts as a mediator between Java application and database which you want to
connect. Before you connect with the database, you need to register the
driver with DriverManager. The main function of DriverManager is to load
the driver class of the Database and create a connection with DB.

[Link](new [Link]())
Establish Connection
DriverManager class has the getConnection method, To call getConnection()
method, we need to pass 3 parameters. The 3 parameters are string data type URL,
a username, and a password to access the database.

The getConnection() method is an overloaded method. The 2 methods are:

● getConnection(URL,username,password); – It has 3 parameters URL,


username, password.
● getConnection(URL); – It has only one parameter. URL has a username
and password also.
Create And Execute Statement
Once the connection has established, we can interact with the connected Database.
First, we need to create the statement to perform the SQL query and then execute the
statement.
Now we will create the statement object that runs the query with the connected
database. We use the createStatement method of the Connection class to create the
query.
There are 3 statement interfaces are available in the [Link] package. These are
explained below:
a) Statement
This interface is used to implement simple SQL statements with no parameter. It returns
the ResultSet object.
Create And Execute Statement
b) PreparedStatement
This PreparedStatement interface extends the Statement interface. So, it
has more features than the Statement interface. It is used to implement
parameterized and precompiled SQL statements. The performance of the
application increases because it compiles the query only once.
It is easy to reuse this interface with a new parameter. It supports the IN
parameter. Even we can use this statement without any parameter.
Create And Execute Statement
c) CallableStatement interface extends the PreparedStatement interface.
So, it has more features than the PreparedStatement interface. It is used to
implement a parameterized SQL statement that invokes procedure or
function in the database. A stored procedure works like a method or function
in a class. It supports the IN and OUT parameters.

The CallableStatement instance is created by calling the prepareCall method


of the Connection object.
Create And Execute Statement
(ii) Execute The Query
There are 4 important methods to execute the query in
Statement interface. These are explained below:
● ResultSet executeQuery(String sql)
● int executeUpdate(String sql)
● boolean execute(String sql)
● int []executeBatch()
Create And Execute Statement
a) ResultSet executeQuery(String sql)
The executeQuery() method in Statement interface is used to execute the SQL
query and retrieve the values from DB. It returns the ResultSet object. Normally,
we will use this method for the SELECT query.
b) executeUpdate(String sql)
The executeUpdate() method is used to execute value specified queries like
INSERT, UPDATE, DELETE (DML statements), or DDL statements that return
nothing. Mostly, we will use this method for inserting and updating.
Create And Execute Statement
c) execute(String sql)
The execute() method is used to execute the SQL query. It returns true if it
executes the SELECT query. And, it returns false if it executes INSERT or
UPDATE query.
d) executeBatch()
This method is used to execute a batch of SQL queries to the Database and if all
the queries get executed successfully, it returns an array of update counts. We
will use this method to insert/update the bulk of records.
.
Retrieve Results
When we execute the queries using the executeQuery() method,
the result will be stored in the ResultSet object.
The returned ResultSet object will never be null even if there is
no matching record in the table. ResultSet object is used to
access the data retrieved from the Database.
Close Connection
Finally, we are done with manipulating data in DB. Now we can
close the JDBC connection. We need to make sure that we have
closed the resource after we have used it. If we don’t close them
properly we may end up out of connections.
When we close the connection object, Statement and ResultSet
objects will be closed automatically.

You might also like