You are on page 1of 19

DBMS UNIT II

SSCITM

Relational Model concept

Relational model can represent as a table with columns and rows. Each row is known as a
tuple. Each table of the column has a name or attribute.

Domain: It contains a set of atomic values that an attribute can take.

Attribute: It contains the name of a column in a particular table. Each attribute Ai must have
a domain, dom(Ai)

Relational instance: In the relational database system, the relational instance is represented
by a finite set of tuples. Relation instances do not have duplicate tuples.

Relational schema: A relational schema contains the name of the relation and name of all
columns or attributes.

Relational key: In the relational key, each row has one or more attributes. It can identify the
row in the relation uniquely.

Example: STUDENT Relation

NAME ROLL_NO PHONE_NO ADDRESS AGE


Ram 14795 7305758992 Noida 24
Shyam 12839 9026288936 Delhi 35
Laxman 33289 8583287182 Gurugram 20
Mahesh 27857 7086819134 Ghaziabad 27
Ganesh 17282 9028 9i3988 Delhi 40
 In the given table, NAME, ROLL_NO, PHONE_NO, ADDRESS, and AGE are the
attributes.
 The instance of schema STUDENT has 5 tuples.

 t3 = <Laxman, 33289, 8583287182, Gurugram, 20>

Relational Algebra

Basic operations:

 Selection ( ) Selects a subset of rows from relation.


 Projection ( ) Deletes unwanted columns from relation.

 Cross-product ( ) Allows us to combine two relations.

 Set-difference ( ) Tuples in relation. 1, but not in relation. 2.

 Union (  ) Tuples in relation. 1 and in relation. 2.

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 1


DBMS UNIT II
SSCITM

Relational Algebra

Relational algebra is a procedural query language. It gives a step by step process to obtain the
result of the query. It uses operators to perform queries.

Types of Relational operation

1. Selection Operation:
 The select operation selects tuples that satisfy a given predicate.
 It is denoted by sigma (σ).

1. Notation:  σ p(r)  

Where:

σ is used for selection prediction


r is used for relation
p is used as a propositional logic formula which may use connectors like: AND OR and
NOT. These relational can use as relational operators like =, ≠, ≥, <, >, ≤.

For example: LOAN Relation

BRANCH_NAME LOAN_NO AMOUNT


Downtown L-17 1000
Redwood L-23 2000
Perryride L-15 1500
Downtown L-14 1500
Mianus L-13 500
Roundhill L-11 900
Perryride L-16 1300

Input:

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 2


DBMS UNIT II
SSCITM

1. σ BRANCH_NAME="perryride" (LOAN)  

Output:

BRANCH_NAME LOAN_NO AMOUNT


Perryride L-15 1500
Perryride L-16 1300

2. Project Operation:
 This operation shows the list of those attributes that we wish to appear in the result.
Rest of the attributes are eliminated from the table.
 It is denoted by ∏.

1. Notation:  ∏ A1, A2, An (r)   

Where A1, A2, A3 is used as an attribute name of relation r.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Input: ∏ NAME, CITY (CUSTOMER)  

Output:

NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 3


DBMS UNIT II
SSCITM

3. Union Operation:
 Suppose there are two tuples R and S. The union operation contains all the tuples that
are either in R or S or both in R & S.
 It eliminates the duplicate tuples. It is denoted by ∪.

1. Notation: R ∪ S   

A union operation must hold the following condition:

 R and S must have the attribute of the same number.


 Duplicate tuples are eliminated automatically.

Example: DEPOSITOR RELATION

CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

CUSTOMER_NAME LOAN_NO

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17

Input:

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 4


DBMS UNIT II
SSCITM

1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)  

Output:

CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes

4. Set Intersection:
 Suppose there are two tuples R and S. The set intersection operation contains all
tuples that are in both R & S.
 It is denoted by intersection ∩.

1. Notation: R ∩ S   

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)  

Output:

CUSTOMER_NAME

Smith

Jones

5. Set Difference:
 Suppose there are two tuples R and S. The set intersection operation contains all
tuples that are in R but not in S.

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 5


DBMS UNIT II
SSCITM

 It is denoted by intersection minus (-).

1. Notation: R - S  

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)  

Output:

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

6. Cartesian product
 The Cartesian product is used to combine each row in one table with each row in the
other table. It is also known as a cross product.
 It is denoted by X.

1. Notation: E X D  

Example:

EMPLOYEE

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B

DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 6


DBMS UNIT II
SSCITM

B Sales

C Legal

Input:

1. EMPLOYEE X DEPARTMENT  

Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

7. Rename Operation:

The rename operation is used to rename the output relation. It is denoted by rho (ρ).

Example: We can use the rename operator to rename STUDENT relation to STUDENT1.

1. ρ(STUDENT1, STUDENT)  

Relational Calculus

 Relational calculus is a non-procedural query language. In the non-procedural query


language, the user is concerned with the details of how to obtain the end results.
 The relational calculus tells what to do but never explains how to do.

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 7


DBMS UNIT II
SSCITM

Types of Relational calculus:

1. Tuple Relational Calculus (TRC)


 The tuple relational calculus is specified to select the tuples in a relation. In TRC,
filtering variable uses the tuples of a relation.
 The result of the relation can have one or more tuples.

Notation:

1. {T | P (T)}   or {T | Condition (T)}   

Where

T is the resulting tuples

P(T) is the condition used to fetch T.

For example:

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

OUTPUT: This query selects the tuples from the AUTHOR relation. It returns a tuple with
'name' from Author who has written an article on 'database'.

TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and
Universal Quantifiers (∀).

For example:

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

Output: This query will yield the same result as the previous one.

2. Domain Relational Calculus (DRC)


 The second form of relation is known as Domain relational calculus. In domain
relational calculus, filtering variable uses the domain of attributes.

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 8


DBMS UNIT II
SSCITM

 Domain relational calculus uses the same operators as tuple calculus. It uses logical
connectives ∧ (and), ∨ (or) and ┓ (not).
 It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable.

Notation:

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

Where

a1, a2 are attributes


P stands for formula built by inner attributes

For example:

1. {< article, page, subject > |  ∈ javatpoint ∧ subject = 'database'}  

Output: This query will yield the article, page, and subject from the relational javatpoint,
where the subject is a database.

EXPRESSIVE POWER OF ALGEBRA AND CALCULUS

1. The tuple relational calculus restricts to safe expression and is equal in expressive power to
algebra.
2. Thus for every relational algebra expression, there is an equivalent expression in the tuple
relational calculus expression, there is equivalent relational-algebra expression.
3. The expressive power of relational algebra is often used as how powerful a relational
database query language is.
4. The domain relational calculus is restricted to safe expressions,it is equivalent in
expressive power to the tuple relational calculus restricted to safe expression

More Examples of Algebra Queries

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 9


DBMS UNIT II
SSCITM

(Q1) Find the names of sailors who have reserved boat 103

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 10


DBMS UNIT II
SSCITM

THE FORM OF A BASIC SQL QUERY

The basic form of an SQL query is as follows:

SELECT [DISTINCT] select-list

FROM from-list

WHERE qualification

Every query must have a SELECT clause, which specifies columns to be retained in the
result, and a FROM clause, which specifies a cross-product of tables. The optional WHERE
clause specifies selection conditions on the tables mentioned in the FROM clause.

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 11


DBMS UNIT II
SSCITM

Examples of Basic SQL Queries

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 12


DBMS UNIT II
SSCITM

Expressions and Strings in the SELECT Command: SQL supports a more general version
of the select-list than just a list of colu1nns. Each item in a select-list can be of the form
expression AS column_name, where expression is any arithmetic or string expression over
column names and constants, and column name is a new name for this column in the output
of the query. It can also contain aggregates such as sum and count etc.

NESTED QUERIES

 One of the most powerful features of SQL is nested queries.


 A nested query is a query that has another query embedded within it; the embedded
query is called a sub-query.
 The embedded query can of course be a nested query itself; thus queries that have
very deeply nested structures are possible.
 When writing a query, we sometimes need to express a condition that refers to a table
that must itself be computed.
 The query used to compute this subsidiary table is a sub query and appears as part of
the main query. A sub-query typically appears within the WHERE clause of a query.
 Sub-queries can sometimes appear in the FROM clause or the HAVING clause.

Introduction to Nested Queries

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 13


DBMS UNIT II
SSCITM

Correlated Nested Queries


 In the nested queries seen thus far, the inner sub-query has been completely
independent of the outer query.
 In general, the inner sub-query could depend on the row currently being examined in
the outer query (in terms of our conceptual evaluation strategy).

The EXISTS operator is another set comparison operator, such as IN.

It allows us to test whether a set is nonempty, an implicit comparison with the empty set.

Thus, for each Sailor row 5, we test whether the set of Reserves rows R such that R.bid = 103
AND S.sid = R.sid is nonempty.

If so, sailor 5 has reserved boat 103, and we retrieve the name. The subquery clearly depends
on the current row S and must be re-evaluated for each row in Sailors.

The occurrence of S in the subquery (in the form of the literal S.sid) is called a correlation,
and such queries are called correlated queries.

Set-Comparison Operators:

 The set-comparison operators EXISTS, IN, and UNIQUE, are also with their negated
versions NOT.
 SQL also supports op ANY and op ALL, where op is one of the arithmetic comparison
operators {<, <=, =, <>, >=, >}. (SOME is also available, but it is just a synonym for
ANY.)

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 14


DBMS UNIT II
SSCITM

AGGREGATE OPERATORS

 SQL allows the use of arithmetic expressions. We consider a powerful class of


constructs for computing aggregate values such as MIN and SUM.
 These features represent a significant extension of relational algebra.
 SQL supports five aggregate operations, which can be applied on any column, say A, of
a relation:
1. COUNT ([DISTINCT] A): The number of (unique) values in the A column.
2. SUM ([DISTINCT] A): The sum of all (unique) values in the A column.
3. AVG ([DISTINCT] A): The average of all (unique) values in the A column.
4. MAX (A): The maximum value in the A column.
5. MIN (A): The minimum value in the A column.
Note that it does not make sense to specify DISTINCT in conjunction with MIN or MAX .

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 15


DBMS UNIT II
SSCITM

NULL VALUES

SQL provides a special column value called null to use if value is unknown. We use null
when the column value is either unknown or inapplicable.

Comparisons Using Null Values


 If we compare two null values using <, >, =, and so on, the result is always unknown.
For example, if we have null in two distinct rows of the sailor relation, any comparison
returns unknown.
 SQL also provides a special comparison operator IS NULL to test whether a column
value is null.

Logical Connectives AND, OR, and NOT

We must define the logical operators AND, OR, and NOT using a three-value logic in
which expressions evaluate to true(T), false(F), or unknown (U).

And OR
conditon1 condition2 Result conditon1 condition2 Result
F F F F F F
F T F F T T
F U F F U U
T F F
T F T
T T T
T T T
T U T
U MCA Dept.
Prepared by P. Sandeep Kumar, Asst. Prof U U Page 16
DBMS UNIT II
SSCITM

T U U
U U U

The expression NOT unknown is defined to be unknown.

Disallowing Null Values

We can disallow null values by specifying NOT NULL as part of the field definition.

for example : create table student( sname CHAR(20) NOT NULL);

In addition, the fields in a primary key are not allowed to take on null values. Thus, there is
an implicit NOT NULL constraint for every field listed in a PRIMARY KEY constraint.

COMPLEX INTEGRITY CONSTRAINTS IN SQL

Constraints over a Single Table:

We can specify complex constraints over a single table using table constraints, which have
the form CHECK conditional-expression. For example, to ensure that rating must be an
integer in the range 1 to 10, we could use:

To enforce the constraint that Interlake boats cannot be reserved, we could use:

Domain Constraints and Distinct Types

A user can define a new domain using the CREATE DOMAIN statement, which uses
CHECK constraints.

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 17


DBMS UNIT II
SSCITM

CREATE DOMAIN ratingval INTEGER DEFAULT 1

CHECK ( VALUE >= 1 AND VALUE <= 10 )

INTEGER is the underlying, or source, type for the domain ratingval, and every ratingval
value must be of this type. Values in ratingval are further restricted by using a CHECK
constraint; in defining this constraint, we use the keyword VALUE to refer to a value in the
domain.:

The optional DEFAULT keyword is used to associate a default value with a domain. If the
domain ratingval is used for a column in some relation and no value is entered for this
column in an inserted tuple, the default value 1 associated with ratingval is used.

CREATE TYPE ratingtype AS INTEGER

Assertions: ICs over Several Tables


Table constraints are associated with a single table, although the conditional expression in the
CHECK clause can refer to other tables. Table constraints are required to hold only if the
associated table is nonempty. Thus, when a constraint involves two or more tables, the table
constraint mechanism is sometimes cumbersome and not quite what is desired. To cover such
situations, SqL supports the creation of assertions, which are constraints not associated with
anyone table.

As an example, suppose that we wish to enforce the constraint that the number of boats plus
the number of sailors should be less than 100. (This condition might be required, say, to
qualify as a 'smaIl' sailing club.) We could try the following assertion:

CREATE ASSERTION smallClub CHECK (( SELECT COUNT (S.sid) FROM Sailors S )

+ ( SELECT COUNT (B. bid) FROM Boats B) < 100 )

TRIGGERS AND ACTIVE DATABASES

A trigger is a procedure that is automatically invoked by the DBMS in response to specified


changes to the database, and is typically specified by the DBA. A database that has a set of
associated triggers is called an active database. A trigger description contains three parts:

Event: A change to the database that activates the trigger.

Condition: A query or test that is run when the trigger is activated.

Action: A procedure that is executed when the trigger is activated and its condition is true.

A trigger can be thought of as a 'daemon' that monitors a database, and is executed when the
database is modified in a way that matches the event specification. An insert, delete, or
update statement could activate a trigger, regardless of which user or application invoked the
activating statement; users may not even be aware that a trigger was executed as a side effect
of their program.

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 18


DBMS UNIT II
SSCITM

A condition in a trigger can be a true/false statement.If the condition part evaluates to true,
the action associated with the trigger is executed.

A trigger action can examine the answers to the query in the condition part of the trigger,
refer to old and new values of tuples modified by the statement activating the trigger, execute
new queries, and make changes to the database.

In fact, an action can even execute a series of data-definition commands (e.g., create new
tables, change authorizations) and transaction-oriented commands (e.g., commit) or call host-
language procedures.

Examples of Triggers in SQL

DESIGNING ACTIVE DATABASES


Triggers offer a powerful mechanism for dealing with changes to a database, but they must be
used with caution. The effect of a collection of triggers can be very complex, and maintaining
an active database can become very difficult. Often, a judicious use of integrity constraints
can replace the use of triggers.

Why Triggers Can Be Hard to Understand


In an active database system, when the DBMS is about to execute a statement that modifies
the databa.se, it checks whether some trigger is activated by the statement. If so, the DBMS
processes the trigger by evaluating its condition part, and then executing its action part.

If a statement activates more than one trigger, the DBMS typically processes all of them, in
same arbitrary order. An important point is that the execution of the action part of a trigger
could in turn activate another trigger. In particular, the execution of the action part of a
trigger could again activate the same trigger; such triggers are called recursive triggers. The
potential for such chain activations and the unpredictable order in which a DBMS processes
activated triggers can make it difficult to understand the effect of a collection of triggers.

Prepared by P. Sandeep Kumar, Asst. Prof MCA Dept. Page 19

You might also like