16 Mark Questions: Structure of Relational Databases
16 Mark Questions: Structure of Relational Databases
16 Mark Questions
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
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
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
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 37
Output relation is
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 38
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.
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.
The project operation selects certain columns from a table while discarding others. It removes any
duplicate tuples from the result relation.
Syntax
Π<attributelist> ( R )
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))
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
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 41
Example 1: Renames both the relation and its attributes, the second renames the relation only and the third
renames as follows.
*ρTemp (Book)
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 42
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
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_name Salary
Hari 2000
Om 5000
Smith 7000
Jay 10000
Division Operation is suited to queries that include the phrase ‗for all‘.
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 45
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.
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
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
G avg (salary)(pt-works)
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 48
Result:
Salary
2062.5
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,
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
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:
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
2. s[x] u[y], where s and u are tuple variables, x is an attribute on which s is defined, y is
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 52
3. Fin
d the names of all customers having a loan, an account, or both at the bank
4. Find the names of all customers who have a loan and an account at the bank
5. Find the names of all customers having a loan at the Perryridge branch
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 53
Safety of Expressions
1. Find the loan_number, branch_name, and amount for loans of over $1200
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 54
2. Find the names of all customers who have a loan of over $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
Syntax: create table <table name> (columnname1 data type (size), Columnname 2 data
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));
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 57
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';
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 58
Where P
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%‘;
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;
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 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
INExample:
Select * from customer where customer_name in(‗Hays‘,Jones‘);
NOT
INExample: 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;
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);
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
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
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 68
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 69
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 70
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
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
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
Creating of Views
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
2 Mark Questions
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 80
http://engineerportal.blogspot.in/
CS1254 – DATABASE MANAGEMENT SYSTEMS 81
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/