Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Module III - Royal Babu

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

CS208 Principles of Database Design Module III MESCE Kuttipuram

Contents:
Structured Query Language (SQL): Basic SQL Structure, examples, Set operations, Aggregate Functions, nested
sub-queries (Reading: Elmasri Navathe, Ch. 4 and 5.1) Views, assertions and triggers (Reading: Elmasri Navathe,
Ch. 5.2-5.3, Optional reading: Silbershatz, Korth Ch. 5.3).

Structured Query Language (SQL)


Basic SQL Structure
Statements used for data definitions, queries, and updates (both DDL and DML). Table, Row, and
Column used for relational model terms Relation, Tuple, and Attribute.

Examples

Department of Information Technology 1 Prof Lino Abraham Varghese


CS208 Principles of Database Design Module III MESCE Kuttipuram

1. Retrieve the birthdate and address of the employee whose name is 'John B. Smith'.

2. Retrieve the name and address of all employees who work for the 'Research' department.

3. For every project located in 'Stafford', list the project number, the controlling department
number, and the department manager's last name, address, and birthdate

4. For each employee, retrieve the employee's name, and the name of his or her immediate
supervisor.

5. Retrieve the SSN values for all employees.

6. Make a list of all project numbers for projects that involve an employee whose last name is
'Smith' as a worker or as a manager of the department that controls the project.

7. Retrieve the name and address of all employees who work for the 'Research' department with
nested queries

8. Retrieve the name of each employee who has a dependent with the same first name as the
employee.

9. Retrieve the name of each employee who works on all the projects controlled by department
number 5.

10. Retrieve the name of each employee who has a dependent with the same first name as the
employee.

11. Retrieve the names of employees who have no dependents.

12. Retrieve the social security numbers of all employees who work on project number 1, 2, or 3.

13. Find the maximum salary, the minimum salary, and the average salary among all employees.

14. Find the maximum salary, the minimum salary, and the average salary among employees who
work for the 'Research' department.

15. Retrieve the total number of employees in the company

16. Retrieve the number of employees in the 'Research' department

17. For each project, retrieve the project number, project name, and the number of employees
who work on that project.

18. Retrieve all employees whose address is in 'Houston,TX'.

19. Retrieve all employees who were born during the 1950s.

20. Show the effect of giving all employees who work on the 'ProductX' project a 10% raise.

21. Retrieve a list of employees and the projects each works in, ordered by the employee's
department, and within each department ordered alphabetically by employee last name.

Department of Information Technology 2 Prof Lino Abraham Varghese


CS208 Principles of Database Design Module III MESCE Kuttipuram

Set Operations
The set operations apply only to union compatible relations; the two relations must have the same
attributes and the attributes must appear in the same order. SQL does not automatically eliminate
duplicate tuples in the results of queries. SQL has directly incorporated some of the set operations
from mathematical set theory, which are also part of relational algebra. They are:
 UNION(set union):
Make a list of all project numbers for projects that involve an employee whose last name is ‘Smith’,
either as a worker or as a manager of the department that controls the project.

 EXCEPT (difference):
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE NOT EXISTS
( (SELECT PNUMBER
FROM PROJECT
WHERE DNUM=5)
EXCEPT
(SELECT PNO
FROM WORKS_ON
WHERE SSN=ESSN) );

The first subquery (which is not correlated) selects all projects controlled by department 5, and the
second subquery (which is correlated) selects all projects that the particular employee being
considered works on. If the set difference of the first subquery MINUS (EXCEPT) the second
subquery is empty, it means that the employee works on all the projects and is hence selected.

 INTERSECT (intersection):
To find the set of all courses taught in the Fall 2009 as well as in Spring 2010
(SELECT COURSE ID
FROM SECTION
WHERE SEMESTER = ’FALL’ AND YEAR= 2009)
INTERSECT
(SELECT COURSE ID
FROM SECTION
WHERE SEMESTER = ’SPRING’ AND YEAR= 2010);

The relations resulting from these set operations are sets of tuples; that is, duplicate tuples are
eliminated from the result. Corresponding multiset operations: UNION ALL, EXCEPT ALL,
INTERSECT ALL

Aggregate Functions
Used to summarize information from multiple tuples into a single-tuple summary. Grouping is used
to create subgroups of tuples before summarizing. Built-in aggregate functions are COUNT, SUM,

Department of Information Technology 3 Prof Lino Abraham Varghese


CS208 Principles of Database Design Module III MESCE Kuttipuram

MAX, MIN, and AVG. Functions can be used in the SELECT clause or in a HAVING clause.
NULL values discarded when aggregate functions are applied to a particular column.

GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-
clause

For each department, retrieve the department number, the number of employees in the department,
and their average salary.

Q20: SELECT DNO, COUNT (*), AVG (SALARY)


FROM EMPLOYEE
GROUP BY DNO

HAVING clause provides a condition on the summary information. The HAVING-clause is used
for specifying a selection condition on groups (rather than on individual tuples).

Nested sub-queries
 Complete select-from-where blocks within WHERE clause of another query.
 Comparison operator IN Compares value v with a set (or multiset) of values V
 Evaluates to TRUE if v is one of the elements in V

Department of Information Technology 4 Prof Lino Abraham Varghese


CS208 Principles of Database Design Module III MESCE Kuttipuram

 Use other comparison operators to compare a single value v


 = ANY (or = SOME) operator
• Returns TRUE if the value v is equal to some value in the set V and is hence
equivalent to IN
 Other operators that can be combined with ANY (or SOME): >, >=, <, <=, and <>

Correlated Nested Query


If a condition in the WHERE-clause of a nested query references an attribute of a relation declared
in the outer query , the two queries are said to be correlated. The result of a correlated nested query
is different for each tuple (or combination of tuples) of the relation(s) the outer query.

Example: Retrieve the name of each employee who has a dependent with the same first name as the
employee.
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE AS E
WHERE E.SSN IN (SELECT ESSN
FROM DEPENDENT
WHERE ESSN=E.SSN
AND E.FNAME=DEPENDENT_NAME)

EXISTS is used to check whether the result of a correlated nested query is empty (contains no
tuples) or not
The six clauses in the syntax of an SQL query

Views
A view in SQL terminology is a single table that is derived from other tables. These other tables
could be base tables or previously defined views. A view does not necessarily exist in physical
form; it is considered a virtual table, in contrast to base tables whose tuples are actually stored in the
database. This limits the possible update operations that can be applied to views, but it does not
provide any limitations on querying a view.

Creating a View:
CREATE VIEW WORKS_ON1
AS SELECT FNAME, LNAME, PNAME, HOURS
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE SSN=ESSN AND PNO=PNUMBER;

Querying a View:
SELECT FNAME, LNAME

Department of Information Technology 5 Prof Lino Abraham Varghese


CS208 Principles of Database Design Module III MESCE Kuttipuram

FROM WORKS_ON1
WHERE PNAME=‘ProjectX’;

Deleting a view:
DROP VIEW WORKS_ON1;
Assertions
Assertions are use to specify additional types of constraints outside scope of built-in relational
model constraints. Specify a query that selects any tuples that violate the desired condition. Use
only in cases where it is not possible to use CHECK on attributes and domains.

For example, to specify the constraint that "the salary of an employee must not be greater than
the salary of the manager of the department that the employee works for"

Triggers
Triggers are used to specify automatic actions that database system will perform when certain
events and conditions occur. A rule in the Event-Condition-Action model has three components:
1. The event (or events) that triggers the rule: These events are usually database update operations
that are explicitly applied to the database.
2. The condition that determines whether the rule action should be executed: Once the triggering
event has occurred, an optional condition may be evaluated. If no condition is specified, the action
will be executed once the event occurs. If a condition is specified, it is first evaluated, and only if it
evaluates to true will the rule action be executed.
3. The action to be taken: The action is usually a sequence of SQL statements, but it could also be a
database transaction or an external program that will be automatically executed.

The example below shows how triggers can be used to ensure referential integrity on the time slot id
attribute of the section relation. The trigger definition specifies that the trigger is initiated after any
insert on the relation section and it ensures that the time slot id value being inserted is valid. An
SQL insert statement could insert multiple tuples of the relation, and the for each row clause in the
trigger code would then explicitly iterate over each inserted row. The referencing new row as
clause creates a variable nrow (called a transition variable) that stores the value of an inserted row
after the insertion.

create trigger timeslot check1 after insert on section


referencing new row as nrow
for each row
when (nrow.time slot id not in (
select time slot id
from time slot)) /* time slot id not present in time slot */
begin
rollback
end;

Department of Information Technology 6 Prof Lino Abraham Varghese

You might also like