0% found this document useful (0 votes)
3 views66 pages

DB08 Query

RDBMS slide chương 8

Uploaded by

vubaohuy2903
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views66 pages

DB08 Query

RDBMS slide chương 8

Uploaded by

vubaohuy2903
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

08

Query
FIT

Outline

• Select Basic
• Comparison operators
• Between … And, In
• Like
• Not – And – Or
• More than one table query
• Aggregate Functions
• Grouping – Having Clause

• Ref: Chapter 6, 7

2 Design and Manage Database


FIT

Retrieval Queries in SQL

• SQL has one basic statement for retrieving information from a


database; the SELECT statement
• This is not the same as the SELECT operation of the relational algebra
• Important distinction between SQL and the formal relational
model:
• SQL allows a table (relation) to have two or more tuples that are
identical in all their attribute values
• Hence, an SQL relation (table) is a multi-set (sometimes called a
bag) of tuples; it is not a set of tuples
• SQL relations can be constrained to be sets by specifying
PRIMARY KEY or UNIQUE attributes, or by using the DISTINCT
option in a query

3 Design and Manage Database


FIT

• A bag or multi-set is like a set, but an element may appear more


than once.
• Example:
• {A, B, C, A} is a bag.
• {A, B, C} is also a bag that also is a set.
• Bags also resemble lists, but the order is irrelevant in a bag.
• Example:
• {A, B, A} = {B, A, A} as bags
• However, [A, B, A] is not equal to [B, A, A] as lists

4 Design and Manage Database


FIT

• Basic form of the SQL SELECT statement is called a mapping or a


SELECT-FROM-WHERE block

SELECT <attribute list>


FROM <table list>
WHERE <condition>;

• <attribute list> is a list of attribute names whose values are to be retrieved


by the query
• <table list> is a list of the relation names required to process the query
• <condition> is a conditional (Boolean) expression that identifies the tuples
to be retrieved by the query

5 Design and Manage Database


FIT

• Example of a simple query on one table


List all Employee.
SELECT *
FROM EMPLOYEE;

6 Design and Manage Database


FIT

• Retrieve the First name, Last name and address of the employees
Select Fname, Lname, Address
From Employee;

7 Design and Manage Database


FIT

Comparison operators

Comparison operators: =,!=,<>,<,<=,>,>=



Retrieve the birthday and address of the employee whose first name is
'John‘ (string).
SELECT Bdate, Address
FROM EMPLOYEE
WHERE Fname='John‘;

8 Design and Manage Database


FIT

• Retrieve the last name, birth date and address of the employees
whose last name is not ‘Borg‘ (string).
SELECT Lname, Bdate, Address
FROM EMPLOYEE
WHERE Lname <>‘Borg’;

9 Design and Manage Database


FIT

• Retrieve the first name and last name of the employee whose
DNo is 5 (number).
SELECT Fname, Lname
FROM EMPLOYEE
WHERE DNo = 5;

10 Design and Manage Database


FIT

• Retrieve the first name and last name of the employee whose
salary is greater or equal 40000 (number).
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Salary >= 40000;

11 Design and Manage Database


FIT

• Retrieve the name, SSN and address of the employee whose


birthdates ‘Jul-31-1972’ (date).
SELECT Lname, Minit, LName, SSn
FROM EMPLOYEE
WHERE Bdate = ‘1972-07-31’;

12 Design and Manage Database


FIT

Null

• Retrieve the first name and last name of the employees who does not
have his supper.
SELECT Fname, Minit, Lname
FROM EMPLOYEE
WHERE Supper_SSN is null;
• Note that NULL indicates a value which is missing, not known, inappropriate, etc.
NULL is not a blank or zero. NULL cannot be tested for equality with other NULL
values.

13 Design and Manage Database


FIT

String Operations

• Pattern matching
• Simple pattern matching is carried out using LIKE:
LIKE ’pattern-to-match’
• Where the pattern can include special wildcard characters:
• % (percent) 0 or more arbitrary characters
• _ (underscore) any one character

14 Design and Manage Database


FIT

• Retrieve all employees whose address is in Houston, Texas. Here, the value of the
ADDRESS attribute must contain the substring 'Houston,TX‘ in it.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Address LIKE ‘Houston,TX%‘;

• Find the names of all employees whose first


name starts with ‘J’ character and are at least
4 characters in length.
Select FName, Lname
From employee
Where FName like 'J___';

15 Design and Manage Database


FIT

Arithmetic Operations

• The standard arithmetic operators '+', '-'. '*', and '/' (for addition,
subtraction, multiplication, and division, respectively) can be
applied to numeric values in an SQL query result

• Show the effect of giving all employees who work on the


'ProductX' project a 10% raise.
SELECT Fname, Lname, 1.1*Salary
FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE Ssn=Essn AND Pno=Pnumber
AND Pname='ProductX’;

16 Design and Manage Database


FIT

Distinct – Order clause

SELECT [DISTINCT] column_list


FROM table_list
[WHERE condition]
[ORDER BY attribute[DESC/ASC]
[,attribute [DESC,ASC]]...];

17 Design and Manage Database


FIT

Distinct

• Use Of DISTINCT
• SQL does not treat a relation as a set; duplicate tuples can appear
• To eliminate duplicate tuples in a query result, the keyword
DISTINCT is used
SELECT Salary
FROM EMPLOYEE;

SELECT DISTINCT Salary


FROM EMPLOYEE;

18 Design and Manage Database


FIT

Order By

• We can specify the keyword DESC if we want a descending order; the keyword
ASC can be used to explicitly specify ascending order, even though it is the
default
• Example:
SELECT Dname, Lname, Fname, Pname
FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT
WHERE Dnumber=Dno AND Ssn=Essn AND Pno=Pnumber
ORDER BY Dname, Lname DESC;

19 Design and Manage Database


FIT

Operator: Not – And – Or

• Not
Select *
From Employee
Where Supper_SSn is Not Null;

20 Design and Manage Database


FIT

• And
Select *
From Employee
Where Fname = ‘Joyce’ And Lname = ‘English’;

21 Design and Manage Database


FIT

• Or
Select *
From Employee
Where Lname = ‘English’ Or Fname = ‘James’;

22 Design and Manage Database


FIT

Operator: Between … And …

• Between … And …
• Retrieve the first name, last name and address of the employee whose
birthdates from June-01-1959 to Dec-31-1959.
SELECT Fname, Lname, address
FROM EMPLOYEE
WHERE Bdate Between ‘1959-01-01’ And ‘1959-06-31’;

• Note that the BETWEEN predicate is inclusive. The above condition is


equivalent to :
WHERE Bdate >= ‘1959-01-01’ And Bdate <= ‘1959-06-31’;

23 Design and Manage Database


FIT

Operator: In

• In
• Retrieve the first name, last name and address of the employee
whose Dno is 1 or 4.
SELECT Fname, Lname, address
FROM EMPLOYEE
WHERE Dno In (1,4);

• The above condition is equivalent to :


WHERE Dno = 1 Or Dno = 4;

24 Design and Manage Database


FIT

Display Data from multiple tables

• Obtaining Data from Multiple Tables

Fname LName SSN Dno Dnumber Dname


Join Smith 123456789 5 5 Research
… … … … … …
James Borg 888665555 1 1 Headquarters
25 Design and Manage Database
FIT

• Syntax
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;

• Use a join to query data from more than one table.


• Write the join condition in the WHERE clause.
• Prefix the column name with the table name when the same column name appears in
more than one table.

• Ex:
Select Fname, Lname, Dname
From Employee, Department
Where Employee.Dno = Department.Dnumber;

26 Design and Manage Database


FIT

Aliases

• Some queries need to refer to the same relation twice


• In this case, aliases are given to the relation name

• For each employee, retrieve the employee's name, and the name of his or her
immediate supervisor.
SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE as E, EMPLOYEE as S
WHERE E.Super_ssn = S.Ssn;

• The alternate relation names E and S are called aliases or tuple variables for
the EMPLOYEE relation
• We can think of E and S as two different copies of EMPLOYEE; E represents
employees in role of supervisees and S represents employees in role of
supervisors

27 Design and Manage Database


FIT

• Aliasing can also be used in any SQL query for convenience

• Can also use the AS keyword to specify aliases


SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn=S.Ssn;

EMPLOYEE E EMPLOYEE S

28 Design and Manage Database


FIT

Joining More than Two Tables

Fname LName SSN Dno Dnumber Dname Dnumber Dlocation


Join Smith 123456789 5 5 Research 5 Bellaire
Join Smith 123456789 5 5 Research 5 Sugarland
Join Smith 123456789 5 5 Research 5 Houston
… … … … … … … …
James Borg 888665555 1 1 Headquarter 1 Houston
29 Design and Manage Database
FIT

UNSPECIFIED WHERE-clause

• Example:
SELECT Ssn, Dname
FROM EMPLOYEE, DEPARTMENT;

• It is extremely important not to overlook specifying any selection and join


conditions in the WHERE-clause; otherwise, incorrect and very large
relations may result

How many rows?

30 Design and Manage Database


FIT

• For every project located in 'Stafford', list the project number, the controlling
department number, and the department manager's last name, address, and
birthdate.
SELECT Pnumber, Dnum, Lname, Bdate, Address
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNum=DNumber AND MgrSSN=SSN
AND Plocation='Stafford‘;

There are two join conditions


• The join condition DNum=DNumber relates a project to its controlling
department
• The join condition MgrSSN=SSN relates the controlling department to the
employee who manages that department

31 Design and Manage Database


FIT

Set Operations

• SQL has directly incorporated some set operations


• There is a union operation (UNION), and in some versions of SQL
there are set difference (MINUS) and intersection (INTERSECT)
operations
• The resulting relations of these set operations are sets of tuples;
duplicate tuples are eliminated from the result
• 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

32 Design and Manage Database


FIT

• Find number project in Project or in Works_on relation


Select Pnumber From Project
Union
Select Pno From works_on;
Union

33 Design and Manage Database


FIT

• Find number project in Project and in Works_on relation


Select Pnumber From Project
Intersect
Select Pno From works_on;
Intersect

34 Design and Manage Database


FIT

• Find number project in Project but not in Works_on relation


Select Pnumber From Project
Except
Select Pno From works_on;
Except

35 Design and Manage Database


FIT

• SQL has directly incorporated some set operations


• The resulting relations of these set operations are sets of
tuples; duplicate tuples are eliminated from the result
• 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
• To retain all duplicates use the
• union all,
• intersect all
• except all.

36 Design and Manage Database


FIT

Nesting Of Queries - Subqueries

• A complete SELECT query, called a nested query, can be specified within the WHERE-clause of
another query, called the outer query
• Many of the previous queries can be specified in an alternative form using nesting

• Retrieve the name and address of all employees who work for the 'Research' department.
SELECT Fname, Lname, Address
FROM EMPLOYEE
WHERE Dno IN
(SELECT Dnumber
FROM DEPARTMENT
WHERE Dname='Research');

Select Fname, Lname, Address


From Employee E, Department D
Where E.Dno = D.Dnumber And D.Dname='Research‘;

37 Design and Manage Database


FIT

Correlated Nested Queries

• 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
• 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);
SELECT E.Fname, E.Lname
FROM EMPLOYEE E, DEPENDENT D
WHERE E.Ssn=D.Essn AND
E.Fname=D.Dependent_name;

38 Design and Manage Database


FIT

• Retrieve the name of each employee who works on all the


projects controlled by department number 5.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE ((SELECT Pno
FROM WORKS_ON
WHERE Ssn=Essn)
CONTAINS
(SELECT Pnumber
FROM PROJECT
WHERE Dnum=5));

39 Design and Manage Database


FIT

Set Comparison – “some/any” Clause

• Find names of employees with salary greater than that of some (at least one)
employee in the department 5.
Select Distinct E.Fname, E.Lname, E.Salary
From Employee as E, Employee as E5
Where E.salary > E5.salary and E5.DNo = 5;
• Same query using > some clause
Select Fname, LName, Salary
From Employee
Where salary > Some (Select Salary From Employee
Where DNo = 5);

40 Design and Manage Database


FIT

Set Comparison – “all” Clause

• Find the names of all employees whose salary is greater than the
salary of all employees in the department 5.
Select Fname, LName, Salary
From Employee
Where salary >
All (Select Salary From Employee
Where DNo = 5);

41 Design and Manage Database


FIT

Test for Empty Relations

• The exists construct returns the value true if the argument subquery is
nonempty.
• exists r  r  Ø
• not exists r  r = Ø
• Retrieve the name of all employees who work for the 'Research'
department.
Select Fname, Lname
From Employee
Where Exists (Select * From Department
Where DNo = Dnumber And Dname='Research' );

Select Fname, Lname


From Employee
Where Dno IN
(Select Dnumber From Department
Where Dname='Research' );

42 Design and Manage Database


FIT

• List the names of employees who have a dependent with


the same first name and sex as themselves.
Select FName, LName
From Employee E
Where Exists
(Select * From Dependent D
Where E.SSN = D.ESSN And
E.FName = D.Dependent_Name And
E.Sex = D.Sex);

Select E.FName, E.Lname


From Employee E, Dependent D
Where E.SSN = D.ESSN And
E.FName = D.Dependent_Name And
E.Sex = D.Sex;

43 Design and Manage Database


FIT

Use of “not exists” Clause

•Find
all employees who have taken all projects managed in the
department 5.
Select E.FName, E.Lname
From employee E
Where not exists
( (select Pnumber from project where DNum = 5)
except
(Select W.Pno From works_on W where W.ESSN = E.SSN));
•First nested query lists all projects managed in department 5.
•Second nested query lists all projects a particular employee works on

•Note
• X – Y = Ø  X Y
•Cannot write this query using = all and its variants

44 Design and Manage Database


FIT

• Query: Give name of employees participating in projects


managed by department 5.

45 Design and Manage Database


FIT

• SQL:
Select A.FName, A.Lname
From employee A
Where Not Exists
(Select *
From Works_On B
Where B.PNo in
(Select PNumber
From Project
where DNum = 5) And Not Exists
(Select *
From Works_On C
Where A.SSN = C.ESSN And C.PNo =
B.PNo));

46 Design and Manage Database


FIT

Joined Relations Feature in SQL2

• Can specify a "joined relation" in the FROM-clause


• Looks like any other relation but is the result of a join
• Allows the user to specify different types of joins (regular "theta" JOIN, NATURAL JOIN,
LEFT OUTER JOIN, RIGHT OUTER JOIN, CROSS JOIN, etc)
• Examples:
SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE E S
WHERE E.super_ssn=S.ssn;

• can be written as:


SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE E LEFT OUTER JOIN EMPLOYEE S
ON E.Super_ssn=S.Ssn);

47 Design and Manage Database


FIT

• Examples:
SELECT Fname, Lname, Address
FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND Dnumber=Dno;

• could be written as:


SELECT Fname, Lname, Address
FROM (EMPLOYEE JOIN DEPARTMENT ON Dnumber=Dno)
WHERE Dname='Research’;

• or as:
SELECT Fname, Lname, Address
FROM (EMPLOYEE NATURAL JOIN EPARTMENT
AS DEPT(Dname, Dno, Mssn,Msdate)
WHERE Dname='Research’;

48 Design and Manage Database


FIT

• Another Example:
For every project located in 'Stafford', list the project number, the controlling department
number, and the department manager's last name, address, and birthdate.
SELECT Pnumber, Dnum, Lname, Bdate, Address
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum=Dnumber AND Mgr_ssn=Ssn
AND Plocation='Stafford‘;

Could be written as follows; this illustrates multiple joins in the joined tables
SELECT Pnumber, Dnum, Lname, Bdate, Address
FROM (PROJECT JOIN DEPARTMENT ON
(Dnum=Dnumber) JOIN EMPLOYEE ON
(Mgr_ssn=Ssn) )
WHERE Plocation='Stafford’;

49 Design and Manage Database


FIT

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.
• Three forms of outer join:
• left outer join
• right outer join
• full outer join

50 Design and Manage Database


FIT

• Relation Course

• Relation GradeReport

• Observe that
Course information is missing BA140
GradeReport information is missing BA250

51 Design and Manage Database


FIT

• Course left outer join GradeReport


 In relational algebra: Course ⟕ GradeReport
 In SQL:
Select *
From Course C Left Outer Join GradeReport G On C.CourseID
= G.CourseID;

52 Design and Manage Database


FIT

• Course Right outer join GradeReport


 In relational algebra: Course ⟖ GradeReport
 In SQL:
Select *
From Course C Right Outer Join GradeReport G On C.CourseID
= G.CourseID;

53 Design and Manage Database


FIT

• Course full outer join GradeReport


 In relational algebra: Course ⟗ GradeReport
 In SQL:
Select *
From Course C Full Outer Join GradeReport G On
C.CourseID = G.CourseID;

54 Design and Manage Database


FIT

Aggregate Functions

• Include COUNT, SUM, MAX, MIN, and AVG

• Find the maximum salary, the minimum salary, the average salary and numbers of
employees.
SELECT MAX(Salary), MIN(Salary), AVG(Salary), Count(*)
FROM EMPLOYEE;

• Some SQL implementations may not allow more than one function in the SELECT-clause

55 Design and Manage Database


FIT

• Find the maximum salary, the minimum salary, and the average
salary among employees who work for the 'Research'
department.
SELECT MAX(Salary), MIN(Salary), AVG(Salary)
FROM EMPLOYEE, DEPARTMENT
WHERE Dno=Dnumber AND Dname='Research‘;

Result?

56 Design and Manage Database


FIT

• Retrieve the total number of employees in the company.


SELECT COUNT (*)
FROM EMPLOYEE;

Result?

57 Design and Manage Database


FIT

• The number of employees in the 'Research' department.


SELECT COUNT (*)
FROM EMPLOYEE, DEPARTMENT
WHERE Dno=Dnumber AND Dname='Research’;

Result?

58 Design and Manage Database


FIT

Grouping

• In many cases, we want to apply the aggregate functions to


subgroups of tuples in a relation
• Each subgroup of tuples consists of the set of tuples that have the
same value for the grouping attribute(s)
• The function is applied to each subgroup independently
• SQL has a GROUP BY-clause for specifying the grouping
attributes, which must also appear in the SELECT-clause

59 Design and Manage Database


FIT

• For each department, retrieve the department number, the


number of employees in the department, and their average
salary.
SELECT Dno, COUNT(*), Sum(Salary)
FROM EMPLOYEE
GROUP BY Dno;

60 Design and Manage Database


FIT

• For each project, retrieve the project number, project name, and
the number of employees who work on that project.
SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno
GROUP BY Pnumber, Pname;

61 Design and Manage Database


FIT

The HAVING-clause

• Sometimes we want to retrieve the values of these functions for


only those groups that satisfy certain conditions

• The HAVING-clause is used for specifying a selection condition on


groups (rather than on individual tuples)

62 Design and Manage Database


FIT

• For each project on which more than two employees work, retrieve
the project number, project name, and the number of employees
who work on that project.
SELECT Pnumber, Pname, COUNT(*)
FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno
GROUP BY Pnumber, Pname
HAVING COUNT (*) > 2;

63 Design and Manage Database


FIT

Summary of SQL Queries

• A query in SQL can consist of up to six clauses, but only the


first two, SELECT and FROM, are mandatory. The clauses are
specified in the following order:

SELECT <attribute list>


FROM <table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>
[HAVING <group condition>]]
[ORDER BY <attribute list>];

64 Design and Manage Database


FIT

• The SELECT-clause lists the attributes or functions to be retrieved


• The FROM-clause specifies all relations (or aliases) needed in the query
but not those needed in nested queries

• The WHERE-clause specifies the conditions for selection and join of


tuples from the relations specified in the FROM-clause

• GROUP BY specifies grouping attributes


• HAVING specifies a condition for selection of groups

• ORDER BY specifies an order for displaying the result of a query


• A query is evaluated by first applying the WHERE-clause, then
GROUP BY and HAVING, and finally the SELECT-clause

65 Design and Manage Database


FIT

66 Design and Manage Database

You might also like