SlideShare a Scribd company logo
1 of 51
Download to read offline
Database System Concepts, 6th Ed.
©Silberschatz, Korth and Sudarshan
See www.db-book.com for conditions on re-use
Intermediate SQL
©Silberschatz, Korth and Sudarshan
4.2
Database System Concepts - 6th Edition
Integrity Constraints
 Integrity constraints guard against accidental damage to
the database, by ensuring that authorized changes to the
database do not result in a loss of data consistency.
 An integrity constraint can be an arbitrary condition
pertaining to the database.
 Examples of integrity constraints are:
 An account must have a balance greater than $10,000.00
 A salary of a bank employee must be at least $4.00 an
hour.
 A customer must have a (non-null) phone number.
©Silberschatz, Korth and Sudarshan
4.3
Database System Concepts - 6th Edition
Integrity Constraints on a Single Relation
The allowed integrity constraints include
 not null
 primary key
 unique
 check (P), where P is a predicate
 Integrity constraints are usually declared as part of the
create table command used to create relations.
 Can also be added to an existing relation by using the
command alter table table-name add constraint
The system first ensures that the relation satisfies the
specified constraint. If it does, the constraint is added to
the relation; if not, the command is rejected.
©Silberschatz, Korth and Sudarshan
4.4
Database System Concepts - 6th Edition
Not Null Constraints
 null value is a member of all domains, and a legal value for
every attribute in SQL by default.
 For certain attributes, null values may be inappropriate.
 Consider a tuple in the student relation where name is null.
Such a tuple gives student information for an unknown
student; thus, it does not contain useful information.
 The not null specification prohibits the insertion of a null value
for the attribute.
 Any database modification that would cause a null to be
inserted in an attribute declared to be not null generates an
error.
Example: Declare name to be not null
name varchar(20) not null
©Silberschatz, Korth and Sudarshan
4.5
Database System Concepts - 6th Edition
Unique Constraints
unique ( A1, A2, …, Am)
 The unique specification states that the attributes A1, A2,…Am
form a candidate key.
i.e. no two tuples in the relation can be equal on all the listed
attributes.
 A null value does not equal any other value.
 Candidate keys are permitted to be null unless they have
explicitly been declared to be not null (in contrast to primary
keys).
©Silberschatz, Korth and Sudarshan
4.6
Database System Concepts - 6th Edition
The check clause
 check (P), where P is a predicate (condition).
 When applied to a relation declaration, the clause check(P)
specifies a condition (P) that must be satisfied by every
tuple in a relation.
 A common use of the check clause is to ensure that
attribute values satisfy specified conditions.
 For instance, check ( budget > 0 ) in the create table
command would ensure that the value of budget column is
nonnegative.
©Silberschatz, Korth and Sudarshan
4.7
Database System Concepts - 6th Edition
The check clause
Ex: Ensure that semester is one of fall, winter, spring or summer.
create table section (
course_id varchar (8),
sec_id varchar (8),
semester varchar (6),
year numeric (4,0),
building varchar (15),
room_number varchar (7),
time slot id varchar (4),
check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’))
);
©Silberschatz, Korth and Sudarshan
4.8
Database System Concepts - 6th Edition
Primary key Constraint
 primary key (A1, ..., An )
The primary key specification says that attributes A1, ..., An
form the primary key for the relation.
Example:
create table instructor (
ID char(5) not null,
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
primary key (ID) );
 The primary key attributes must be not null and unique.
• No tuple can have a null value for a primary-key attribute.
• No two tuples in the relation can be equal on all the primary-
key attributes.
©Silberschatz, Korth and Sudarshan
4.9
Database System Concepts - 6th Edition
Referential Integrity Constraint
 Often, we wish to ensure that a value that 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.
 Foreign key is implementation of referential integrity
constraint.
 Let A be a set of attributes.
 Let R and S be two relations that contain attributes A and
where A is the primary key of S.
 A is said to be a foreign key of R if for any values of A
appearing in R these values also appear in S.
©Silberschatz, Korth and Sudarshan
4.10
Database System Concepts - 6th Edition
 foreign key (Am, ..., An ) references r
Example:
create table instructor (
ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
foreign key (dept_name) references department);
 This foreign-key declaration specifies that for each instructor
tuple, the department name specified in the tuple must exist
in the department relation.
 Without this constraint, it is possible for an instructor to specify
a nonexistent department name.
Referential Integrity Constraint
©Silberschatz, Korth and Sudarshan
4.11
Database System Concepts - 6th Edition
Short forms of primary key and foreign key
 create table course (
course_id char(5) primary key,
title varchar(20),
dept_name varchar(20) references department
);
©Silberschatz, Korth and Sudarshan
4.12
Database System Concepts - 6th Edition
Cascading Actions in Referential Integrity
 A foreign key clause can specify that if a delete or update action
on the referenced relation violates the constraint, then instead
of rejecting the action, the system must take steps to change the
tuple in the referencing relation to restore the constraint.
 create table instructor (
…
dept_name varchar(20),
foreign key (dept_name) references department
on delete cascade
on update cascade )
 A delete of a tuple in department results in this referential-
integrity constraint being violated, the system does not reject the
delete.
 Instead, the delete “cascades” to the instructor relation, deleting
the tuple that refers to the department that was deleted.
©Silberschatz, Korth and Sudarshan
4.13
Database System Concepts - 6th Edition
Default Values
 SQL allows a default value to be specified for an attribute.
create table student
( ID varchar (5),
name varchar (20) not null,
dept_name varchar (20),
tot_cred numeric (3,0) default 0,
primary key (ID) );
 When a tuple is inserted into the student relation, if no value
is provided for the tot_cred attribute, its value is set to 0.
insert into student (ID, name, dept name)
values (’12789’, ’Newman’, ’Comp. Sci.’);
©Silberschatz, Korth and Sudarshan
4.14
Database System Concepts - 6th Edition
Joined Relations
 Join operations take two relations and return as a result
another relation.
 A join operation is a Cartesian product which requires that
tuples in the two relations match (under some condition).
It also specifies the attributes that are present in the result of
the join.
 The join operations are typically used as subquery
expressions in the from clause.
select * from student join takes on student.ID= takes.ID;
 The on condition above specifies that a tuple from student
matches a tuple from takes if their ID values are equal.
 ID attribute will be listed twice in the result. (Natural join ? )
©Silberschatz, Korth and Sudarshan
4.15
Database System Concepts - 6th Edition
Join operations – Example
 Relation course
 Relation prereq
 Observe that
prereq information is missing for CS-315 and
course information is missing for CS-437
 course prereq
©Silberschatz, Korth and Sudarshan
4.16
Database System Concepts - 6th Edition
Outer Join
 An extension of the join operation that avoids loss of
information.
 Computes the join and then adds tuples form one relation
that does not match tuples in the other relation to the
result of the join.
 Uses null values for not matching tuples.
 There are three forms of outer join
 left outer join
 right outer join
 full outer join
The join operations that do not preserve unmatched tuples
are called inner join operations.
©Silberschatz, Korth and Sudarshan
4.17
Database System Concepts - 6th Edition
Left Outer Join
 The left outer join preserves tuples only in the relation
named before (to the left of) the left outer join operation.
Left outer-join operation
 First, compute the result of the inner join.
Then, for every tuple t in the left-hand-side relation that
does not match any tuple in the right-hand-side relation,
add a tuple r to the result of the join constructed as follows:
 The attributes of tuple r that are derived from the left-
hand-side relation are filled in with the values from
tuple t.
 The remaining attributes of r are filled with null values.
©Silberschatz, Korth and Sudarshan
4.18
Database System Concepts - 6th Edition
Left Outer Join
 course natural left outer join prereq
©Silberschatz, Korth and Sudarshan
4.19
Database System Concepts - 6th Edition
Right Outer Join
 The right outer join is symmetric to the left outer join.
 Tuples from the right hand-side relation that do not match
any tuple in the left-hand-side relation are padded with nulls
and are added to the result of the right outer join.
course natural right outer join prereq
©Silberschatz, Korth and Sudarshan
4.20
Database System Concepts - 6th Edition
Full Outer Join
 The full outer join is a combination of the left and right
outer-join types.
 After the operation computes the result of the inner join, it
extends with nulls those tuples from the left-hand-side relation
that did not match with any from the right-hand side relation,
and adds them to the result.
 Similarly, it extends with nulls those tuples from the right-
hand-side relation that did not match with any tuples from the
left-hand-side relation and adds them to the result.
Course natural full outer join prereq (MySQL doest not support)
©Silberschatz, Korth and Sudarshan
4.21
Database System Concepts - 6th Edition
Joined Relations
 Join operations take two relations and return as a result
another relation.
 These additional operations are typically used as subquery
expressions in the from clause
 Join condition – defines which tuples in the two relations
match, and what attributes are present in the result of the join.
 Join type – defines how tuples in each relation that do not
match any tuple in the other relation (based on the join
condition) are treated.
©Silberschatz, Korth and Sudarshan
4.22
Database System Concepts - 6th Edition
Joined Relations – Examples
 course inner join prereq on
course.course_id = prereq.course_id
 course left outer join prereq on / ( using (cousrse_id) )
course.course_id = prereq.course_id
©Silberschatz, Korth and Sudarshan
4.23
Database System Concepts - 6th Edition
Joined Relations – Examples
 course natural right outer join prereq
 course natural full outer join prereq
©Silberschatz, Korth and Sudarshan
4.24
Database System Concepts - 6th Edition
Built-in Data Types in SQL
 date: Dates, containing a (4 digit) year, month and date
 Example: date ‘2005-7-27’
 time: Time of day, in hours, minutes and seconds.
 Example: time ‘09:00:30’ time ‘09:00:30.75’
 timestamp: date plus time of day
 Example: timestamp ‘2005-7-27 09:00:30.75’
 interval: period of time
 Example: interval ‘1’ day
 Subtracting a date/time/timestamp value from another
gives an interval value
 Interval values can be added to date/time/timestamp
values
©Silberschatz, Korth and Sudarshan
4.25
Database System Concepts - 6th Edition
Large-Object Types
 Large objects (photos, videos, CAD files, etc.) are stored as
a large object:
 blob: binary large object -- object is a large collection of
binary data (whose interpretation is left to an application
outside of the database system).
 clob: character large object -- object is a large collection
of character data.
 When a query returns a large object, a pointer is
returned rather than the large object itself.
©Silberschatz, Korth and Sudarshan
4.26
Database System Concepts - 6th Edition
User-Defined Types
 create type construct in SQL-99 creates user-defined type
create type Dollars as numeric (12,2)
 The user-defined type Dollars to be decimal numbers with a
total of 12 digits, with two decimal point.
 The newly created types can then be used, as types of
attributes of relations.
 create table department
( dept_name varchar (20),
building varchar (15),
budget Dollars );
©Silberschatz, Korth and Sudarshan
4.27
Database System Concepts - 6th Edition
Domains
 create domain construct in SQL-92 creates user-defined
domain types
create domain person_name as char(20) not null
 Types and domains are similar. Domains can have
constraints or default values specified on them.
 create domain degree_level varchar(10)
constraint degree_level_test
check (value in (’Bachelors’, ’Masters’, ’Doctorate’));
©Silberschatz, Korth and Sudarshan
4.28
Database System Concepts - 6th Edition
Views
 In some cases, it is not desirable for all users to see the
entire logical model (that is, all the actual relations stored in
the database.)
 Consider a person who needs to know an instructors name
and department, but not the salary. This person should see
a relation described, in SQL, by
select ID, name, dept_name
from instructor
 A view provides a mechanism to hide certain data from the
view of certain users.
 Any relation that is not of the conceptual model but is made
visible to a user as a “virtual relation” is called a view.
©Silberschatz, Korth and Sudarshan
4.29
Database System Concepts - 6th Edition
View Definition
 A view is defined using the create view statement which has the
form
create view v as < query expression >
where <query expression> is any legal SQL expression. The
view name is represented by v.
 View definition is not the same as creating a new relation by
evaluating the query expression
 Rather, a view definition causes the saving of an
expression; the expression is substituted into queries using
the view.
 i.e. whenever the view relation is accessed, its tuples are
created by computing the query result.
©Silberschatz, Korth and Sudarshan
4.30
Database System Concepts - 6th Edition
Example Views
 A view of instructors without their salary
create view faculty as
select ID, name, dept_name
from instructor
 Once a view is created, we can use the view to refer to the
virtual relation that the view generates. (select * from faculty)
 View names may appear in a query any place where a
relation name may appear.
 Find all instructors in the Biology department
select name
from faculty
where dept_name = ‘Biology’
©Silberschatz, Korth and Sudarshan
4.31
Database System Concepts - 6th Edition
Views
 The attribute names of a view can also be specified explicitly.
 Create a view of department salary total
create view departments_total_salary(dept_name, total_salary)
as
select dept_name, sum (salary)
from instructor
group by dept_name;
 The preceding view gives for each department the sum of the
salaries of all the instructors at that department.
 At any given time, the set of tuples in the view relation is the
result of evaluation of the query expression that defines the
view.
©Silberschatz, Korth and Sudarshan
4.32
Database System Concepts - 6th Edition
Views Defined Using Other Views
 One view may be used in the expression defining another
view.
 A view relation v1 is said to depend directly on a view
relation v2 if v2 is used in the expression defining v1.
 A view relation v1 is said to depend on view relation v2 if
either v1 depends directly to v2 or there is a path of
dependencies from v1 to v2
 A view relation v is said to be recursive if it depends on
itself.
©Silberschatz, Korth and Sudarshan
4.33
Database System Concepts - 6th Edition
Views Defined Using Other Views
 create view physics_fall_2009 as
select course.course_id, sec_id, building, room_number
from course, section
where course.course_id = section.course_id
and course.dept_name = ’Physics’
and section.semester = ’Fall’
and section.year = ’2009’;
 create view physics_fall_2009_watson as
select course_id, room_number
from physics_fall_2009
where building= ’Watson’;
©Silberschatz, Korth and Sudarshan
4.34
Database System Concepts - 6th Edition
Materialized Views
 Certain database systems allow view relations to be stored,
but they make sure that, if the actual relations used in the view
definition change, the view is kept up-to-date. Such views
are called materialized views.
 The process of keeping the materialized view up-to-date is
called view maintenance.
Advantages
 Applications that use a view frequently may benefit if the view is
materialized.
 Applications that demand fast response to certain queries that
compute aggregates over large relations can also benefit by
creating materialized views corresponding to the queries.
Disadvantage: Overhead of storage and update cost.
©Silberschatz, Korth and Sudarshan
4.35
Database System Concepts - 6th Edition
Update of a View
 Views present serious problems if we allow updates, insertions,
or deletions with them.
 The difficulty is that a modification to the database expressed in
terms of a view must be translated to a modification to the actual
relations
 Add a new tuple to faculty view which we defined earlier
insert into faculty values (’30765’, ’Green’, ’Music’);
 This insertion must be represented by an insertion into the actual
relation instructor.
 However, to insert a tuple into instructor, we must have some
value for salary.
This insertion must be null for the salary into the instructor relation.
(’30765’, ’Green’, ’Music’, null)
©Silberschatz, Korth and Sudarshan
4.36
Database System Concepts - 6th Edition
Some Updates cannot be Translated Uniquely
 create view instructor_info as
select ID, name, building
from instructor, department
where instructor.dept_name= department.dept_name;
 insert into instructor_info values (’69987’, ’White’, ’Taylor’);
which department, if multiple departments in Taylor?
what if no department is in Taylor?
 Most SQL implementations allow updates only on simple views
 The from clause has only one database relation.
 The select clause contains only attribute names of the relation,
and does not have any expressions, aggregates, or distinct
specification.
 Any attribute not listed in the select clause can be set to null
 The query does not have a group by or having clause.
©Silberschatz, Korth and Sudarshan
4.37
Database System Concepts - 6th Edition
Index Creation
 create table student
( ID varchar (5),
name varchar (20) not null,
dept_name varchar (20),
tot_cred numeric (3,0) default 0,
primary key (ID) );
 create index studentID_index on student(ID)
 Indices are data structures used to speed up access to
records with specified values for index attributes
 e.g. select *
from student
where ID = ‘12345’
can be executed by using the index to find the required
record, without looking at all records of student
©Silberschatz, Korth and Sudarshan
4.38
Database System Concepts - 6th Edition
Transactions
 A transaction consists of a sequence of query and/or update
statements. (Unit of work).
 Begin implicitly when an SQL statement is executed.
 One of the following SQL statements must end the transaction:
 Commit [work] commits the current transaction; that is, it
makes the updates performed by the transaction become
permanent in the database.
 Rollback [work] causes the current transaction to be rolled
back; that is, it undoes all the updates performed by the SQL
statements in the transaction.
 Once a transaction has executed commit work, its effects can no
longer be undone by rollback work.
©Silberschatz, Korth and Sudarshan
4.39
Database System Concepts - 6th Edition
Transactions
 Atomic transaction
 either fully executed or rolled back as if it never occurred
 Isolation from concurrent transactions
 But default on most databases: each SQL statement
commits automatically
 Can turn off auto commit for a session (e.g. using API)
(SET autocommit = 0;) (MySQL)
 In SQL:1999, can use: begin atomic …. end
Not supported on most databases
(START TRANSACTION ……… COMMIT/ROLLBACK)
©Silberschatz, Korth and Sudarshan
4.40
Database System Concepts - 6th Edition
Authorization
 Specifying access rights/privileges to resources is called
authorization.
 We may assign a user several forms of authorization on data of
the database:
 Read (Select) - allows reading, but not modification of data.
 Insert - allows insertion of new data, but not modification of
existing data.
 Update - allows modification, but not deletion of data.
 Delete - allows deletion of data.
 Each of these types of authorizations is called a privilege.
 DB Admin may authorize the user all, none, or a combination of
these privileges on a relation or a view.
©Silberschatz, Korth and Sudarshan
4.41
Database System Concepts - 6th Edition
Authorization
 When a user submits a query or an update, the SQL first checks if
the query or update is authorized, based on the authorizations that
the user has been granted.
 If the query or update is not authorized, it is rejected.
 Users may also be granted authorizations on the database
schema, allowing them to create, modify, or drop relations.
Forms of authorization to modify the database schema
 Index - allows creation and deletion of indices.
 Resources - allows creation of new relations.
 Alteration - allows addition or deletion of attributes in a relation.
 Drop - allows deletion of relations.
A user who has some form of authorization is allowed to pass on
(grant) this authorization to other users, or to withdraw (revoke)
an authorization that was granted earlier. (NOT by Default)
©Silberschatz, Korth and Sudarshan
4.42
Database System Concepts - 6th Edition
Authorization Specification in SQL
 The grant statement is used to confer authorization
grant <privilege list>
on <relation name or view name> to <user/role list>
 <user list> is:
 a user-id
 public, which allows all valid users the privilege is granted
 A role (more on this later)
 Granting a privilege on a view does not imply granting any
privileges on the underlying relations.
 The grantor of the privilege must already hold the privilege
on the specified item (or be the database administrator).
 grant and revoke are DDL (DCL) commands.
©Silberschatz, Korth and Sudarshan
4.43
Database System Concepts - 6th Edition
Privileges in SQL
 select: allows read access to relation, or the ability to query
using the view
 Example: grant users U1, U2, and U3 select authorization
on the instructor relation:
grant select on instructor to U1, U2, U3
 insert: the ability to insert data(tuples) in a relation.
 update: the ability to update (some/all attributes of a relation)
 delete: the ability to delete data(tuples) of a relation.
 all [ privileges ]: used as a short form for all the allowable
privileges.
 A user who creates a new relation is given all privileges on
that relation automatically.
©Silberschatz, Korth and Sudarshan
4.44
Database System Concepts - 6th Edition
Revoking Authorization in SQL
 The revoke statement is used to revoke authorization.
revoke <privilege list>
on <relation name or view name> from <user/role list>
Example: revoke select on branch from U1, U2, U3
 <privilege-list> may be all to revoke all privileges the revokee
may hold.
 If <revokee-list> includes public, all users lose the privileges.
 If the same privilege was granted twice to the same user by
different grantees, the user may retain the privilege after the
revocation.
 All privileges that depend on the privilege being revoked are
also revoked.
©Silberschatz, Korth and Sudarshan
4.45
Database System Concepts - 6th Edition
Roles
 A set of roles (users) is created in the database.
 Each database user is granted a set of roles.
 Any authorization that can be granted to a user can be
granted to a role.
 create role instructor;
 grant instructor to Amit;
 Privileges can be granted to roles:
 grant select on takes to instructor;
©Silberschatz, Korth and Sudarshan
4.46
Database System Concepts - 6th Edition
Roles
 Roles can be granted to users, as well as to other roles
 create role teaching_assistant
 grant teaching_assistant to instructor;
Instructor inherits all privileges of teaching_assistant
 There can be a chain of roles;
 create role dean;
 grant instructor to dean;
 grant dean to Satoshi;
Thus the privileges of a user or a role consist of:
 All privileges directly granted to the user/role.
 All privileges granted to roles that have been granted to the
user/role.
©Silberschatz, Korth and Sudarshan
4.47
Database System Concepts - 6th Edition
Authorization on Views
 A user who creates a view does not necessarily receive all
privileges on that view.
Example: A user who creates a view cannot be given update
authorization on a view without having update authorization on
the actual relations used to define the view.
 If a user creates a view on which no authorization can be granted,
the system will deny the view creation request.
create view geo_instructor as
(select *
from instructor
where dept_name = ’Geology’);
 The creator of the geo_instructor view must have select
authorization on the instructor relation.
©Silberschatz, Korth and Sudarshan
4.48
Database System Concepts - 6th Edition
Authorizations on Schema
 SQL includes a references privilege that permits a user to
declare foreign keys when creating relations.
 references privilege to create foreign key
grant reference (dept_name) on department to Mariano;
 This grant statement allows user Mariano to create
relations with an attribute that references the
dept_name of the department relation as a foreign key.
 Why is this required?
( Foreign key constraints restrict updates or deletes on
referenced relations )
©Silberschatz, Korth and Sudarshan
4.49
Database System Concepts - 6th Edition
Transfer of privileges
 A user who has been granted some form of authorization
may be allowed to pass on this authorization to other users.
 To grant a privilege and to allow the recipient to pass the
privilege on to other users, we append the with grant
option clause to the grant command.
grant select on department to Amit with grant option;
 The passing of a specific authorization from one user to
another can be represented by an authorization graph.
 The graph includes an edge Ui → Uj if user Ui grants
authorization to Uj.
 The root of the graph is the database administrator.
 A user has an authorization if and only if there is a path
from the root down to the node representing the user.
©Silberschatz, Korth and Sudarshan
4.50
Database System Concepts - 6th Edition
Authorization-grant graph
 U5 is granted authorization by both U1 and U2, where as
U4 is granted authorization by only U1.
©Silberschatz, Korth and Sudarshan
4.51
Database System Concepts - 6th Edition
Revoking of Privileges
 Revocation of a privilege from a user/role may cause other
users/roles also to lose that privilege. This behavior is called
cascading revocation.
 revoke select on department from Amit, Satoshi
cascade; (By default)
 The revoke statement may specify restrict in order to prevent
cascading revocation:
 revoke select on department from Amit, Satoshi restrict;
 The following revoke statement revokes only the grant option,
rather than the actual select privilege.
 revoke grant option for select on department from Amit;
(cascade of Amit grants)

More Related Content

Similar to Int_SQL.pdf (20)

Sql.pptx
Sql.pptxSql.pptx
Sql.pptx
 
Eer >r.model
Eer >r.modelEer >r.model
Eer >r.model
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
Ch 3.pdf
Ch 3.pdfCh 3.pdf
Ch 3.pdf
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
Integrity & security
Integrity & securityIntegrity & security
Integrity & security
 
Ch4
Ch4Ch4
Ch4
 
ch3[1].ppt
ch3[1].pptch3[1].ppt
ch3[1].ppt
 
4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdf4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdf
 
6 integrity and security
6 integrity and security6 integrity and security
6 integrity and security
 
Relational Model
Relational ModelRelational Model
Relational Model
 
Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013
 
03 Relational Databases.ppt
03 Relational Databases.ppt03 Relational Databases.ppt
03 Relational Databases.ppt
 
Query optimization
Query optimizationQuery optimization
Query optimization
 
Ch3 a
Ch3 aCh3 a
Ch3 a
 
Ch3
Ch3Ch3
Ch3
 
ch6.ppt
ch6.pptch6.ppt
ch6.ppt
 

Recently uploaded

(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...ranjana rawat
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 

Recently uploaded (20)

(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 

Int_SQL.pdf

  • 1. Database System Concepts, 6th Ed. ©Silberschatz, Korth and Sudarshan See www.db-book.com for conditions on re-use Intermediate SQL
  • 2. ©Silberschatz, Korth and Sudarshan 4.2 Database System Concepts - 6th Edition Integrity Constraints  Integrity constraints guard against accidental damage to the database, by ensuring that authorized changes to the database do not result in a loss of data consistency.  An integrity constraint can be an arbitrary condition pertaining to the database.  Examples of integrity constraints are:  An account must have a balance greater than $10,000.00  A salary of a bank employee must be at least $4.00 an hour.  A customer must have a (non-null) phone number.
  • 3. ©Silberschatz, Korth and Sudarshan 4.3 Database System Concepts - 6th Edition Integrity Constraints on a Single Relation The allowed integrity constraints include  not null  primary key  unique  check (P), where P is a predicate  Integrity constraints are usually declared as part of the create table command used to create relations.  Can also be added to an existing relation by using the command alter table table-name add constraint The system first ensures that the relation satisfies the specified constraint. If it does, the constraint is added to the relation; if not, the command is rejected.
  • 4. ©Silberschatz, Korth and Sudarshan 4.4 Database System Concepts - 6th Edition Not Null Constraints  null value is a member of all domains, and a legal value for every attribute in SQL by default.  For certain attributes, null values may be inappropriate.  Consider a tuple in the student relation where name is null. Such a tuple gives student information for an unknown student; thus, it does not contain useful information.  The not null specification prohibits the insertion of a null value for the attribute.  Any database modification that would cause a null to be inserted in an attribute declared to be not null generates an error. Example: Declare name to be not null name varchar(20) not null
  • 5. ©Silberschatz, Korth and Sudarshan 4.5 Database System Concepts - 6th Edition Unique Constraints unique ( A1, A2, …, Am)  The unique specification states that the attributes A1, A2,…Am form a candidate key. i.e. no two tuples in the relation can be equal on all the listed attributes.  A null value does not equal any other value.  Candidate keys are permitted to be null unless they have explicitly been declared to be not null (in contrast to primary keys).
  • 6. ©Silberschatz, Korth and Sudarshan 4.6 Database System Concepts - 6th Edition The check clause  check (P), where P is a predicate (condition).  When applied to a relation declaration, the clause check(P) specifies a condition (P) that must be satisfied by every tuple in a relation.  A common use of the check clause is to ensure that attribute values satisfy specified conditions.  For instance, check ( budget > 0 ) in the create table command would ensure that the value of budget column is nonnegative.
  • 7. ©Silberschatz, Korth and Sudarshan 4.7 Database System Concepts - 6th Edition The check clause Ex: Ensure that semester is one of fall, winter, spring or summer. create table section ( course_id varchar (8), sec_id varchar (8), semester varchar (6), year numeric (4,0), building varchar (15), room_number varchar (7), time slot id varchar (4), check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)) );
  • 8. ©Silberschatz, Korth and Sudarshan 4.8 Database System Concepts - 6th Edition Primary key Constraint  primary key (A1, ..., An ) The primary key specification says that attributes A1, ..., An form the primary key for the relation. Example: create table instructor ( ID char(5) not null, name varchar(20) not null, dept_name varchar(20), salary numeric(8,2), primary key (ID) );  The primary key attributes must be not null and unique. • No tuple can have a null value for a primary-key attribute. • No two tuples in the relation can be equal on all the primary- key attributes.
  • 9. ©Silberschatz, Korth and Sudarshan 4.9 Database System Concepts - 6th Edition Referential Integrity Constraint  Often, we wish to ensure that a value that 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.  Foreign key is implementation of referential integrity constraint.  Let A be a set of attributes.  Let R and S be two relations that contain attributes A and where A is the primary key of S.  A is said to be a foreign key of R if for any values of A appearing in R these values also appear in S.
  • 10. ©Silberschatz, Korth and Sudarshan 4.10 Database System Concepts - 6th Edition  foreign key (Am, ..., An ) references r Example: create table instructor ( ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2), foreign key (dept_name) references department);  This foreign-key declaration specifies that for each instructor tuple, the department name specified in the tuple must exist in the department relation.  Without this constraint, it is possible for an instructor to specify a nonexistent department name. Referential Integrity Constraint
  • 11. ©Silberschatz, Korth and Sudarshan 4.11 Database System Concepts - 6th Edition Short forms of primary key and foreign key  create table course ( course_id char(5) primary key, title varchar(20), dept_name varchar(20) references department );
  • 12. ©Silberschatz, Korth and Sudarshan 4.12 Database System Concepts - 6th Edition Cascading Actions in Referential Integrity  A foreign key clause can specify that if a delete or update action on the referenced relation violates the constraint, then instead of rejecting the action, the system must take steps to change the tuple in the referencing relation to restore the constraint.  create table instructor ( … dept_name varchar(20), foreign key (dept_name) references department on delete cascade on update cascade )  A delete of a tuple in department results in this referential- integrity constraint being violated, the system does not reject the delete.  Instead, the delete “cascades” to the instructor relation, deleting the tuple that refers to the department that was deleted.
  • 13. ©Silberschatz, Korth and Sudarshan 4.13 Database System Concepts - 6th Edition Default Values  SQL allows a default value to be specified for an attribute. create table student ( ID varchar (5), name varchar (20) not null, dept_name varchar (20), tot_cred numeric (3,0) default 0, primary key (ID) );  When a tuple is inserted into the student relation, if no value is provided for the tot_cred attribute, its value is set to 0. insert into student (ID, name, dept name) values (’12789’, ’Newman’, ’Comp. Sci.’);
  • 14. ©Silberschatz, Korth and Sudarshan 4.14 Database System Concepts - 6th Edition Joined Relations  Join operations take two relations and return as a result another relation.  A join operation is a Cartesian product which requires that tuples in the two relations match (under some condition). It also specifies the attributes that are present in the result of the join.  The join operations are typically used as subquery expressions in the from clause. select * from student join takes on student.ID= takes.ID;  The on condition above specifies that a tuple from student matches a tuple from takes if their ID values are equal.  ID attribute will be listed twice in the result. (Natural join ? )
  • 15. ©Silberschatz, Korth and Sudarshan 4.15 Database System Concepts - 6th Edition Join operations – Example  Relation course  Relation prereq  Observe that prereq information is missing for CS-315 and course information is missing for CS-437  course prereq
  • 16. ©Silberschatz, Korth and Sudarshan 4.16 Database System Concepts - 6th Edition Outer Join  An extension of the join operation that avoids loss of information.  Computes the join and then adds tuples form one relation that does not match tuples in the other relation to the result of the join.  Uses null values for not matching tuples.  There are three forms of outer join  left outer join  right outer join  full outer join The join operations that do not preserve unmatched tuples are called inner join operations.
  • 17. ©Silberschatz, Korth and Sudarshan 4.17 Database System Concepts - 6th Edition Left Outer Join  The left outer join preserves tuples only in the relation named before (to the left of) the left outer join operation. Left outer-join operation  First, compute the result of the inner join. Then, for every tuple t in the left-hand-side relation that does not match any tuple in the right-hand-side relation, add a tuple r to the result of the join constructed as follows:  The attributes of tuple r that are derived from the left- hand-side relation are filled in with the values from tuple t.  The remaining attributes of r are filled with null values.
  • 18. ©Silberschatz, Korth and Sudarshan 4.18 Database System Concepts - 6th Edition Left Outer Join  course natural left outer join prereq
  • 19. ©Silberschatz, Korth and Sudarshan 4.19 Database System Concepts - 6th Edition Right Outer Join  The right outer join is symmetric to the left outer join.  Tuples from the right hand-side relation that do not match any tuple in the left-hand-side relation are padded with nulls and are added to the result of the right outer join. course natural right outer join prereq
  • 20. ©Silberschatz, Korth and Sudarshan 4.20 Database System Concepts - 6th Edition Full Outer Join  The full outer join is a combination of the left and right outer-join types.  After the operation computes the result of the inner join, it extends with nulls those tuples from the left-hand-side relation that did not match with any from the right-hand side relation, and adds them to the result.  Similarly, it extends with nulls those tuples from the right- hand-side relation that did not match with any tuples from the left-hand-side relation and adds them to the result. Course natural full outer join prereq (MySQL doest not support)
  • 21. ©Silberschatz, Korth and Sudarshan 4.21 Database System Concepts - 6th Edition Joined Relations  Join operations take two relations and return as a result another relation.  These additional operations are typically used as subquery expressions in the from clause  Join condition – defines which tuples in the two relations match, and what attributes are present in the result of the join.  Join type – defines how tuples in each relation that do not match any tuple in the other relation (based on the join condition) are treated.
  • 22. ©Silberschatz, Korth and Sudarshan 4.22 Database System Concepts - 6th Edition Joined Relations – Examples  course inner join prereq on course.course_id = prereq.course_id  course left outer join prereq on / ( using (cousrse_id) ) course.course_id = prereq.course_id
  • 23. ©Silberschatz, Korth and Sudarshan 4.23 Database System Concepts - 6th Edition Joined Relations – Examples  course natural right outer join prereq  course natural full outer join prereq
  • 24. ©Silberschatz, Korth and Sudarshan 4.24 Database System Concepts - 6th Edition Built-in Data Types in SQL  date: Dates, containing a (4 digit) year, month and date  Example: date ‘2005-7-27’  time: Time of day, in hours, minutes and seconds.  Example: time ‘09:00:30’ time ‘09:00:30.75’  timestamp: date plus time of day  Example: timestamp ‘2005-7-27 09:00:30.75’  interval: period of time  Example: interval ‘1’ day  Subtracting a date/time/timestamp value from another gives an interval value  Interval values can be added to date/time/timestamp values
  • 25. ©Silberschatz, Korth and Sudarshan 4.25 Database System Concepts - 6th Edition Large-Object Types  Large objects (photos, videos, CAD files, etc.) are stored as a large object:  blob: binary large object -- object is a large collection of binary data (whose interpretation is left to an application outside of the database system).  clob: character large object -- object is a large collection of character data.  When a query returns a large object, a pointer is returned rather than the large object itself.
  • 26. ©Silberschatz, Korth and Sudarshan 4.26 Database System Concepts - 6th Edition User-Defined Types  create type construct in SQL-99 creates user-defined type create type Dollars as numeric (12,2)  The user-defined type Dollars to be decimal numbers with a total of 12 digits, with two decimal point.  The newly created types can then be used, as types of attributes of relations.  create table department ( dept_name varchar (20), building varchar (15), budget Dollars );
  • 27. ©Silberschatz, Korth and Sudarshan 4.27 Database System Concepts - 6th Edition Domains  create domain construct in SQL-92 creates user-defined domain types create domain person_name as char(20) not null  Types and domains are similar. Domains can have constraints or default values specified on them.  create domain degree_level varchar(10) constraint degree_level_test check (value in (’Bachelors’, ’Masters’, ’Doctorate’));
  • 28. ©Silberschatz, Korth and Sudarshan 4.28 Database System Concepts - 6th Edition Views  In some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.)  Consider a person who needs to know an instructors name and department, but not the salary. This person should see a relation described, in SQL, by select ID, name, dept_name from instructor  A view provides a mechanism to hide certain data from the view of certain users.  Any relation that is not of the conceptual model but is made visible to a user as a “virtual relation” is called a view.
  • 29. ©Silberschatz, Korth and Sudarshan 4.29 Database System Concepts - 6th Edition View Definition  A view is defined using the create view statement which has the form create view v as < query expression > where <query expression> is any legal SQL expression. The view name is represented by v.  View definition is not the same as creating a new relation by evaluating the query expression  Rather, a view definition causes the saving of an expression; the expression is substituted into queries using the view.  i.e. whenever the view relation is accessed, its tuples are created by computing the query result.
  • 30. ©Silberschatz, Korth and Sudarshan 4.30 Database System Concepts - 6th Edition Example Views  A view of instructors without their salary create view faculty as select ID, name, dept_name from instructor  Once a view is created, we can use the view to refer to the virtual relation that the view generates. (select * from faculty)  View names may appear in a query any place where a relation name may appear.  Find all instructors in the Biology department select name from faculty where dept_name = ‘Biology’
  • 31. ©Silberschatz, Korth and Sudarshan 4.31 Database System Concepts - 6th Edition Views  The attribute names of a view can also be specified explicitly.  Create a view of department salary total create view departments_total_salary(dept_name, total_salary) as select dept_name, sum (salary) from instructor group by dept_name;  The preceding view gives for each department the sum of the salaries of all the instructors at that department.  At any given time, the set of tuples in the view relation is the result of evaluation of the query expression that defines the view.
  • 32. ©Silberschatz, Korth and Sudarshan 4.32 Database System Concepts - 6th Edition Views Defined Using Other Views  One view may be used in the expression defining another view.  A view relation v1 is said to depend directly on a view relation v2 if v2 is used in the expression defining v1.  A view relation v1 is said to depend on view relation v2 if either v1 depends directly to v2 or there is a path of dependencies from v1 to v2  A view relation v is said to be recursive if it depends on itself.
  • 33. ©Silberschatz, Korth and Sudarshan 4.33 Database System Concepts - 6th Edition Views Defined Using Other Views  create view physics_fall_2009 as select course.course_id, sec_id, building, room_number from course, section where course.course_id = section.course_id and course.dept_name = ’Physics’ and section.semester = ’Fall’ and section.year = ’2009’;  create view physics_fall_2009_watson as select course_id, room_number from physics_fall_2009 where building= ’Watson’;
  • 34. ©Silberschatz, Korth and Sudarshan 4.34 Database System Concepts - 6th Edition Materialized Views  Certain database systems allow view relations to be stored, but they make sure that, if the actual relations used in the view definition change, the view is kept up-to-date. Such views are called materialized views.  The process of keeping the materialized view up-to-date is called view maintenance. Advantages  Applications that use a view frequently may benefit if the view is materialized.  Applications that demand fast response to certain queries that compute aggregates over large relations can also benefit by creating materialized views corresponding to the queries. Disadvantage: Overhead of storage and update cost.
  • 35. ©Silberschatz, Korth and Sudarshan 4.35 Database System Concepts - 6th Edition Update of a View  Views present serious problems if we allow updates, insertions, or deletions with them.  The difficulty is that a modification to the database expressed in terms of a view must be translated to a modification to the actual relations  Add a new tuple to faculty view which we defined earlier insert into faculty values (’30765’, ’Green’, ’Music’);  This insertion must be represented by an insertion into the actual relation instructor.  However, to insert a tuple into instructor, we must have some value for salary. This insertion must be null for the salary into the instructor relation. (’30765’, ’Green’, ’Music’, null)
  • 36. ©Silberschatz, Korth and Sudarshan 4.36 Database System Concepts - 6th Edition Some Updates cannot be Translated Uniquely  create view instructor_info as select ID, name, building from instructor, department where instructor.dept_name= department.dept_name;  insert into instructor_info values (’69987’, ’White’, ’Taylor’); which department, if multiple departments in Taylor? what if no department is in Taylor?  Most SQL implementations allow updates only on simple views  The from clause has only one database relation.  The select clause contains only attribute names of the relation, and does not have any expressions, aggregates, or distinct specification.  Any attribute not listed in the select clause can be set to null  The query does not have a group by or having clause.
  • 37. ©Silberschatz, Korth and Sudarshan 4.37 Database System Concepts - 6th Edition Index Creation  create table student ( ID varchar (5), name varchar (20) not null, dept_name varchar (20), tot_cred numeric (3,0) default 0, primary key (ID) );  create index studentID_index on student(ID)  Indices are data structures used to speed up access to records with specified values for index attributes  e.g. select * from student where ID = ‘12345’ can be executed by using the index to find the required record, without looking at all records of student
  • 38. ©Silberschatz, Korth and Sudarshan 4.38 Database System Concepts - 6th Edition Transactions  A transaction consists of a sequence of query and/or update statements. (Unit of work).  Begin implicitly when an SQL statement is executed.  One of the following SQL statements must end the transaction:  Commit [work] commits the current transaction; that is, it makes the updates performed by the transaction become permanent in the database.  Rollback [work] causes the current transaction to be rolled back; that is, it undoes all the updates performed by the SQL statements in the transaction.  Once a transaction has executed commit work, its effects can no longer be undone by rollback work.
  • 39. ©Silberschatz, Korth and Sudarshan 4.39 Database System Concepts - 6th Edition Transactions  Atomic transaction  either fully executed or rolled back as if it never occurred  Isolation from concurrent transactions  But default on most databases: each SQL statement commits automatically  Can turn off auto commit for a session (e.g. using API) (SET autocommit = 0;) (MySQL)  In SQL:1999, can use: begin atomic …. end Not supported on most databases (START TRANSACTION ……… COMMIT/ROLLBACK)
  • 40. ©Silberschatz, Korth and Sudarshan 4.40 Database System Concepts - 6th Edition Authorization  Specifying access rights/privileges to resources is called authorization.  We may assign a user several forms of authorization on data of the database:  Read (Select) - allows reading, but not modification of data.  Insert - allows insertion of new data, but not modification of existing data.  Update - allows modification, but not deletion of data.  Delete - allows deletion of data.  Each of these types of authorizations is called a privilege.  DB Admin may authorize the user all, none, or a combination of these privileges on a relation or a view.
  • 41. ©Silberschatz, Korth and Sudarshan 4.41 Database System Concepts - 6th Edition Authorization  When a user submits a query or an update, the SQL first checks if the query or update is authorized, based on the authorizations that the user has been granted.  If the query or update is not authorized, it is rejected.  Users may also be granted authorizations on the database schema, allowing them to create, modify, or drop relations. Forms of authorization to modify the database schema  Index - allows creation and deletion of indices.  Resources - allows creation of new relations.  Alteration - allows addition or deletion of attributes in a relation.  Drop - allows deletion of relations. A user who has some form of authorization is allowed to pass on (grant) this authorization to other users, or to withdraw (revoke) an authorization that was granted earlier. (NOT by Default)
  • 42. ©Silberschatz, Korth and Sudarshan 4.42 Database System Concepts - 6th Edition Authorization Specification in SQL  The grant statement is used to confer authorization grant <privilege list> on <relation name or view name> to <user/role list>  <user list> is:  a user-id  public, which allows all valid users the privilege is granted  A role (more on this later)  Granting a privilege on a view does not imply granting any privileges on the underlying relations.  The grantor of the privilege must already hold the privilege on the specified item (or be the database administrator).  grant and revoke are DDL (DCL) commands.
  • 43. ©Silberschatz, Korth and Sudarshan 4.43 Database System Concepts - 6th Edition Privileges in SQL  select: allows read access to relation, or the ability to query using the view  Example: grant users U1, U2, and U3 select authorization on the instructor relation: grant select on instructor to U1, U2, U3  insert: the ability to insert data(tuples) in a relation.  update: the ability to update (some/all attributes of a relation)  delete: the ability to delete data(tuples) of a relation.  all [ privileges ]: used as a short form for all the allowable privileges.  A user who creates a new relation is given all privileges on that relation automatically.
  • 44. ©Silberschatz, Korth and Sudarshan 4.44 Database System Concepts - 6th Edition Revoking Authorization in SQL  The revoke statement is used to revoke authorization. revoke <privilege list> on <relation name or view name> from <user/role list> Example: revoke select on branch from U1, U2, U3  <privilege-list> may be all to revoke all privileges the revokee may hold.  If <revokee-list> includes public, all users lose the privileges.  If the same privilege was granted twice to the same user by different grantees, the user may retain the privilege after the revocation.  All privileges that depend on the privilege being revoked are also revoked.
  • 45. ©Silberschatz, Korth and Sudarshan 4.45 Database System Concepts - 6th Edition Roles  A set of roles (users) is created in the database.  Each database user is granted a set of roles.  Any authorization that can be granted to a user can be granted to a role.  create role instructor;  grant instructor to Amit;  Privileges can be granted to roles:  grant select on takes to instructor;
  • 46. ©Silberschatz, Korth and Sudarshan 4.46 Database System Concepts - 6th Edition Roles  Roles can be granted to users, as well as to other roles  create role teaching_assistant  grant teaching_assistant to instructor; Instructor inherits all privileges of teaching_assistant  There can be a chain of roles;  create role dean;  grant instructor to dean;  grant dean to Satoshi; Thus the privileges of a user or a role consist of:  All privileges directly granted to the user/role.  All privileges granted to roles that have been granted to the user/role.
  • 47. ©Silberschatz, Korth and Sudarshan 4.47 Database System Concepts - 6th Edition Authorization on Views  A user who creates a view does not necessarily receive all privileges on that view. Example: A user who creates a view cannot be given update authorization on a view without having update authorization on the actual relations used to define the view.  If a user creates a view on which no authorization can be granted, the system will deny the view creation request. create view geo_instructor as (select * from instructor where dept_name = ’Geology’);  The creator of the geo_instructor view must have select authorization on the instructor relation.
  • 48. ©Silberschatz, Korth and Sudarshan 4.48 Database System Concepts - 6th Edition Authorizations on Schema  SQL includes a references privilege that permits a user to declare foreign keys when creating relations.  references privilege to create foreign key grant reference (dept_name) on department to Mariano;  This grant statement allows user Mariano to create relations with an attribute that references the dept_name of the department relation as a foreign key.  Why is this required? ( Foreign key constraints restrict updates or deletes on referenced relations )
  • 49. ©Silberschatz, Korth and Sudarshan 4.49 Database System Concepts - 6th Edition Transfer of privileges  A user who has been granted some form of authorization may be allowed to pass on this authorization to other users.  To grant a privilege and to allow the recipient to pass the privilege on to other users, we append the with grant option clause to the grant command. grant select on department to Amit with grant option;  The passing of a specific authorization from one user to another can be represented by an authorization graph.  The graph includes an edge Ui → Uj if user Ui grants authorization to Uj.  The root of the graph is the database administrator.  A user has an authorization if and only if there is a path from the root down to the node representing the user.
  • 50. ©Silberschatz, Korth and Sudarshan 4.50 Database System Concepts - 6th Edition Authorization-grant graph  U5 is granted authorization by both U1 and U2, where as U4 is granted authorization by only U1.
  • 51. ©Silberschatz, Korth and Sudarshan 4.51 Database System Concepts - 6th Edition Revoking of Privileges  Revocation of a privilege from a user/role may cause other users/roles also to lose that privilege. This behavior is called cascading revocation.  revoke select on department from Amit, Satoshi cascade; (By default)  The revoke statement may specify restrict in order to prevent cascading revocation:  revoke select on department from Amit, Satoshi restrict;  The following revoke statement revokes only the grant option, rather than the actual select privilege.  revoke grant option for select on department from Amit; (cascade of Amit grants)