You are on page 1of 48

CS1254 – DATABASE MANAGEMENT SYSTEMS 34

16 Mark Questions

1. Explain DBMS System Architecture.


2. Explain E-R Model in detail with suitable example.
3. Explain about various data models.
4 Draw an E – R Diagram for Banking, University, Company, Airlines, ATM, Hospital, Library, Super
market, Insurance Company.
5. Explain in details about the various database languages.
6. Discuss about various operations in Relational Databases.
7. Discuss about database users and administrators.

UNIT II

RELATIONAL MODEL

The relational Model – The catalog- Types– Keys - Relational Algebra – Domain Relational Calculus –
Tuple Relational Calculus - Fundamental operations – Additional Operations- SQL fundamentals -
Integrity – Triggers - Security – Advanced SQL features –Embedded SQL– Dynamic SQL- Missing
Information– Views – Introduction to Distributed Databases and Client/Server Databases

1. THE RELATIONAL MODEL


STRUCTURE OF RELATIONAL DATABASES:
A relational database consists of a collection of tables, each of which is assigned a unique name.
A row in a table represents a relationship among a set of values.
BASIC STRUCTURE
Each column header is attributes. Each attribute allows a set of permitted values called domain of
that attribute.
A table of n-attributes must be a subset of
D 1 × D 2 × ・ ・ ・ × Dn.1 × Dn
A relation is a cartesian product of list of domains.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 35

Mathematically table is called as a relation and rows in a table are called as tuples.
The tuples in a relation can be either sorted or unsorted.
Several attributes can have same domain. E.g.: customer_name, employee_name.
Attributes can also be distinct. E.g.: balance, branch_name
Attributes can have null values incase if the value is unknown or does not exist.
Database schema begins with upper case and database relation begins with lower case.
Account-schema = (account-number, branch-name, balance)
account (Account-schema)

Account Table

2. THE CATALOG
The catalog is a place where all the schemas and the corresponding mappings are kept.
The catalog contains detailed information also called as descriptor information or meta data.
Descriptor information is essential for the system to perform its job properly.
For example the authorization subsystem uses catalog information about users and security
constraints to grant or deny access to a particular user.
The catalog should be self describing.

3. RELATIONAL ALGEBRA

The relational algebra is a procedural query language.


It consists of a set of operations that take one or two relations as input and produce a new relation as
their result.
Formal Definition
A basic expression in the relational algebra consists of either one of the following:
A relation in the database
A constant relation
Let E1 and E2 be relational-algebra expressions; the following are all relational-algebra expressions:
E1 E2

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 36

E1 – E2
E1 x E2
p (E1), P is a predicate on attributes in E1
s (E1), S is a list consisting of some of the attributes in E1
x (E1), x is the new name for the result of E1

Operations can be divided into


Basic operations or Fundamental Operations -Select, Project, Union, rename, set difference &
Cartesian product.
Additional operations that can be expressed in terms of basic operations-Set intersection, Natural
join Division and Assignment.
Extended operations-Generalized projection, Aggregate operations and Outer join.

3.1. BASIC OPERATIONS OR FUNDAMENTAL OPERATIONS


The select, project, and rename operations are called unary operations, because they operate on one
relation.
The other three operations (union, set difference, cartesian product) operate on pairs of relations and
are, therefore, called binary operations.
The basic or fundamental operations are as follows
1. Select
2. Project
3. Union
4. Rename
5. Set difference
6. Cartesian product.
1. Select Operation (σ)
Te select operation selects tuples that satisfy a given predicate.
Syntax
σ<select condition>(R)
Symbol σ is used to denote the select operator.
Predicate appears as a subscript to σ and argument relation in paranthesis.
Example
Consider the loan relation

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 37

Query: σ branch-name =―Perryridge‖ (loan)

Output relation is

Select operation allows all comparisons using =, _=, <, ., >,.


It allows combination of server predicates using connectives like and ( ), or ( ), and not (¬).

E.g.: 1. σ amount>1200 (loan)


2. σ branch-name =―Perryridge‖ amount>1200 (loan)
Other Examples
Consider following Book relation.
Book_Id Title Author Publisher Year Price
B001 DBMS Korth McGraw_Hill 2000 250
B002 Compiler Ulman 2004 350
B003 OOMD Rambaugh 2003 450
B004 PPL Sabista 2000 500

Following are the some examples of the select operation.


Example 1: Display books published in the 2000.
Query 1: σyear=2000(Book)
The output of query 1 is shown below.

Book_Id Title Author Publisher Year Price


B001 DBMS Korth McGraw_Hill 2000 250
B004 PPL Sabista 2000 500

Example 2: Display all books having price greater than 300.


Query 2: σprice>300(Book)
The output of query 2 is shown below.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 38

Book_Id Title Author Publisher Year Price


B002 Compiler Ulman 2004 350
B003 OOMD Rambaugh 2003 450
B004 PPL Sabista 2000 500

Example 3: Select the tuples for all books whose publishing year is 2000 or price is greater than 300.
Query 3: σ(year=2000) OR (price>300)(Book)
The output of query 3 is shown below.

Book_Id Title Author Publisher Year Price


B001 DBMS Korth McGraw_Hill 2000 250
B002 Compiler Ulman 2004 350
B003 OOMD Rambaugh 2003 450
B004 PPL Sabista 2000 500

Example 4: Select the tuples for all books whose publishing year is 2000 and price is greater than 300.
Query 3: σ(year=2000) AND (price>300)(Book)
The output of query 4 is shown below.

Book_Id Title Author Publisher Year Price


B004 PPL Sabista 2000 500

2. Project operation (Π)

The project operation selects certain columns from a table while discarding others. It removes any
duplicate tuples from the result relation.

Syntax
Π<attributelist> ( R )

The symbol Π (pi) is used to denote the project operation


Attribute list to be projected is specified as subscript of Π and R denotes the relation.

E.g.: Π loan-number, amount(loan)

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 39

Example: The following are the examples of project operation on Book relation.
Example 1: Display all titles with author name.
Query 1: ΠTitle, Author (Book)
The output of query 1 is shown below.
Title Author
DBMS Korth
Compiler Ulman
OOMD Rambaugh
PPL Sabista
Example 2: Display all book titles with authors and price.
Query 2: ΠTitle, Author, Price ( Book )
The output of query 2 is shown below.
Title Author Price
DBMS Korth 250
Compiler Ulman 350
OOMD Rambaugh 450
PPL Sabista 500
Composition of select and project operations
The relational operations select and project can be combined to form a complicated query.
Π customer-name (σ customer-city =―Harrison‖ (customer))

Input Table: customer

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 40

Output:
Customer-name

Hayes

Example: Display the titles of books having price greater than 300.
Query: ΠTitle,( σprice>300(Book))
The output of query 1 is shown below.
Title
Compiler
OOMD
PPL

3. Rename operation (ρ)


In relational algebra, you can rename either the relation or the attributes or both. The general rename
operation can take any of the following forms:
Syntax
ρs(new attribute names)( R )  renames both the relation and its attributes

ρs( R ) renames only the relation

ρ(new attribute names)( R )renames only the attribute name


The symbol ‗ρ‘ (rho) is used to denote the RENAME operator.
‗S‘ is the new relation

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 41

‗R‘ is original relation.

Example 1: Renames both the relation and its attributes, the second renames the relation only and the third
renames as follows.

*ρ Temp(Bname, Aname, Pyear, Bprice) ( Book )

Example 2: Only the relation name is renamed.

*ρTemp (Book)

Example 3: Only the attribute names are renamed

*ρ (Bname, Aname, Pyear, Bprice)( Book )

4. Union operation (U)


For union operation (r U s) to be valid two condition should be satisfied.
1. Relation r and s should have the same number of attributes.
2. The domain value of ith attribute of r and ith attribute of s must be the same for all i.
Syntax: Relation1 U Relation 2
Example: Consider the two relations:

To find the names of all customers with a loan in the bank:


Πcustomer -name (borrower)
To find the names of all customers with an account in the bank:
Πcustomer -name (depositor )
Union of these two sets; that is, To find customer names that appear in either or both of the two relations.
Πcustomer -name (borrower) U Πcustomer-name (depositor )
The result relation for this query:

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 42

5. Set Difference Operation (-)


To find tuples that is in one relation but is not in another. The two condition of union operation aso
apply for set difference.
Syntax: Relation1 - Relation 2
Example: find all customers of the bank who have an account but not a loan.
Πcustomer -name (depositor ) − Πcustomer -name (borrower)
The result relation for this query

6. Cartesian-Product Operation(X)
Cartesian product is also known as CROSS PRODUCT or CROSS JOINS.
Cartesian product allows us to combine information from any 2 relation.
Syntax: Relation1 x Relation 2
Example: Consider following two relations publisher_info and Book_info.

Publisher_Info
Publisher_code Name
P0001 McGraw_Hill
P0002 PHI
P0003 Pearson

Book_Info
Book_ID Title
B0001 DBMS

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 43

B0002 Compiler
The Cartesian product of Publisher_Info and Book_Info is given in fig .

Publisher_Info X Book_Info
Publisher_code Name Book_ID Title
P0001 McGraw_Hill B0001 DBMS
P0002 PHI B0001 DBMS
P0003 Pearson B0001 DBMS
P0001 McGraw_Hill B0002 Compiler
P0002 PHI B0002 Compiler
P0003 Pearson B0002 Compiler

3.2. ADDITIONAL OPERATIONS


1. Set intersection
2. Natural join
3. Division
4. Assignment
1. Set intersection Operation ( )
The result of intersection operation is a relation that includes all tuples that are in both Relation1 and
Relation2.
The intersection operation is denoted by depositor borrower.
Syntax: Relation1 Relation 2
Example:
Π customer -name (borrower) Π customer -name (depositor )
The result relation for this query:

2. Natural join ( )

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 44

The natural join operation performs a selection on those attributes that appear in both relation
schemes and finally removes duplicate attributes.
Syntax: Relation1 Relation 2
Example: consider the 2 relations

Employee Salary

Emp_code Emp_name Emp_code Salary

E0001 Hari E0001 2000

E0002 Om E0002 5000

E0003 Smith E0003 7000

E0004 Jay E0004 10000

Query:Π emp_name, salary (employee salary)

The output of query is:

Emp_name Salary
Hari 2000
Om 5000
Smith 7000
Jay 10000

3. Division operation (÷)

Division Operation is suited to queries that include the phrase ‗for all‘.

Syntax: Relation1 ÷ Relation 2


Example: Consider three relations:

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 45

Account Relation Branch Relation

Depositor Relation

Suppose that we wish to find all customers who have an account at all the branches located in Brooklyn.
Step 1: We can obtain all branches in Brooklyn by the expression
r 1 = Π branch-name (σ branch-city =―Brooklyn‖ (branch))
The result relation for this expression is shown in figure.

Step 2: We can find all (customer-name, branch-name) pairs for which the customer has an account at a
branch by writing
r 2 = Π customer -name, branch-name (depositor account)
Figure shows the result relation for this expression.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 46

Now, we need to find customers who appear in r 2 with every branch name in r 1. The operation that
provides exactly those customers is the divide operation.
Thus, the query is
Π customer -name, branch-name (depositor account)
÷ Π branch-name (σ branch-city =―Brooklyn‖ (branch))
The result of this expression is a relation that has the schema (customer-name) and that contains the tuple
(Johnson).
4. The Assignment Operation ( )
The assignment operation works like assignment in a programming language.
Example:

Result of the expression to the right of the ← is assigned to the relation variable on the left of the←.
With the assignment operation, a query can be written as a sequential program consisting of a series
of assignments followed by an expression whose value is displayed as the result of the query.

3.3. EXTENDED RELATIONAL-ALGEBRA OPERATIONS

1. Generalized projection
2. Aggregate operations
3. Outer join.
1. Generalized projection
The generalized-projection operation extends the projection operation by allowing arithmetic
functions to be used in the projection list.
The generalized projection operation has the form

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 47

ΠF 1, F2,..., Fn(E)
Where E is any relational-algebra expression, and each of F 1, F 2, . . . , Fn is an arithmetic
expression involving constants and attributes in the schema of E.
Example: Suppose we have a relation credit-info, as in Figure

Query: Π customer -name, (limit − credit-balance) as credit-available (credit-info )


Result of this query:

2. Aggregate Functions
Aggregate functions take a collection of values and return a single value as a result. Few Aggregate
Function are,
1. Avg
2. Min
3. Max
4. Sum
5. Count
1. Avg: The aggregate function avg returns the average of the values.
Example: Use the pt-works relation in Figure

Suppose that we want to find out the average of salaries.

G avg (salary)(pt-works)

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 48

The symbol G is the letter G in calligraphic font; read it as ―calligraphic G.‖

Result:
Salary
2062.5

2. Min and Max


Min: Return the minimum values in a collection
Max: Return the Maximum values in a collection

Example: branch-name G sum (salary) as sum-salary, max (salary) as max-salary (pt-works)


Result:

The attribute branch-name in the left-hand subscript of G indicates that the input relation pt-
works must be divided into groups based on the value of branch-name.
The calculated sum is placed under the attribute name sum-salary and the maximum salary is
placed under the attribute max-salary.
3. Sum:
The aggregate function sum returns the total of the values.
Example: Suppose that we want to find out the total sum of salaries.
G sum(salary)(pt-works)
The symbol G is the letter G in calligraphic font; read it as ―calligraphic G.‖
Result:
Salary
16500

4. Count:
Returns the number of the elements in the collection,

Example: G count-distinct(branch-name) (pt-works)

Result: The result of this query is a single row containing the value 3.
3. Outer join
Joins are classified into three types namely:

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 49

1. Inner Join
2. Outer Join
3. Natural Joint

Inner Join ( )
Inner Join returns the matching rows from the tables that are being jointed.
Example: Consider the two relations

Example:
Result:

Outer Join
The outer-join operation is an extension of the join operation to deal with missing information.
Outer-join operations avoid loss of information.
Outer Joins are classified into three types namely:
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join

1. Left Outer Join ( )

The left outer join ( ) takes all tuples in the left relation that did not match with any tuple in the
right relation, pads the tuples with null values for all other attributes from the right relation, and adds them
to the result of the natural join.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 50

Example:
Result:

2. Right Outer Join ( )


The right outer join ( ) is symmetric with the left outer join: It pads tuples from the right relation
that did not match any from the left relation with nulls and adds them to the result of the natural join.
Example:
Result:

3. Full Outer Join ( )

The full outer join( ) does both of those operations, padding tuples from the left relation that did
not match any from the right relation, as well as tuples from the right relation that did not match any from
the left relation, and adding them to the result of the join.

Example:
Result:

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 51

4. RELATIONAL CALCULUS
Relational Calculus is a formal query language where we can write one declarative expression to
specify a retrieval request and hence there is no description of how to retrieve it.
A calculus expression specifies what is to be retrieved rather than how to retrieve it.
Relational Calculus is considered to be non procedural language.
Relational Calculus can be divided into
1. Tuple Relational Calculus
2. Domain Relational Calculus

4.1. TUPLE RELATIONAL CALCULUS


Tuple Relational Calculus is a nonprocedural query language.
A query in the Tuple Relational Calculus is expressed as follows
{t | P (t ) }
It is the set of all tuples t such that predicate P is true for t
t r denotes that tuple t is in relation r
P is a formula similar to that of the predicate calculus
A tuple variable is said to be a free variable unless it is quanti.ed by a or .
t ∈ loan ∃ s ∈ customer(t[branch-name] = s[branch-name])

t is a free variable. Tuple variable s is said to be a bound variable.


A tuple-relational-calculus formula is built up out of atoms. An atom has one of the
following forms:
1. s r , where s is a tuple variable and r is a relation

2. s[x] u[y], where s and u are tuple variables, x is an attribute on which s is defined, y is

an attribute on which u is defined, and is a comparison operator


3. s[x] c, where s is a tuple variable, x is an attribute on which s is defined, is a
comparison operator, and c is a constant in the domain of attribute x
Rules to built formulas from atoms
An atom is a formula.
If P 1 is a formula, then so are ¬P 1 and (P 1).
If P 1 and P 2 are formulae, then so are P 1 P 2, P 1 P 2, and P 1 ⇒ P 2.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 52

If P 1(s) is a formula containing a free tuple variable s, and r is a relation, then


∃ s ∈ r (P 1(s)) and ∀ s ∈ r (P 1(s)) are also formulae.
Equivalence relation in Tuple relational calculus
P1 P2 is equivalent to ¬ (¬ (P1) ¬ (P2)).
∀ t ∈ r (P1(t)) is equivalent to ¬ ∃ t ∈ r (¬P1(t)).
P1 ⇒ P2 is equivalent to ¬ (P1) P2.
Banking Example
1. branch (branch_name, branch_city, assets )
2. customer (customer_name, customer_street, customer_city )
3. account (account_number, branch_name, balance )
4. loan (loan_number, branch_name, amount )
5. depositor (customer_name, account_number )
6. borrower (customer_name, loan_number )
Example Queries
1. Find the loan_number, branch_name, and amount for loans of over $1200
{t | t loan t [amount ] 1200}
2. Find the loan number for each loan of an amount greater than $1200
{t | s loan (t [loan_number ] = s [loan_number ] s [amount ] 1200)}

Notice that a relation on schema [loan_number] is implicitly defined by the query

3. Fin
d the names of all customers having a loan, an account, or both at the bank

{t | s borrower ( t [customer_name ] = s [customer_name ]) u depositor ( t [customer_name


] = u [customer_name ])

4. Find the names of all customers who have a loan and an account at the bank

{t | s borrower ( t [customer_name ] = s [customer_name ]) u depositor ( t [customer_name


] = u [customer_name] )

5. Find the names of all customers having a loan at the Perryridge branch

{t | s borrower (t [customer_name ] = s [customer_name ] u loan (u [branch_name ] =


―Perryridge‖ u [loan_number ] = s [loan_number ]))}

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 53

Safety of Expressions

A tuple relational calculus may generate an infinite relation.


For example, { t | t loan} results in infinitely many tuples that are not in loan relation.
To guard against the problem, a domain is defined for all tuple relational calculus formula P.
It is denoted by dom(P). it denotes that P can take value only in that domain.
An expression {t | P (t )} in the tuple relational calculus is safe if every component of t appears in
one of the relations, tuples, or constants that appear in P

4.2. DOMAIN RELATIONAL CALCULUS


Domain relational calculus is also a nonprocedural query language equivalent in power to the tuple
relational calculus.
It servers as the theoretical basis of widely used Query By Example (QBE) language.
Domain relational calculus expression is of the form:
{ x1, x2, …, xn | P (x1, x2, …, xn)}
x1, x2, …, xn represent domain variables.
P represents a formula composed of atoms.
An atom in Domain relational calculus has one of the following form
1. < x1, x2, . . . , xn > r, where r is a relation on n attributes and x1, x2, . . . , xn are domain
variables or domain constants.
2. x y, where x and y are domain variables and is a comparison operator
3. x c, where x is a domain variable, is a comparison operator, and c is a constant.

Rules to built formulas from atoms


An atom is a formula.
If P 1 is a formula, then so are ¬P 1 and (P 1).
If P 1 and P 2 are formulae, then so are P 1 P 2, P 1 P 2, and P 1 ⇒ P 2.
If P 1(x) is a formula in x, where x is a free domain variable, then
∃ x (P 1(x)) and ∀ x (P 1(x)) are also formulae.
Example Queries

1. Find the loan_number, branch_name, and amount for loans of over $1200

{ l, b, a | l, b, a loan a > 1200}

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 54

2. Find the names of all customers who have a loan of over $1200

{ c | l, b, a ( c, l borrower l, b, a loan a > 1200)}

3. Find the names of all customers who have a loan from the Perryridge branch and the loan
amount:
{ c, a | l ( c, l borrower b ( l, b, a loan b = ―Perryridge‖))}
{ c, a | l ( c, l borrower l, “ Perryridge”, a loan)}
Safety of Expressions
The expression: { x1, x2, …, xn | P (x1, x2, …, xn )} is safe if all of the following hold:
1. All values that appear in tuples of the expression are values from dom (P) (that is, the values appear
either in P or in a tuple of a relation mentioned in P).
2. For every ―there exists‖ subformula of the form x (P 1(x)), the subformula is true if and only if there
is a value of x in dom (P 1) such that P 1(x) is true.
3. For every ―for all‖ subformula of the form x (P 1 (x)), the subformula is true if and only if P 1(x) is
true for all values x from dom (P 1).

5. SQL FUNDAMENTALS
5.1. Introduction
SQL is a standard common set used to communicate with the relational database
management systems.
All tasks related to relational data management-creating tables, querying, modifying, and
granting access to users, and so on.
5.2. Advantages of SQL
SQL is a high level language that provides a greater degree of abstraction than procedural languages.
SQL enables the end-users and systems personnel to deal with a number of database management
systems where it is available.
Application written in SQL can be easily ported across systems.
SQL specifies what is required and not how it should be done.
SQL was simple and easy to learn can handle complex situations.
All SQL operations are performed at a set level.
5.3. Parts of SQL
The SQL language has several parts:

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 55

Data-definition language (DDL). The SQL DDL provides commands for defining relation
schemas, deleting relations, and modifying relation schemas.
Interactive data-manipulation language (DML). The SQL DML includes a query language based
on both the relational algebra and the tuple relational calculus. It also includes commands to insert
tuples into, delete tuples from, and modify tuples in the database.
View definition. The SQL DDL includes commands for defining views.
Transaction control. SQL includes commands for specifying the beginning and ending of
transactions.
Embedded SQL and dynamic SQL. Embedded and dynamic SQL define how SQL statements can
be embedded within general-purpose programming languages, such as C, C++, Java, PL/I, COBOL,
Pascal, and FORTRAN.
Integrity. The SQL DDL includes commands for specifying integrity constraints that the data stored
in the database must satisfy. Updates that violate integrity constraints are disallowed.
Authorization. The SQL DDL includes commands for specifying access rights to relations and
views.
5.4. Domain Types in SQL
1. Char (n): Fixed length character string, with user-specified length n.
2. varchar(n): Variable length character strings, with user-specified maximum length n.
3. int: Integer (a finite subset of the integers that is machine-dependent).
4. Smallint: Small integer (a machine-dependent subset of the integer domain type).
5. numeric (p,d): fixed point number, with user-specified precision of p digits, with n digits to the
right of decimal point.
6. Real, double precision: Floating point and double-precision floating point numbers, with
machine-dependent precision.
7. float (n): Floating point number, with user-specified precision of at least n digits.
8. Date: Dates, containing a (4 digit) year, month and date
Example: date ‗2005-7-27‘
9. Time: Time of day, in hours, minutes and seconds.
Example: time ‗09:00:30‘ time ‗09:00:30.75‘
10. Timestamp: date plus time of day
Example: timestamp ‗2005-7-27 09:00:30.75‘
11. Interval: period of time

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 56

Example: interval ‗1‘ day

5.5. DATA DEFINITION LANGUAGE (DDL)


It is used to create a table, alter the structure of a table and also drop the table.
DDL Commands
1. CREATE – Command used for creating tables.

Syntax: create table <table name> (columnname1 data type (size), Columnname 2 data

type(size),.., columnname n data type(size));

Example: create table customer (cust_name varchar2 (15), social_security_no

number(11),cust_street varchar2(7),cust_city varchar2(10));

2. DESC – Command used to view the table structure.


Syntax: desc <table name>;
Example: desc customer;

3. ALTER – Command used for modifying table structure.


i) Syntax: alter table <table name> modify (columnname data type (new size));
Example: alter table customer modify (cust_street varchar2 (10));

ii) Syntax: alter table <table name> modify (columnname new data type (size));
Example: alter table customer modify (social_security_no varchar2 (11));

iii) Syntax: alter table <table name> add (new columnname data type (size));
Example: alter table customer add (acc_no varchar2(5));

iv) Syntax: alter table<table name> drop (column name);

Example: alter table customer drop (acc_no);

4. RENAME – used to change the name of the table.


Syntax: rename <Old table name> to <New table name>;
Example: rename cust to cust1;

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 57

5. DROP – Command used for removing an existing table.


Syntax: drop table <table name>;
Example: drop table cust1;

5.6. DATA MANIPULATION LANGUAGE (DML)


Data Manipulation language commands let user to insert, modify and delete the data from
database.
DDL Commands
1. INSERT – To insert one or more number of Rows
Syntax 1: insert into <table name> values (List of Data Values)
Syntax 2: insert into <table name> (column names) values (list of data values)
Insert command using User interaction
Syntax 3: insert into <Table name> values (&columnname1, &columnname2…)

2. SELECT – To display one or more rows


Syntax 1: select * from <table name>;
Syntax 2: select columnname1, columnname 2 from <table name>;
Syntax 3: select * from <table name> where <condition>;

Example:
a) Find the names of all branches in the loan table
select branch_name from loan;
b) List all account numbers made by brighton branch
select acc_no from account where branch_name = 'brighton';
c) List the customers who are living in the city harrison
select cust_name from customer where cust_city = 'harrison';

3. UPDATE – Used to alter the column values in a table

Syntax: update <table name> set column_name=new_value where <condition>;


Example: update the account table to replace the balance value 500 to 450.
Query: update account set balance=450 where acc_no=‘A-101‘;

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 58

4. DELETE – Used to delete one or more rows.

Syntax: delete from <table name> where <condition>;


Example: delete from borrower where cust_name=‘jackson‘;

5.7. BASIC STRUCTURE OF SQL EXPRESSION


SQL expression consists of three clauses:
Select: The select clause corresponds to projection operation of the relational algebra. It is used to
list the attributes desired in the result of a query.
From: The from clause corresponds to the Cartesian product operation of the relational algebra .It
lists the relations to be scanned in the evaluation of the expression.
Where: The where clause corresponds to the selection predicate of the relations that appear in the
form clause.
General form of SQL query
Select A1, A2…………., An

From R1, R2……………, Rm

Where P

Where, A1-represent an attribute


R1-represent relation
P-is a predicate
Example:
―Find the names of all branches in the loan relation‖:
select branch-name from loan
select distinct branch-name from loan /*Distinct keyword eleminates duplicates*/
select all branch-name from loan /*Duplicates are not removed*/
―Find all loan numbers for loans made at the Perryridge branch with loan amounts greater that $1200.‖
select loan-number from loan where branch-name = ‘Perryridge‘ and amount > 1200

Rename Operation
The SQL allows renaming relations and attributes using the as clause:
Old-name as new-name

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 59

Example: Find the name, loan number and loan amount of all customers; rename the column name
loan_number as loan_id.
select customer_name ,borrower.loan_number as loan_id,a mount from borrower,loan where
borrower.loan_number = loan.loan_number

Tuple Variables
Tuple variables are defined in the from clause via the use of the as clause.
Example: Find the customer names and their loan numbers for all customers having a loan at some
branch.
select customer_name, T.loan_number, S.amount from borrower as T, loan as S
where T.loan_number = S.loan_number

String Operation
SQL includes a string-matching operator for comparisons on character strings.The operator ―like‖
uses patterns that are described using two special characters:
o percent (%). The % character matches any substring.
o underscore ( _ ). The _ character matches any character.
Example:
‘Perry%‘ matches any string beginning with ―Perry‖.
‘%idge%‘ matches any string containing ―idge‖ as a substring, for example, ‘Perryridge‘, ‘Rock
Ridge‘, ‘Mianus Bridge‘, and ‘Ridgeway‘.
‘- - - ‘ matches any string of exactly three characters.
‘ - - -%‘ matches any string of at least three characters.
Example: Select * from customer where customer_name like ‘j%‘;

Select * from customer where customer_Street like ‘_a%‘;

SQL supports a variety of string operations such as


 concatenation (using ―||‖)
 converting from upper to lower case (and vice versa)
 finding string length, extracting substrings, etc.

Ordering the Display of Tuples


List in alphabetic order the names of all customers having a loan in Perryridge branch

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 60

Example :select distinct customer_name from borrower, loan where borrower loan_number =
loan.loan_number and branch_name = 'Perryridge' order by customer_name
 We may specify desc for descending order or asc for ascending order, for each attribute; ascending
order is the default.
Example: order by customer_name desc

Set Operations
Set operators combine the results of two queries into a single one.
1. Union – returns all distinct rows selected by either query.
Example: Find all customers having a loan, an account or both at the bank
Query: select cust_name from depositor union select cust_name from borrower;

2. Union all - returns all rows selected by either query


Example: Find all customers having a loan and an account at the bank
Query: select cust_name from depositor union all select cust_name from borrower;

3. Intersect – returns only rows that are common to both the Queries
Example: Find all customers who have both a loan, and an account at the bank.
Query: select cust_name from depositor intersect select cust_name from borrower;

4. Minus – returns all distinct rows selected only by the first Query and not by the second.
Example: To find all customers who have an account but no loan at the bank.
Query: select cust_name from depositor minus select cust_name from borrower;

Aggregate Function
These functions operate on the multiset of values of a column of a relation, and return a value
(a) AVG - To find the average of values.
Example: Find the average of account balance from the account table
Query: select avg (balance) from account;
(b) SUM – To find the sum of values.
Example: Find the sum of account balance from the account table

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 61

Query: select sum (balance) from account;


(c) MAX – Returns the maximum value.
Example: Find the Maximum value of account balance from the account table.
Query: select max (balance) from account;
(d) MIN - Returns the minimum value.
Example: Find the Minimum value of account balance from the account table.
Query: select min (balance) from account;
(e) COUNT – Returns the number of rows in the column or table.
Example 1: Find the number rows in the customer table.
Query: select count (*) from customer;
Example 2: Find the number of rows in the balance column of account table.
Query: select count (balance) from account;
(f) GROUP BY
Aggregate Functions – Group By
Example 1: Find the average account balance at each branch.

Query:select branch_name, avg (balance) from account group by branch_name;

(g) HAVING CLAUSE

Aggregate Functions – Having Clause

Example 2: Find the average account balance at brighton branch.

Query: select branch_name, avg (balance) from account group by branch_name having
branch_name=‘brighton‘;

Null Values
 It is possible for tuples to have a null value, denoted by null, for some of their attributes
 Null signifies an unknown value or that a value does not exist.
 The predicate is null can be used to check for null values.
Example: Find all loan number which appears in the loan relation with null values for
amount.
select loan_number from loan where amount is null

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 62

and: The result of true and unknown is unknown, false and unknown is false, while unknown and unknown
is unknown.
or: The result of true or unknown is true, false or unknown is unknown, while unknown or unknown is
unknown.
not: The result of not unknown is unknown.

Nested Subqueries
 SQL provides a mechanism for the nesting of subqueries.
 A subquery is a select-from-where expression that is nested within another query.
 A common use of subqueries is to perform tests for set membership, set comparisons, and set
cardinality.
Example 1: Find all the information of customer who has an account number is A-101.
Query: select * from customer where cust_name=(select cust_name
from depositor where acc_no='A-101');

Example 2:Find all customers who have a loan from the bank, find their names And loan numbers.
Query: select cust_name, loan_no from borrower where loan_no in
(select loan_no from loan);
1. Set memberships
INExample:
Select * from customer where customer_name in(‗Hays‘,Jones‘);
NOT
INExample: Select * from customer where customer_name not in(‗Hays‘,Jones‘);

2. Set comparisons
SQL uses various comparison operators such as <, <=,=,>,>=,<>,any, all,
some,>some,>any etc to compare sets.
Examples 1: Select * from borrower where loan_number<any(select loan_number
from loan 2 where branch_name=‘Perryridge‘);
Example 2: Select loan_no from loan from amount<=30000;

3. Test for Empty Relation


Exists is a test for non empty set.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 63

Example: Select title from book where exists(select * from order where book.book-
id=order.book_id);
Similar to exists we can use not exists also.
Example: Select title from book where not exists(select * from order where book.book-
id=order.book_id);

4. Test for absence of duplicate tuples


The Unique construct tests whether a subquery has any duplicate tuples in its result.
Example: select T.customer-name from depositor as T
where unique (select R.customer-name from account, depositor as R
where T.customer-name = R.customer-name and
R.account-number = account.account-number and
account.branch-name = ‘Perryridge‘)
Not Unique construct is used for test the existence of duplicate tuples in the same manner.
Complex Queries
Complex queries are often hard or impossible to write as a single SQL block.There are two ways of
composing multiple SQL blocks to express a complex query.
1. Derived relations
2. with clause.

1. Derived Relations
SQL allows a subquery expression to be used in the from clause. If we use such an
expression, then we must give the result relation a name, and we can rename the attributes. For renaming as
clause is used
For example: ―Find the average account balance of those branches where the average account balance is
greater than $1200.‖
Select branch-name, avg-balance from (select branch-name, avg (balance) from account
group by branch-name)as branch-avg (branch-name, avg-balance) where avg-balance > 1200
Here subquery result is named as branch-avg with attributes of branch-name and avg-balance.
2. with clause.
The with clause provides a way of defining a temporary view, whose definition is available
only to the query in which the with clause occurs.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 64

Consider the following query, which selects accounts with the maximum balance; if there are
many accounts with the same maximum balance, all of them are selected.
with max-balance (value) as
select max(balance)
from account
select account-number
from account, max-balance
where account.balance = max-balance.value

6. INTEGRITY
Integrity constraints ensures that changes made to the database by authorized users donot result in a
loss of data consistency.
It is a mechanism used to prevent invalid data entry into the table.
Prevents accidental damages of database.
Types
1. Domain integrity Constraints
2. Entity integrity Constraints
3. Referential integrity Constraints
1. Domain integrity Constraints
A Domain is a set of values that may be assigned to an attribute. All values that appear in a column
of a relation (table) must be taken from the same domain.
Types
 Not Null Constraints
 Check Constraints

a) NOT NULL – It will not allow null values.


Syntax : create table <table name>(columnname data type (size) constraint constraint_name not
null);
Example : account_no char(10) notnull;
b) CHECK - Use the CHECK constraint when you need to enforce integrity rules that can be evaluated
based on a condition (logical expression).
Syntax : create table <table name>(columnname data type (size) constraint constraint_name check
(check_condition));

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 65

Example: create table student (name char(15) not null,student-id char(10), degree_level char(15),
primary key(student_id), check(degree_level in(‗bachelors‘,‘master‘,‘doctorate‘)));
The create domain clause can be used to de.ne new domains. For example, the statements:
create domain Dollars numeric(12,2)
create domain Pounds numeric(12,2)
2. Entity integrity Constraints
The entity integrity constraints state that no primary key value can be null. This is because the
primary key value is used to identify individual tuples in a relation.
Types
Unique Constraint
Primary key Constraint
a) UNIQUE – Avoid duplicate values
unique(Aj1,Aj2,……,Ajm)

The unique specification saya that attributes Aj1,Aj2,……,Ajm form a candidate key. These attributes
should have distinct values.
Syntax :create table <table name>(columnname data type (size) constraint
constraint_name unique);
b) Composite UNIQUE – Multicolumn unique key is called composite unique key
Syntax : create table <table name>(columnname1 data type (size), columnname2 data type
(size), constraint constraint_name unique (columnname1, columnname2));
c) PRIMARY KEY – It will not allow null values and avoid duplicate values.
Syntax : create table <table name>(columnname data type (size) constraint constraint_name
primary key);
d) Composite PRIMARY KEY – Multicolumn primary key is called composite primary key
Syntax : create table <table name>(columnname1 data type (size), columnname2 data type
(size), constraint constraint_name primary key (columnname1, columnname2));

3. REFERENTIAL INTEGRITY
Ensures that a value appears in one relation for a given set of attributes also appears for a certain set
of attributes in another relation. This condition is called referential integrity
Reference key (foreign key) – Its represent relationships between tables. Foreign key is a column whose
values are derived from the primary key of the same or some other table.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 66

Syntax: create table <table name>(columnname data type (size) constraint constraint_name
references parent_table_name);
Formal Definition
 Let r 1(R1) and r 2(R2) be relations with primary keys K1 and K2 respectively.
 The subset of R2 is a foreign key referencing K1 in relation r 1, if for every t2 in r 2 there
must be a tuple t1 in r 1 such that t1[K1] = t2[ ].
 Referential integrity constraint also called subset dependency since its can be written as
(r 2) K1 (r 1)
Assertions
 An assertion is a predicate expressing a condition that we wish the database always to satisfy.
 An assertion in SQL takes the form
Create assertion <assertion-name> check <predicate>
 When an assertion is made, the system tests it for validity, and tests it again on every update that
may violate the assertion
 Asserting for all X,P(X) is achieved in a round-robin fashion using not exists X such that not
P(X).
Assertion Example
 The sum of all loan amounts for each branch must be less than the sum of all account balances at
the branch.
create assertion sum-constraint check (not exists (select * from branch where (select
sum(amount) from loan where loan.branch-name = branch.branch-name) > = (select
sum(balance) from account where account.branch-name = branch.branch-name)))

7.TRIGGERS
 A trigger is a statement that is executed automatically by the system as a side effect of a
modification to the database.
 To design a trigger mechanism, we must:
 Specify the conditions under which the trigger is to be executed.
 Specify the actions to be taken when the trigger executes.
Trigger Example
 Suppose that instead of allowing negative account balances, the bank deals with overdrafts by
 setting the account balance to zero

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 67

 creating a loan in the amount of the overdraft


 giving this loan a loan number identical to the account number of the overdrawn account
 The condition for executing the trigger is an update to the account relation that results in a negative
balance value.
Syntax:
Create or replace trigger<trigger-name>{before/after}{insert/delete/update}on <table-
name>[for each statement/for each row][when <condition>];
Parts of trigger:
a. Trigger statement (The DML statement like insert/delete/update. It fires the trigger body)
b. Trigger body
c. Trigger restriction (optional)
Types of triggers:
a. Before
b. After
c. For each row
d. For each statement (default)
a. Before/after:
It specifies when the trigger boby should be fired.
In case of before, the trigger will be executed before executing the triggering statement.
In case of after, it will be executed after the triggering statement.
b. For each row/statement:
It decides if the trigger body to be fired once for each row affected by the triggering statement or
only once for the statementb executed.
By default, the trigger fires for each statement.
Disabling Triggers:
Syntax :Alter trigger <trigger_name> disable;
Example : Alter trigger sales_trigger disable;
Specific triggers on a table can be disabled as follows
Alter table purchase_details disable purchase;
All triggers on a table can be disabled on a table as follows.
Syntax :Alter table <table_name> disable all triggers;
Example :Alter table sales_details disables all triggers;
Enabling trigger:

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 68

Syntax :Alter table <table_name> enable trigger_name;


Example :Alter table purchase_details enable purchase;
To Enable all triggers
Syntax :Alter table <table_name> enable all triggers;
Dropping triggers:
Syntax :Drop trigger <trigger_name>;
Example :Drop trigger purchase;
Trigger Example:
create trigger overdraft-trigger after update on account
referencing new row as nrow for each row when nrow.balance < 0
Triggering Events and Actions in SQL
 Triggering event can be insert, delete or update
 Triggers on update can be restricted to specific attributes
 E.g. create trigger overdraft-trigger after update of balance on account
 Values of attributes before and after an update can be referenced
referencing old row as : for deletes and updates
referencing new row as : for inserts and updates
 Triggers can be activated before an event, which can serve as extra constraints. E.g. convert blanks
to null.
Statement Level Triggers
 Instead of executing a separate action for each affected row, a single action can be executed for all
rows affected by a transaction
o Use for each statement instead of for each row
o Use referencing old table or referencing new table to refer to temporary tables (called
transition tables) containing the affected rows
o Can be more efficient when dealing with SQL statements that update a large number of rows
When Not To Use Triggers
 Triggers were used earlier for tasks such as
 maintaining summary data (e.g. total salary of each department)
 Replicating databases by recording changes to special relations (called change or delta
relations) and having a separate process that applies the changes over to a replica
 There are better ways of doing these now:
 Databases today provide built in materialized view facilities to maintain summary data

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 69

 Databases provide built-in support for replication


 Encapsulation facilities can be used instead of triggers in many cases
 Define methods to update fields
 Carry out actions as part of the update methods instead of
through a trigger
8. SECURITY
Security of data is important concept in DBMS because it is essential to safeguard the data against
any unwanted users.
It is a protection from malicious attempts to steal or modify data.
There are five different levels of security
1. Database system level
Authentication and authorization mechanism to allow specific users access only to required data.
2. Operating
Protection from invalid logins
File-level access protection
Protection from improper use of ―superuser‖ authority.
Protection from improper use of privileged machine instructions.
3. Network level
Each site must ensure that it communicates with trusted sites.
Links must be protected from theft or modification of messages.
Mechanisms used
Identification protocol (password based)
Cryptography
4. Physical level
Protection of equipment from floods,power failure etc.
Protection of disks from theft,erasure,physical damage etc.
Protection of network and terminal cables from wire tapes,non-invasive electronic
eavesdropping,physical damage, etc.
Solution
Replication hardware-mirrored disks,dual busses etc.
Multiple access paths between every pair of devices.
Physical security by locks,police etc.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 70

Software techniques to detect physical security breaches


5. Human level
Protection from stolen passwords,sabotage,etc.
Solution
1. Frequent change of passwords.
2. Use of ―non-guessable‖ passwords.
3. Log all invalid access attempts.
4. Data audits.
5. Careful hiring practices.
Authorization
Forms of authorization on parts of the database:
 Read authorization - allows reading, but not modification of data.
 Insert authorization - allows insertion of new data, but not modification of existing data.
 Update authorization - allows modification, but not deletion of data.
 Delete authorization - allows deletion of data
Forms of authorization to modify the database schema:
 Index authorization - allows creation and deletion of indices.
 Resources authorization - allows creation of new relations.
 Alteration authorization - allows addition or deletion of attributes in a relation.
 Drop authorization - allows deletion of relations.
 The grant statement is used to give authorization
Syntax: grant <previlege list> on <relation name or view name> to <user/role list>
Example : grant select on account to john, mary; // this query grants database users john and
mary with select authorization.
grant update(account) on loan to john, mary;
 Revoke statement: It gets back the granted previlege
Syntax: revoke <previlege list> on <relation name or view name> from <user/role
list>[restrict|cascade]
Example : revoke select on branch from john, mary;
revoke update(account) on loan from john, mary;
 Revocation of a privilege from a user may cause other users also to lose that privilege; referred to as
cascading of the revoke.
 We can prevent cascading by specifying restrict:

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 71

 revoke select on
branch from U 1, U 2, U 3 restrict
 With restrict, the revoke command fails if cascading revokes are required.
Roles
 Roles permit common privileges for a class of users can be specified just once by creating a
corresponding ―role‖
 Privileges can be granted to or revoked from roles, just like user
 Roles can be assigned to users, and even to other roles
o create role teller
create role manager
o grant select on
branch to teller
grant update (balance) on account to teller
grant all privileges on account to manager
grant teller to manager
grant teller to alice, bob
grant manager to avi
Authorization and Views
 Users can be given authorization on views, without being given any authorization on the relations
used in the view definition
 Ability of views to hide data serves both to simplify usage of the system and to enhance security by
allowing users access only to data they need for their job
 A combination or relational-level security and view-level security can be used to limit a user‘s
access to precisely the data that user needs.
Granting of Privileges
 The passage of authorization from one user to another may be represented by an authorization grant
graph.
 The nodes of this graph are the users.
 The root of the graph is the database administrator.
 Consider graph for update authorization on loan.
 An edge U i U j indicates that user U i has granted update authorization on loan to U j.
Authorization Grant Graph

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 72

Authorization Grant Graph


 Requirement: All edges in an authorization graph must be part of some path originating with the
database administrator
 If DBA revokes grant from U 1:
o Grant must be revoked from U 4 since U 1 no longer has authorization
o Grant must not be revoked from U 5 since U 5 has another authorization path from DBA
through U 2
 Must prevent cycles of grants with no path from the root:
o DBA grants authorization to U 2
o U 7 grants authorization to U 3
o U 8 grants authorization to U 2
o DBA revokes authorization from U 2

 If the database administrator revokes authorization from U 2, U 2 retains authorization through U 3,

 If authorization is revoked subsequently from U 3, U 3 appears to retain authorization through U 2.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 73

 When the database administrator revokes authorization from U 3, the edges fromU 3 to U 2 and from
U 2 to U 3 are no longer part of a path starting with the database administrator.
 The edges between U 2 and U 3 are deleted, and the resulting authorization graph is

Audits Trials
 An audit trail is a log of all changes (inserts/deletes/updates) to the database along with information
such as which user performed the change, and when the change was performed.
 Used to track erroneous/fraudulent updates.
 Can be implemented using triggers, but many database systems provide direct support.
Limitations of SQL Authorization
 SQL does not support authorization at a tuple level
o E.g. we cannot restrict students to see only (the tuples storing) their own grades
 With the growth in Web access to databases, database accesses come primarily from application
servers.
o End users don't have database user ids, they are all mapped to the same database user id
 All end-users of an application (such as a web application) may be mapped to a single database
user
 The task of authorization in above cases falls on the application program, with no support from
SQL
o Benefit: fine grained authorizations, such as to individual tuples, can be implemented by the
application.
o Drawback: Authorization must be done in application code, and may be dispersed all over
an application
o Checking for absence of authorization loopholes becomes very difficult since it requires
reading large amounts of application code
Encryption

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 74

Data Encryption Standard (DES) substitutes characters and rearranges their order on the basis of an
encryption key which is provided to authorized users via a secure mechanism. Scheme is no more secure
than the key transmission mechanism since the key has to be shared.
 Advanced Encryption Standard (AES) is a new standard replacing DES, and is based on the
Rijndael algorithm, but is also dependent on shared secret keys
 Public-key encryption is based on each user having two keys:
o public key – publicly published key used to encrypt data, but cannot be used to decrypt data
o private key -- key known only to individual user, and used to decrypt data.
Need not be transmitted to the site doing encryption.
 Encryption scheme is such that it is impossible or extremely hard to decrypt data given only the
public key.
 The RSA public-key encryption scheme is based on the hardness of factoring a very large number
(100's of digits) into its prime components.
Authentication (Challenge response system)
 Password based authentication is widely used, but is susceptible to sniffing on a network
 Challenge-response systems avoid transmission of passwords
o DB sends a (randomly generated) challenge string to user
o User encrypts string and returns result.
o DB verifies identity by decrypting result
o Can use public-key encryption system by DB sending a message encrypted using user‘s
public key, and user decrypting and sending the message back
 Digital signatures are used to verify authenticity of data
o Private key is used to sign data and the signed data is made public.
o Any one can read the data with public key but cannot generate data without private key..
o Digital signatures also help ensure nonrepudiation: sender
cannot later claim to have not created the data
Digital Certificates
 Digital certificates are used to verify authenticity of public keys.
 Problem: when you communicate with a web site, how do you know if you are talking with the
genuine web site or an imposter?
o Solution: use the public key of the web site
o Problem: how to verify if the public key itself is genuine?
 Solution:

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 75

o Every client (e.g. browser) has public keys of a few root-level certification authorities
o A site can get its name/URL and public key signed by a certification authority: signed
document is called a certificate
o Client can use public key of certification authority to verify certificate
o Multiple levels of certification authorities can exist. Each certification authority
 presents its own public-key certificate signed by a higher level authority, and
 Uses its private key to sign the certificate of other web sites/authorities

9. EMBEDDED SQL
 Embedded SQL are SQL statements included in the programming language
 The SQL standard defines embeddings of SQL in a variety of programming languages such as C,
Java, and Cobol.
 A language to which SQL queries are embedded is referred to as a host language, and the SQL
structures permitted in the host language comprise embedded SQL.
 The embedded SQL program should be preprocessed prior to compilation.
 The preprocessor replaces embedded SQLrequests with host language declarations and procedure
calls.
 The resulting program is compiled by host language compiler.
 EXEC SQL statement is used to identify embedded SQL request to the preprocessor
o EXEC SQL <embedded SQL statement > END_EXEC
Note: this varies by language (for example, the Java embedding uses # SQL { …. }; , C language uses
semicolon instead of END_EXEC)
Example Query
 From within a host language, find the names and cities of customers with more than the variable
amount dollars in some account.
 Specify the query in SQL and declare a cursor for it
EXEC SQL
declare c cursor for
select depositor.customer_name, customer_city
from depositor, customer, account
where depositor.customer_name = customer.customer_name
and depositor account_number = account.account_number
and account.balance > :amount

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 76

END_EXEC
 The open statement causes the query to be evaluated
EXEC SQL open c END_EXEC
 The fetch statement causes the values of one tuple in the query result to be placed on host
language variables.
EXEC SQL fetch c into :cn, :cc END_EXEC
Repeated calls to fetch get successive tuples in the query result
 A variable called SQLSTATE in the SQL communication area (SQLCA) gets set to ‗02000‘ to
indicate no more data is available
 The close statement causes the database system to delete the temporary relation that holds the result
of the query.
EXEC SQL close c END_EXEC
Note: above details vary with language. For example, the Java embedding defines Java iterators to step
through result tuples.
Updates Through Cursors
 Can update tuples fetched by cursor by declaring that the cursor is for update
o declare c cursor for select * from account
where branch_name = ‗Perryridge‘
for update
 To update tuple at the current location of cursor c
update account set balance = balance + 100 where current of c

10. DYNAMIC SQL


 The Dynamic SQL allows programs to construct and submit SQL queries at run time.
 Dynamic SQL can be executed immediately or can be used later.
 Two principle Dynamic SQL statements are
1. PREPARE
2. EXECUTE
SQLSOURCE = ‘Delete from account where amount<10000;
EXEC SQL PREPARE SQLPREPPED FROM:SQLSOURCE;
EXEC SQL EXECUTE SQLPREPPED;
 SQLSOURCE specifies the programming language variable.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 77

 SQLPREPPED identifies the SQL variables. It holds the compiled version of SQL statement whose
source form is given in SQLSOURCE.
 The prepare statement takes the source statement and prepares it to produce an executable version,
which is stored in SQLPREPPED.
 EXECUTE statement executes the SQLPREPPED version.
 EXECUTE IMMEDIATE statement combines the functions of PREPARE and EXECUTE in a
single operation.
Call Level Interface
 The SQL Call Level Interface (SQL/CLI) is based on Microsoft‘s Opensoure DataBase Connectivity
(ODBC).
 They allow the applications to be written from which the exact SQL code is not known until run
time.
 Two principle reason for using SQL/CLI
Dynamic SQL is a source code statement. Dynamic SQL requires some kind of SQL
compiler to process the operations like PREPARE, EXECUTE. SQL/CLI does not requir any
special compiler instead it uses the host language compiler. It is in object code form.
SQL/CLI is DBMS independent i.e, it allows creation of several applications with different
DBMS.
 Example for SQL/CLI
strcpy (sqlsource, ― Delete from account where amount>10000);
rc = SQLExecDirect(hstmt,(SQLCHAR*)sqlsource,SQL.NTS);
 Strcpy is used to copy the source form of delete statement into sqlsource variable.
 SQLExecDirect executes the SQL Statement contained in sqlsource anf assigns the return code to
the variable rc.
Two standards connects an SQL database and performs queries and updates.
 Opensoure DataBase Connectivity (ODBC) was initially developed for C language and extended to
other languages like C++, C# amd Visual Basic.
 Java DataBase Connectivity (JDBC) is an application program interface foe java language.
 The users and applications connects to an SQL server establishing a session, executes a series of
atatements and finally disconnects the session.
 In addition to normal SQL commands, a session can also contains commands to commit the work
carried out or rollback the work carried out in a session.

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 78

11.VIEWS
A View is an object that gives the user a logical view of data from an underlying tables or tables.
It is not desirable for all users to see the entire logical model.
Security consideration may require that certain data be hidden from users.
Any relation that is not part of the logical model, but is made visible to a user as a virtual relation,
is called as view

Views may be created for the following reasons:


1. To provide data security
2. Query simplicity
3. Structure simplicity

Creating of Views

VIEW:-is an imaginary table.


Syntax: Create view <view name>(column alias name) as query with condition.
Query: create view custall as (Select cust_name, city from customer);

Assigning Names to Columns


Example: create view custall (customername, city) as (Select cust_name, city from customer);

Selecting data from view: Display the view


Example:select * from custall;

Updation of a View

Views can be used for data manipulation i.e, the user can perform insert, Update,a nd the delete
operations on the view.
The views on which data manipulation can be done are called updatable Views, the views that do
not allow data manipulation are called Readonly Views.

Destroying a view

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 79

A view can be dropped by using the drop view command.

Syntax: drop view view_name;

Example: drop view custall;

12.INTRODUCTION TO DISTRIBUTED DATABASES AND


CLIENT/SERVER DATABASES

2 Mark Questions

1. Define- relational algebra.


2. What is a SELECT operation?
3. What is a PROJECT operation?
4. Write short notes on tuple relational calculus
5. Write short notes on domain relational calculus
6. Define query language?
7. What are the two different categories of query languages?
8. Write short notes on Schema diagram.
9. Which condition is called referential integrity? Explain its basic concepts.
10. What are the parts of SQL language?

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 80

12. What are the categories of SQL command?


13. What are the three classes of SQL expression?0r Explain the basic structure of an SQL expression.
14. Give the general form of SQL query?
15. What is the use of rename operation?
16. Define tuple variable?
17. List the string operations supported by SQL?
18. List the set operations of SQL?
19. What is the use of Union and intersection operation?
20. What are aggregate functions? And list the aggregate functions supported by SQL?
21. What is the use of group by clause?
22. What is the use of sub queries?
23. What is view in SQL? How is it defined?
24. What is the use of with clause in SQL?
25. List the table modification commands in SQL?
26. List out the statements associated with a database transaction?
27. What is transaction?
28. List the SQL domain Types?
29. What is the use of integrity constraints?
30. Mention the 2 forms of integrity constraints in ER model?
31. What is trigger?
32. What are domain constraints?
33. What are referential integrity constraints?
34. What is assertion? Mention the forms available.
35. Give the syntax of assertion?
36. What is the need for triggers?
37. List the requirements needed to design a trigger.
38. Give the forms of triggers?
39. What does database security refer to?
40. List some security violations (or) name any forms of malicious access.
41. List the types of authorization.
42. What is authorization graph?
43. List out various user authorization to modify the database schema.
44. What are audit trails?

http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 81

45. Mention the various levels in security measures.


46. Name the various privileges in SQL?
47. Mention the various user privileges.
48. Give the limitations of SQL authorization.
49. Give some encryption techniques?
50. What does authentication refer?
51. List some authentication techniques.
52. What is embedded SQL? What are its advantages?

16 Mark Questions

1. Discuss about various operations in Relational algebra (Fundamental operations – Additional operation)
2. Discuss in detail about an Integrity, Triggers and Security.
3. Explain Embedded and Dynamic SQL.
4. Explain String Operations and Aggregate functions used in SQL.
5. Explain detail in domain relational calculus.
6. Explain detail in Tuple relational calculus.
7. Explain detail in distributed databases and client/server databases.

UNIT III

http://engineerportal.blogspot.in/

You might also like