Database Intermediate SQL

#Joined relations

Join operations take two relations and return as 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.

#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 instructor's name and department, but not 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.

#View definition

A view is defined using the create view statement which has the form:

create view view_name as <query expression>

Once the view is defined, the view name can be used to refer to the virtual relation that the view generated.

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.

Examples:

create view faculty as
  select ID, name, dept_name
  from instructor;

select name
from faculty
where dept_name = 'Biology';

create view departments_total_salary(dept_name, total_salary) as
  select dept_name, sum(salary)
  from instructor
  group by dept_name;

You can also defined view 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;

View expansion: Expand use of a view in q query/another view

create view physics_fall_2009_watson as
  (select course_id, room_number
  from (select course.course_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)
        where building = 'Watson';

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.

If a view is often used in queries, it might be very inefficient to recompute the view from scratch every time it is used.

To deal with this, your DBMS will often materialize and then maintain the view under updates to the underlying tables ("materialized views").

The best strategy depends on number of view accesses versus number of updates to the underlying table.

#Update a view

Add a new tuple to faculty view which we defined earlier

insert into faculty values (30765, Green, Music);

This insertion could be represented by the insertion of the tuple (’30765’, ’Green’, ’Music’, null) into the instructor relation

Is this legal?

Yes, assuming we may assign a null value to salary

If salary attribute was NOT NULL, cannot do this.

Some updates can't be translated uniquely Example:

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);

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.

But Oracle allows some updates on views with several relations.

Sometimes you can't update using view:

create view history_instructors as
  select *
  from instructor
  where dept_name= History;

Insert (25566, Brown, Biology, 100000) into history_instructors;
#Transactions:
  • Unit or work
  • Atomic transaction
    • either fully executed or rolled back as if it never occured
  • Isolation from concurrent transactions
  • Transactions begin implicitly
    • Ended by commit work or rollback work
  • But default on most databases: each SQL statement commits automatically.
    • Can turn off auto commit for a session
    • In SQL:1999, can use begin atomic ... end
#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.

Examples:

  • A checking 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.

Constraints on a single relation

  • not null
  • primary key
  • unique
  • check(p), where p is a predicate

not null: name varchar(10) not null

unique(A1, A2, A3) The unique specification states that the attributes A1, A2, A3 form a candidate key. Candidate keys are permitted to be null (in contrast to primary keys).

check(p)

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),
primary key (course_id, sec_id, semester, year),
check (semester in ('Fall', 'Winter', 'Spring', Summer'));
#Referential integrity

Ensures 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.

Example: If "Biology" is a department name appearing in one of the tuples in the instructor relation, then there exists a tuple in the department relation for "Biology".


create table course (
course_id char(5) primary key,
title varchar(20),
dept_name varchar(20) references department
);

create table course (
course_id char(5) primary key,
title varchar(20),
dept_name varchar(20),
foreign key (dept_name) references department
on delete cascade
on update cascade
)

alternative actions to cascade: set null, set default.

Unfortunately: subquery in check clause not supported by pretty much any database

#Other features

index:

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)

large objects:

book review clob(10KB)

image blob(10MB), movie blob(2GB)

blob: binary large object -- object is a large collection of uninterpreted binary data (whose interpretation is left to an application outside of the database system)

clob: character large object -- object is a large collection of char data

When a query returns a large object, a pointer is returned rather than the large object itself.

create user-defined type

create type Dollars as numeric (12,2) final

create table department (
dept_name varchar (20),
building varchar (15),
budget Dollars
);

create domain

create domain person_name char(20) not null

create domain degree_level varchar(10)
constraint degree_level_test
check (value in (Bachelors, Masters, Doctorate));

Types and domains are similar, Domains can have constraints, such as not null.

#Authorization

Forms of authorization on parts of a database:

  • Read - 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.
  • 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.

The grant statement is used to confer authorization

grant <privilege list>
on <relation name or view name> to <user list>

<user list> is

  • a user-id
  • public, which allows all valid users the privilege granted
  • A role

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).

The revoke statement is used to revoke authorization.

revoke <privilege list>
on <relation name or view name> from <user list>

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.

#Roles

Privileges can be granted to roles:

create role instructor;
grant select on takes to instructor;

Roles can be granted to users, as well as to other roles

create role student
grant instructor to Amit;
create role dean;
grant instructor to dean;
grant dean to Satoshi;