Structured Query Language (2)
The main reference of this presentation is the textbook and PPT from : Elmasri & Navathe, Fundamental of Database Systems, 4th edition, 2004, Chapter 8Additional resources: presentation prepared by Prof Steven A. Demurjian, Sr (http://www.engr.uconn.edu/~steve/courses.html)
Slide 5-2
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
Outline
Tables as Sets in SQLSubstring pattern matchingArithmatic operationNULL values in SQLNested queriesEXISTS FUNCTIONEXPLICIT SET & RENAMING ATTRIBUTEJOINAGGREGATE FUNCTIONGROUPING & HAVING CLAUSE
Slide 5-3
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
SET OPERATIONSSQL has directly incorporated some set operationsThere is a union operation (UNION), and in some versions of SQL there are set difference (MINUS) and intersection (INTERSECT) operationsThe resulting relations of these set operations are sets of tuples; duplicate tuples are eliminated from the resultThe 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
Slide 5-4
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
SET OPERATIONS (cont.) Query 4: 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.
Q4: (SELECT PNUMBERFROM PROJECT, DEPARTMENT,
EMPLOYEEWHERE DNUM=DNUMBER AND
MGRSSN=SSN AND LNAME='Smith')UNION(SELECT PNUMBERFROM PROJECT, WORKS_ON, EMPLOYEEWHERE PNUMBER=PNO AND ESSN=SSN
AND LNAME='Smith')
Slide 5-5
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
SUBSTRING COMPARISON
The LIKE comparison operator is used to compare partial stringsTwo reserved characters are used: '%' (or '*' in some implementations) replaces an arbitrary number of characters, and '_' replaces a single arbitrary character
Slide 5-6
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
SUBSTRING COMPARISON (cont.)
Query 12: Retrieve all employees whose address is in Houston, Texas. Here, the value of the ADDRESS attribute must contain the substring 'Houston,TX'.
Q12: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE ADDRESS LIKE '%Houston, TX
%’
Slide 5-7
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
SUBSTRING COMPARISON (cont.)
Query 12A: Retrieve all employees who were born during the 1950s. Here, '5' must be the 8th character of the string (according to our format for date), so the BDATE value is '_______5_', with each underscore as a place holder for a single arbitrary character.
Q12A: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE BDATE LIKE '_______5_’
If underscore or % is needed as a literal character in the string, the character should be preceded by an escape character (‘\’).
‘AB\_CD\%EF’ is represent ‘AB_CD%EF’
Slide 5-8
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
ARITHMETIC OPERATIONS
The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction, multiplication, and division, respectively) can be applied to numeric values in an SQL query resultQuery 13: Show the effect of giving all employees who work on the 'ProductX' project a 10% raise.
Q13:SELECT FNAME, LNAME, 1.1*SALARYAS INCREASED_SAL
FROM EMPLOYEE, WORKS_ON, PROJECTWHERE SSN=ESSN AND PNO=PNUMBER AND
PNAME='ProductX’
Slide 5-9
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
ARITHMETIC OPERATIONS (2)
Query 14: Retrieve all employees in department 5 whose salary is between $30,000 and $40,000
Q14:SELECT *FROM EMPLOYEEWHERE (SALARY BETWEEN 30000 AND 40000)
AND DNO=5;
Q14A:SELECT *FROM EMPLOYEEWHERE (SALARY >= 30000 AND SALARY
<=40000)AND DNO=5;
Slide 5-10
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
ORDER BY
The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s)Query 15: 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.
Q15: SELECT DNAME, LNAME, FNAME, PNAME FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT
WHERE DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER
ORDER BY DNAME, LNAME
Slide 5-11
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
ORDER BY (cont.)
The default order is in ascending order of valuesWe 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
Slide 5-12
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
NULLS IN SQL QUERIESSQL allows queries that check if a value is NULL (missing or undefined or not applicable)SQL uses IS or IS NOT to compare NULLs because it considers each NULL value distinct from other NULL values, so equality comparison is not appropriate .Query 18: Retrieve the names of all employees who do not have supervisors.Q18: SELECT FNAME, LNAME
FROM EMPLOYEEWHERE SUPERSSN IS NULL
Note: If a join condition is specified, tuples with NULL values for the join attributes are not included in the result
Slide 5-13
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
NESTING OF QUERIESSome queries require that existing values in the database be fetched and then used in a comparison condition using nested queryA nested query is a complete SELECT-FROM-WHERE block within in the WHERE-clause of another queryThat other query is called the outer queryQuery 1A: Retrieve the name and address of all employees who work for the 'Research' department.
Q1A: SELECT FNAME, LNAME, ADDRESSFROM EMPLOYEEWHERE DNO IN
(SELECT DNUMBER FROM DEPARTMENTWHERE DNAME='Research' )
Outer Query
Nested Query
Slide 5-14
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
NESTING OF QUERIES (cont.)
The nested query selects the number of the 'Research' departmentThe outer query select an EMPLOYEE tuple if its DNO value is in the result of either nested queryThe comparison operator IN compares a value v with a set (or multi-set) of values V, and evaluates to TRUE if v is one of the elements in VIn general, we can have several levels of nested queries
Slide 5-15
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
NESTING OF QUERIES (cont.)
SQL allows the use of tuples of values in comparisons by placing them within parenthesesQuery: retrieve the SSN from all employees who work the same (project,hours) combination on same project that employee ‘Jhon Smith’ (ESSN = ‘123456789’ works on.
SELECT DISTINCT ESSNFROM WORKS_ONWHERE (PNO, HOURS) IN (SELECT PNO,
HOURS FROM WORKS_ON WHERE ESSN = ‘123456789’);
Slide 5-16
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
NESTING OF QUERIES (cont.)
Comparison operator can be used in nested query: >, >=, <, <=, <>Keyword ALL can be used(v > ALL V) returns TRUE if the value v is greater than all the values in the set (or multiset) V.Query: Return the names of employees whose salary is greater than salary of all the employees in department 5.
SELECT LNAME, FNAMEFROM EMPLOYEEWHERE SALARY > ALL (SELECT SALARY
FROM EMPLOYEE WHERE DNO=5)
Slide 5-17
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
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 correlatedThe result of a correlated nested query is different for each tuple (or combination of tuples) of the relation(s) the outer queryQuery 16: Retrieve the name of each employee who has a dependent with the same first name and same sex as the employee.
Q16: SELECT E.FNAME, E.LNAMEFROM EMPLOYEE AS EWHERE SSN IN (SELECT ESSN
FROM DEPENDENTWHERE FNAME=DEPENDENT_NAMEAND E.SEX = SEX)
Refer to sex attribute in outer
query (EMPLOYEE)
Slide 5-18
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
CORRELATED NESTED QUERIES (cont.)
A query written with nested SELECT... FROM... WHERE... blocks and using the = or IN comparison operators can always be expressed as a single block query. For example, Q12 may be written as in Q12A
Q12A: SELECT E.FNAME, E.LNAMEFROM EMPLOYEE E, DEPENDENT DWHERE E.SSN=D.ESSN AND
E.FNAME=D.DEPENDENT_NAMEANDE.SEX = D.SEX
The original SQL as specified for SYSTEM R also had a CONTAINS comparison operator, which is used in conjunction with nested correlated queriesThis operator was dropped from the language, possibly because of the difficulty in implementing it efficiently
Slide 5-19
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
CORRELATED NESTED QUERIES (cont.)
Most implementations of SQL do not have this operatorThe CONTAINS operator compares two sets of values , and returns TRUE if one set contains all values in the other set (reminiscent of the division operation of algebra).
• Query 3: Retrieve the name of each employee who works on all the projects controlled by department number 5.
Q3: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE ( (SELECT PNO
FROM WORKS_ON WHERE SSN=ESSN) CONTAINS (SELECT PNUMBER FROM PROJECT WHERE DNUM=5) )
Slide 5-20
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
CORRELATED NESTED QUERIES (cont.)
In Q3, the second nested query, which is not correlated with the outer query, retrieves the project numbers of all projects controlled by department 5The first nested query, which is correlated, retrieves the project numbers on which the employee works, which is different for each employee tuple because of the correlation
Slide 5-21
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
THE EXISTS FUNCTION
EXISTS is used to check whether the result of a correlated nested query is empty (contains no tuples) or notWe can formulate Query 12 in an alternative form that uses EXISTS as Q12B belowEXISTS AND NOT EXISTS are usually used in conjunction with a correlated nested query
Slide 5-22
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
THE EXISTS FUNCTION (cont.)Query 12: Retrieve the name of each employee who has a dependent with the same first name and same sex as the employee.
Q12B: SELECT FNAME, LNAMEFROM EMPLOYEE EWHERE EXISTS (SELECT *
FROM DEPENDENTWHERE SSN=ESSN AND
FNAME=DEPENDENT_NAME AND E.SEX = SEX
)
Slide 5-23
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
THE EXISTS FUNCTION (cont.)Query 6: Retrieve the names of employees who have no dependents.
Q6: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE NOT EXISTS (SELECT
*FROM DEPENDENTWHERE SSN=ESSN)
In Q6, the correlated nested query retrieves all DEPENDENT tuples related to an EMPLOYEE tuple. If none exist , the EMPLOYEE tuple is selected
Slide 5-24
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
THE EXISTS FUNCTION (cont.)Query 7:List the names of managers who have at least one dependent.
SELECT FNAME, LNAMEFROM EMPLOYEEWHEREEXISTS (SELECT * FROM DEPENDENT WHERE SSN=ESSN)ANDEXISTS (SELECT * FROM DEPARTMENT WHERE SSN = MGRSSN);
The first nested query select all DEPENDENT tuples related to an EMPLOYEEThe second nested query select all DEPARTMENT tuples managed by the EMPLOYEEIf at least one of the first and at least one of the second exists, we select the EMPLOYEE tuple.
Can you rewrite that query using only one nested query or no nested query ?
Slide 5-25
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
THE EXISTS FUNCTION (cont.)Query 3: Retrieve the name of each employee who works on all the projects controlled by department number 5Can be used: (S1 CONTAINS S2) that logically equivalent to (S2 EXCEPT S1) is empty.SELECT FNAME, LNAMEFROM EMPLOYEEWHERE NOT EXISTS( (SELECT PNUMBER FROM PROJECT WHERE DNUM=5) EXCEPT (SELECT PNO FROM WORKS_ON WHERE SSN = ESSN));
The first subquery select all projects controlled by dept 5The second subquery select all projects that 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
Slide 5-26
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
EXPLICIT SETS
It is also possible to use an explicit (enumerated) set of values in the WHERE-clause rather than a nested queryQuery 17: Retrieve the social security numbers of all employees who work on project number 1, 2, or 3.
Q17: SELECT DISTINCT ESSNFROM WORKS_ONWHERE PNO IN (1, 2, 3)
Slide 5-27
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
RENAMING ATTRIBUTE
In SQL, its possible to rename attribute that appears in the result of a query by adding the qualifier AS followed by the desired new name.
Q8A: SELECT E.LNAME AS EMPLOYEE_NAME, S.LNAME AS
SUPERVISOR_NAMEFROM EMPLOYEE E, EMPLOYEE SWHERE E.SUPERSSN = S.SSN;
Slide 5-28
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
Joined Relations Feature in SQL2
Can specify a "joined relation" in the FROM-clauseLooks like any other relation but is the result of a joinAllows the user to specify different types of joins (regular "theta" JOIN, NATURAL JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, CROSS JOIN, etc)
Slide 5-29
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
Example-Cross Join
Beers
name manf
Beer 1
XYZ
Beer 2
ABC
Beer 3
ABCLikes
drinker beer
Narpati Beer 1
Nizar Beer 1
Danu Beer 3
SELECT * FROM Beers CROSS JOIN Likes
name manf drinker Beer
Beer 1 XYZ Narpati Beer 1
Beer 1 XYZ Nizar Beer 1
Beer 1 XYZ Danu Beer 3
Beer 2 ABC Narpati Beer 1
Beer 2 ABC Nizar Beer 1
Beer 2 ABC Danu Beer 3
Beer 3 ABC Narpati Beer 1
Beer 3 ABC Nizar Beer 1
Beer 3 ABC Danu Beer 3
Slide 5-30
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
Example-Natural JoinLikes
drinker beer
Narpati Beer 1
Nizar Beer 1
Danu Beer 3
Harith Beer 2
Frequents
drinker bar
Avi ABC
Danu XYZ
Nizar ABC
Jack Zanz
SELECT * FROM Beers NATURAL JOIN Likes
drinker
beer bar
Nizar Beer 1
ABC
Danu Beer 3
XYZ
Slide 5-31
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
Example-Theta Join
Beers
name manf
Beer 1 XYZ
Beer 2 ABC
Beer 3 ABC
Likes
drinker beer
Narpati
Beer 1
Nizar Beer 1
Danu Beer 3
SELECT * FROM Beers B JOIN Likes L ON B.name = L.beer
name manf drinker beer
Beer 1 XYZ Narpati Beer 1
Beer 1 XYZ Nizar Beer 1
Beer 3 ABC Danu Beer 3
Slide 5-32
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
Example-Outer Join
Beers
name manf
Beer 1 XYZ
Beer 2 ABC
Beer 3 ABC
Likes
SELECT * FROM Beers B LEFT OUTER JOIN Likes L ON B.name = L.beername manf drinker beer
Beer 1 XYZ Narpati Beer 1
Beer 1 XYZ Nizar Beer 1
Beer 2 ABC
Beer 3 ABC Danu Beer 3
drinker beer
Narpati Beer 1
Nizar Beer 1
Danu Beer 3
Avi Beer 5
SELECT * FROM Beers B RIGHT OUTER JOIN Likes L ON B.name = L.beername manf drinker beer
Beer 1 XYZ Narpati Beer 1
Beer 1 XYZ Nizar Beer 1
Beer 3 ABC Danu Beer 3
Avi Beer 5
Slide 5-33
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
Example-Outer Join
Beers
name manf
Beer 1
XYZ
Beer 2
ABC
Beer 3
ABCLikes
SELECT * FROM Beers B FULL OUTER JOIN Likes L ON B.name = L.beername manf drinker beer
Beer 1 XYZ Narpati Beer 1
Beer 1 XYZ Nizar Beer 1
Beer 2 ABC
Beer 3 ABC Danu Beer 3
Avi Beer 5
drinker beer
Narpati Beer 1
Nizar Beer 1
Danu Beer 3
Avi Beer 5
Slide 5-34
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
AGGREGATE FUNCTIONS
Include COUNT, SUM, MAX, MIN, and AVGQuery : Find the maximum salary, the minimum salary, and the average salary among all employees.
SELECT MAX(SALARY), MIN(SALARY),
AVG(SALARY)FROM EMPLOYEE
Some SQL implementations may not allow more than one function in the SELECT-clause
Slide 5-35
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
AGGREGATE FUNCTIONS (cont.)
Query : 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, DEPARTMENTWHERE DNO=DNUMBER AND
DNAME='Research'
Slide 5-36
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
AGGREGATE FUNCTIONS (cont.)
Queries : Retrieve the total number of employees in the company (QA), and the number of employees in the 'Research' department (QB).
QA: SELECT COUNT (*)FROM EMPLOYEE
QB: SELECT COUNT (*)FROM EMPLOYEE,
DEPARTMENTWHERE DNO=DNUMBER AND
DNAME='Research’
Slide 5-37
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
GROUPING
In many cases, we want to apply the aggregate functions to subgroups of tuples in a relationEach 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 independentlySQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-clause
Slide 5-38
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
GROUPING (cont.)Query 24: For each department, retrieve the department number, the number of employees in the department, and their average salary.
Q24:SELECT DNO, COUNT (*), AVG (SALARY)FROM EMPLOYEEGROUP BY DNO
In Q24, the EMPLOYEE tuples are divided into groups--each group having the same value for the grouping attribute DNOThe COUNT and AVG functions are applied to each such group of tuples separatelyThe SELECT-clause includes only the grouping attribute and the functions to be applied on each group of tuplesA join condition can be used in conjunction with grouping
Slide 5-39
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
GROUPING (cont.)
Query 25: For each project, retrieve the project number, project name, and the number of employees who work on that project.
Q25: SELECT PNUMBER, PNAME, COUNT (*)FROM PROJECT, WORKS_ONWHERE PNUMBER=PNOGROUP BY PNUMBER, PNAME
In this case, the grouping and functions are applied after the joining of the two relations
Slide 5-40
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
THE HAVING-CLAUSE
Sometimes we want to retrieve the values of these functions for only those groups that satisfy certain conditionsThe HAVING-clause is used for specifying a selection condition on groups (rather than on individual tuples)
Slide 5-41
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
THE HAVING-CLAUSE (cont.)
Query 26: 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.
Q26: SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ONWHERE PNUMBER=PNOGROUP BY PNUMBER, PNAMEHAVING COUNT (*) > 2
Slide 5-42
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
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>]
Slide 5-43
Elmasri and Navathe, Fundamentals of Database Systems, Fourth EditionRevised by IB & SAM, Fasilkom UI, 2005
Summary of SQL Queries (cont.)
The SELECT-clause lists the attributes or functions to be retrievedThe FROM-clause specifies all relations (or aliases) needed in the query but not those needed in nested queriesThe WHERE-clause specifies the conditions for selection and join of tuples from the relations specified in the FROM-clauseGROUP BY specifies grouping attributesHAVING specifies a condition for selection of groupsORDER BY specifies an order for displaying the result of a queryA query is evaluated by first applying the WHERE-clause, then GROUP BY and HAVING, and finally the SELECT-clause
Top Related