Relational Algebra In Dbms Assignment

Lecture Notes: Relational Algebra

Det finns inget kapitel om relationsalgebra i kursen. Jag hade först tänkt ha med ett, men relationsalgebra passar inte riktigt i en grundkurs som den här. I stället finns en kort förklaring i ordlistan, och för den som vill läsa mer finns dessutom dessa föreläsningsanteckningar på engelska.

What? Why?

  • Similar to normal algebra (as in ), except we use relations as values instead of numbers, and the operations and operators are different.
  • Not used as a query language in actual DBMSs. (SQL instead.)
  • The inner, lower-level operations of a relational DBMS are, or are similar to, relational algebra operations. We need to know about relational algebra to understand query execution and optimization in a relational DBMS.
  • Some advanced SQL queries requires explicit relational algebra operations, most commonly outer join.
  • Relations are seen as sets of tuples, which means that no duplicates are allowed. SQL behaves differently in some cases. Remember the SQL keyword .
  • SQL is declarative, which means that you tell the DBMS what you want, but not how it is to be calculated. A C++ or Java program is procedural, which means that you have to state, step by step, exactly how the result should be calculated. Relational algebra is (more) procedural than SQL. (Actually, relational algebra is mathematical expressions.)

Set operations

Relations in relational algebra are seen as sets of tuples, so we can use basic set operations.

Review of concepts and operations from set theory

  • set
  • element
  • no duplicate elements (but: multiset = bag)
  • no order among the elements (but: ordered set)
  • subset
  • proper subset (with fewer elements)
  • superset
  • union
  • intersection
  • set difference
  • cartesian product

Projection

Example: The table E (for EMPLOYEE)
nrnamesalary
1John100
5Sarah300
7Tom100
SQLResultRelational algebra
select salary from E PROJECTsalary(E)
select nr, salary from E PROJECTnr, salary(E)

Note that there are no duplicate rows in the result.

Selection

The same table E (for EMPLOYEE) as above.
SQLResultRelational algebra
select * from E where salary < 200
nrnamesalary
1John100
7Tom100
SELECTsalary < 200(E)
select * from E where salary < 200 and nr >= 7 SELECTsalary < 200 and nr >= 7(E)

Note that the select operation in relational algebra has nothing to do with the SQL keyword . Selection in relational algebra returns those tuples in a relation that fulfil a condition, while the SQL keyword means "here comes an SQL statement".

Relational algebra expressions

SQLResultRelational algebra
select name, salary from E where salary < 200
namesalary
John100
Tom100
PROJECTname, salary (SELECTsalary < 200(E))

or, step by step, using an intermediate result

Temp <- SELECTsalary < 200(E)
Result <- PROJECTname, salary(Temp)

Notation

The operations have their own symbols. The symbols are hard to write in HTML that works with all browsers, so I'm writing PROJECT etc here. The real symbols:

Example: The relational algebra expression which I would here write as

PROJECTNamn ( SELECTMedlemsnummer < 3 ( Medlem ) )

should actually be written

Cartesian product

The cartesian product of two tables combines each row in one table with each row in the other table.

Example: The table E (for EMPLOYEE)

enrenamedept
1BillA
2SarahC
3JohnA

Example: The table D (for DEPARTMENT)

dnrdname
AMarketing
BSales
CLegal
SQLResultRelational algebra
select * from E, D
enrenamedeptdnrdname
1BillAAMarketing
1BillABSales
1BillACLegal
2SarahCAMarketing
2SarahCBSales
2SarahCCLegal
3JohnAAMarketing
3JohnABSales
3JohnACLegal
E X D
  • Seldom useful in practice.
  • Usually an error.
  • Can give a huge result.

Join (sometimes called "inner join")

The cartesian product example above combined each employee with each department. If we only keep those lines where the dept attribute for the employee is equal to the dnr (the department number) of the department, we get a nice list of the employees, and the department that each employee works for:
SQLResultRelational algebra
select * from E, D where dept = dnr
enrenamedeptdnrdname
1BillAAMarketing
2SarahCCLegal
3JohnAAMarketing
SELECTdept = dnr (E X D)

or, using the equivalent join operation

E JOINdept = dnr D

  • A very common and useful operation.
  • Equivalent to a cartesian product followed by a select.
  • Inside a relational DBMS, it is usually much more efficient to calculate a join directly, instead of calculating a cartesian product and then throwing away most of the lines.
  • Note that the same SQL query can be translated to several different relational algebra expressions, which all give the same result.
  • If we assume that these relational algebra expressions are executed, inside a relational DBMS which uses relational algebra operations as its lower-level internal operations, different relational algebra expressions can take very different time (and memory) to execute.

Natural join

A normal inner join, but using the join condition that columns with the same names should be equal. Duplicate columns are removed.

Renaming tables and columns

Example: The table E (for EMPLOYEE)
nrnamedept
1BillA
2SarahC
3JohnA

Example: The table D (for DEPARTMENT)

nrname
AMarketing
BSales
CLegal

We want to join these tables, but:

  • Several columns in the result will have the same name (nr and name).
  • How do we express the join condition, when there are two columns called nr?

Solutions:

  • Rename the attributes, using the rename operator.
  • Keep the names, and prefix them with the table name, as is done in SQL. (This is somewhat unorthodox.)
SQLResultRelational algebra
select * from E as E(enr, ename, dept), D as D(dnr, dname) where dept = dnr
enrenamedeptdnrdname
1BillAAMarketing
2SarahCCLegal
3JohnAAMarketing
(RENAME(enr, ename, dept)(E)) JOINdept = dnr (RENAME(dnr, dname)(D))
select * from E, D where dept = D.nr
nrnamedeptnrname
1BillAAMarketing
2SarahCCLegal
3JohnAAMarketing
E JOINdept = D.nr D

You can use another variant of the renaming operator to change the name of a table, for example to change the name of E to R. This is necessary when joining a table with itself (see below).

RENAMER(E)
A third variant lets you rename both the table and the columns:
RENAMER(enr, ename, dept)(E)

Aggregate functions

Example: The table E (for EMPLOYEE)
nrnamesalarydept
1John100A
5Sarah300C
7Tom100A
12AnnenullC
SQLResultRelational algebra
select sum(salary) from E Fsum(salary)(E)

Note:

  • Duplicates are not eliminated.
  • Null values are ignored.
SQLResultRelational algebra
select count(salary) from E Result: Fcount(salary)(E)
select count(distinct salary) from E Result: Fcount(salary)(PROJECTsalary(E))

You can calculate aggregates "grouped by" something:

SQLResultRelational algebra
select sum(salary) from E group by dept deptFsum(salary)(E)

Several aggregates simultaneously:

SQLResultRelational algebra
select sum(salary), count(*) from E group by dept deptFsum(salary), count(*)(E)

Standard aggregate functions: sum, count, avg, min, max

Hierarchies

Example: The table E (for EMPLOYEE)
nrnamemgr
1Gretchennull
2Bob1
5Anne2
6John2
3Hulda1
4Hjalmar1
7Usama4

Going up in the hierarchy one level: What's the name of John's boss?

SQLResultRelational algebra
select b.name from E p, E b where p.mgr = b.nr and p.name = "John" PROJECTbname ([SELECTpname = "John"(RENAMEP(pnr, pname, pmgr)(E))] JOINpmgr = bnr [RENAMEB(bnr, bname, bmgr)(E)])

or, in a less wide-spread notation

PROJECTb.name ([SELECTname = "John"(RENAMEP(E))] JOINp.mgr = b.nr [RENAMEB(E)])

or, step by step

P <- RENAMEP(pnr, pname, pmgr)(E)
B <- RENAMEB(bnr, bname, bmgr)(E)
J <- SELECTname = "John"(P)
C <- J JOINpmgr = bnr B
R <- PROJECTbname(C)

Notes about renaming:

  • We are joining E with itself, both in the SQL query and in the relational algebra expression: it's like joining two tables with the same name and the same attribute names.
  • Therefore, some renaming is required.
  • RENAMEP(E) JOIN...RENAMEB(E) is a start, but then we still have the same attribute names.

Going up in the hierarchy two levels: What's the name of John's boss' boss?

SQLResultRelational algebra
select ob.name from E p, E b, E ob where b.mgr = ob.nr where p.mgr = b.nr and p.name = "John" PROJECTob.name (([SELECTname = "John"(RENAMEP(E))] JOINp.mgr = b.nr [RENAMEB(E)]) JOINb.mgr = ob.nr [RENAMEOB(E)])

or, step by step

P <- RENAMEP(pnr, pname, pmgr)(E)
B <- RENAMEB(bnr, bname, bmgr)(E)
OB <- RENAMEOB(obnr, obname, obmgr)(E)
J <- SELECTname = "John"(P)
C1 <- J JOINpmgr = bnr B
C2 <- C1 JOINbmgr = bbnr OB
R <- PROJECTobname(C2)

Recursive closure

Both one and two levels up: What's the name of John's boss, and of John's boss' boss?
SQLResultRelational algebra
(select b.name ...) union (select ob.name ...) (...) UNION (...)

Recursively: What's the name of all John's bosses? (One, two, three, four or more levels.)

  • Not possible in (conventional) relational algebra, but a special operation called transitive closure has been proposed.
  • Not possible in (standard) SQL (SQL2), but in SQL3, and using SQL + a host language with loops or recursion.

Outer join

Example: The table E (for EMPLOYEE)
enrenamedept
1BillA
2SarahC
3JohnA

Example: The table D (for DEPARTMENT)

dnrdname
AMarketing
BSales
CLegal

List each employee together with the department he or she works at:

SQLResultRelational algebra
select * from E, D where edept = dnr

or, using an explicit join

select * from (E join D on edept = dnr)
enrenamedeptdnrdname
1BillAAMarketing
2SarahCCLegal
3JohnAAMarketing
E JOINedept = dnr D

No employee works at department B, Sales, so it is not present in the result. This is probably not a problem in this case. But what if we want to know the number of employees at each department?

SQLResultRelational algebra
select dnr, dname, count(*) from E, D where edept = dnr group by dnr, dname

or, using an explicit join

select dnr, dname, count(*) from (E join D on edept = dnr) group by dnr, dname
dnrdnamecount
AMarketing2
CLegal1
dnr, dnameFcount(*)(E JOINedept = dnr D)

No employee works at department B, Sales, so it is not present in the result. It disappeared already in the join, so the aggregate function never sees it. But what if we want it in the result, with the right number of employees (zero)?

Use a right outer join, which keeps all the rows from the right table. If a row can't be connected to any of the rows from the left table according to the join condition, null values are used:

SQLResultRelational algebra
select * from (E right outer join D on edept = dnr)
enrenamedeptdnrdname
1BillAAMarketing
2SarahCCLegal
3JohnAAMarketing
nullnullnullBSales
E RIGHT OUTER JOINedept = dnr D
select dnr, dname, count(*) from (E right outer join D on edept = dnr) group by dnr, dname
dnrdnamecount
AMarketing2
BSales1
CLegal1
dnr, dnameFcount(*)(E RIGHT OUTER JOINedept = dnr D)
select dnr, dname, count(enr) from (E right outer join D on edept = dnr) group by dnr, dname
dnrdnamecount
AMarketing2
BSales0
CLegal1
dnr, dnameFcount(enr)(E RIGHT OUTER JOINedept = dnr D)

Join types:

  • JOIN = "normal" join = inner join
  • LEFT OUTER JOIN = left outer join
  • RIGHT OUTER JOIN = right outer join
  • FULL OUTER JOIN = full outer join

Outer union

Outer union can be used to calculate the union of two relations that are partially union compatible. Not very common.

Example: The table R

Example: The table S

The result of an outer union between R and S:

Division

Who works on (at least) all the projects that Bob works on?

Semijoin

A join where the result only contains the columns from one of the joined tables. Useful in distributed databases, so we don't have to send as much data over the network.

Update

To update a named relation, just give the variable a new value. To add all the rows in relation N to the relation R:

R <- R UNION N


Relational Algebra


Previous Page

Next Page  


Relational database systems are expected to be equipped with a query language that can assist its users to query the database instances. There are two kinds of query languages − relational algebra and relational calculus.

Relational Algebra

Relational algebra is a procedural query language, which takes instances of relations as input and yields instances of relations as output. It uses operators to perform queries. An operator can be either unary or binary. They accept relations as their input and yield relations as their output. Relational algebra is performed recursively on a relation and intermediate results are also considered relations.

The fundamental operations of relational algebra are as follows −

  • Select
  • Project
  • Union
  • Set different
  • Cartesian product
  • Rename

We will discuss all these operations in the following sections.

Select Operation (σ)

It selects tuples that satisfy the given predicate from a relation.

Notation − σp(r)

Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula which may use connectors like and, or, and not. These terms may use relational operators like − =, ≠, ≥, < ,  >,  ≤.

For example

σsubject = "database"(Books)

Output − Selects tuples from books where subject is 'database'.

σsubject = "database" and price = "450"(Books)

Output − Selects tuples from books where subject is 'database' and 'price' is 450.

σsubject = "database" and price = "450" or year > "2010"(Books)

Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those books published after 2010.

Project Operation (∏)

It projects column(s) that satisfy a given predicate.

Notation − ∏A1, A2, An (r)

Where A1, A2 , An are attribute names of relation r.

Duplicate rows are automatically eliminated, as relation is a set.

For example

subject, author (Books)

Selects and projects columns named as subject and author from the relation Books.

Union Operation (∪)

It performs binary union between two given relations and is defined as −

r ∪ s = { t | t ∈ r or t ∈ s}

Notation − r U s

Where r and s are either database relations or relation result set (temporary relation).

For a union operation to be valid, the following conditions must hold −

  • r, and s must have the same number of attributes.
  • Attribute domains must be compatible.
  • Duplicate tuples are automatically eliminated.
author (Books) ∪ ∏ author (Articles)

Output − Projects the names of the authors who have either written a book or an article or both.

Set Difference (−)

The result of set difference operation is tuples, which are present in one relation but are not in the second relation.

Notationrs

Finds all the tuples that are present in r but not in s.

author (Books) − ∏ author (Articles)

Output − Provides the name of authors who have written books but not articles.

Cartesian Product (Χ)

Combines information of two different relations into one.

Notation − r Χ s

Where r and s are relations and their output will be defined as −

r Χ s = { q t | q ∈ r and t ∈ s}

σauthor = 'tutorialspoint'(Books Χ Articles)

Output − Yields a relation, which shows all the books and articles written by tutorialspoint.

Rename Operation (ρ)

The results of relational algebra are also relations but without any name. The rename operation allows us to rename the output relation. 'rename' operation is denoted with small Greek letter rhoρ.

Notationρx (E)

Where the result of expression E is saved with name of x.

Additional operations are −

  • Set intersection
  • Assignment
  • Natural join

Relational Calculus

In contrast to Relational Algebra, Relational Calculus is a non-procedural query language, that is, it tells what to do but never explains how to do it.

Relational calculus exists in two forms −

Tuple Relational Calculus (TRC)

Filtering variable ranges over tuples

Notation − {T | Condition}

Returns all tuples T that satisfies a condition.

For example

{ T.name | Author(T) AND T.article = 'database' }

Output − Returns tuples with 'name' from Author who has written article on 'database'.

TRC can be quantified. We can use Existential (∃) and Universal Quantifiers (∀).

For example

{ R| ∃T   ∈ Authors(T.article='database' AND R.name=T.name)}

Output − The above query will yield the same result as the previous one.

Domain Relational Calculus (DRC)

In DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as done in TRC, mentioned above).

Notation

{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}

Where a1, a2 are attributes and P stands for formulae built by inner attributes.

For example

{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}

Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is database.

Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also involves relational operators.

The expression power of Tuple Relation Calculus and Domain Relation Calculus is equivalent to Relational Algebra.


Previous Page

Print

PDF

Next Page  


Categories: 1

0 Replies to “Relational Algebra In Dbms Assignment”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *