72
Chapter 9 Chapter 9 Relational Data Relational Data Retrieval: SQL Retrieval: SQL Fundamentals of Database Management Systems by Mark L. Gillenson, Ph.D. University of Memphis Presentation by: Amita Goyal Chin, Ph.D. Virginia Commonwealth University John Wiley & Sons, Inc.

Chapter 9 Relational Data Retrieval: SQL Fundamentals of Database Management Systems by Mark L. Gillenson, Ph.D. University of Memphis Presentation by:

Embed Size (px)

Citation preview

Chapter 9Chapter 9Relational Data Relational Data Retrieval: SQLRetrieval: SQL

Fundamentals of Database Management Systemsby

Mark L. Gillenson, Ph.D.

University of Memphis

Presentation by: Amita Goyal Chin, Ph.D.

Virginia Commonwealth University

John Wiley & Sons, Inc.

9-9-22

Chapter ObjectivesChapter Objectives

Describe SQL as a relational data manipulation Describe SQL as a relational data manipulation language. language.

Explain that you can create and update Explain that you can create and update relational tables using SQL. relational tables using SQL.

Write SQL SELECT commands to retrieve Write SQL SELECT commands to retrieve relational data using a variety of operators, relational data using a variety of operators, including GROUP BY, ORDER BY, and the built-including GROUP BY, ORDER BY, and the built-in functions of AVG, SUM, MAX, MIN, and in functions of AVG, SUM, MAX, MIN, and COUNT. COUNT.

9-9-33

Chapter ObjectivesChapter Objectives

Write SQL SELECT commands that join Write SQL SELECT commands that join relational tables. relational tables.

Write SQL SELECT subqueries. Write SQL SELECT subqueries.

Describe a strategy for writing SQL SELECT Describe a strategy for writing SQL SELECT statements. statements.

Describe the principles of how a relational query Describe the principles of how a relational query optimizer works. optimizer works.

9-9-44

Data ManagementData Management

Data DefinitionData Definition

Data ManipulationData Manipulation

9-9-55

Data Management: Data Management: Data DefinitionData Definition

Operationalized with a data definition Operationalized with a data definition language (DDL).language (DDL).

Instructs the DBMS software on what Instructs the DBMS software on what tables will be in the database, what tables will be in the database, what attributes will be in the tables, which attributes will be in the tables, which attributes will be indexed, etc.attributes will be indexed, etc.

9-9-66

Data Management: Data Management: Data ManipulationData Manipulation

Refers to the four basic operations that can and Refers to the four basic operations that can and must be performed on data stored in any DBMS.must be performed on data stored in any DBMS. Data retrievalData retrieval Data updateData update Insertion of new recordsInsertion of new records Deletion of existing recordsDeletion of existing records

Requires data manipulation language (DML)Requires data manipulation language (DML)

9-9-77

SQLSQL

Structured Query LanguageStructured Query Language

Incorporates both DDL and DML features.Incorporates both DDL and DML features.

Very heavily used in practice today.Very heavily used in practice today.

9-9-88

Building the Data StructureBuilding the Data Structure

Base tables - actual physical tables in which the Base tables - actual physical tables in which the data will be stored on the disk.data will be stored on the disk.

Created using the CREATE TABLE command.Created using the CREATE TABLE command.

Deleted using the DROP TABLE command.Deleted using the DROP TABLE command.

9-9-99

Logical ViewLogical View

Also just called a Also just called a view.view.

May consist of a subset of the columns of a single table, May consist of a subset of the columns of a single table, a subset of the rows of a single table, or both.a subset of the rows of a single table, or both.

May also be the join of two or more base tables.May also be the join of two or more base tables.

A mapping onto the base table(s).A mapping onto the base table(s).

Created using the CREATE VIEW command.Created using the CREATE VIEW command.

9-9-1010

Data Manipulation OperationsData Manipulation Operations

UPDATE - used for updating existing data.UPDATE - used for updating existing data.

INSERT - used for inserting new rows in INSERT - used for inserting new rows in tables.tables.

DELETE - used for deleting existing rows DELETE - used for deleting existing rows in tables.in tables.

9-9-1111

Introduction: SQL SELECTIntroduction: SQL SELECT

Used for data retrieval.Used for data retrieval.

You specify what data you are looking for rather You specify what data you are looking for rather than provide a logical sequence of steps that than provide a logical sequence of steps that guide the system in how to find the data.guide the system in how to find the data.

Can be run in either a query or an embedded Can be run in either a query or an embedded mode.mode.

Command will work with Oracle, MS Access, SQL Command will work with Oracle, MS Access, SQL Server, DB2, Informix, etc.Server, DB2, Informix, etc.

9-9-1212

The Basic SQL SELECTThe Basic SQL SELECT

SELECT <columns> FROM <table> WHERE <predicates identifying rows to be included>;

9-9-1313

General Hardware Company General Hardware Company Database (Modified)Database (Modified)

9-9-1414

General Hardware Company General Hardware Company SQL Query ExampleSQL Query Example

The desired attributes are listed in the SELECT clause.The desired attributes are listed in the SELECT clause.

The required table is listed in the FROM clause.The required table is listed in the FROM clause.

The restriction (predicate) indicating which row(s) is involved is The restriction (predicate) indicating which row(s) is involved is shown in the WHERE clause in the form of an equation.shown in the WHERE clause in the form of an equation.

“Find the commission percentage and year of hire of salesperson number 186.”

SELECT COMMPERCT, YEARHIRE FROM SALESPERSONWHERE SPNUM=186;

9-9-1515

General Hardware Company General Hardware Company SQL Query Example, *SQL Query Example, *

The “*” indicates that all attributes of the selected row are The “*” indicates that all attributes of the selected row are to be retrieved.to be retrieved.

“Retrieve the entire record for salesperson 186.”

SELECT *FROM SALESPERSONWHERE SPNUM=186;

9-9-1616

General Hardware Company General Hardware Company SQL Query ExampleSQL Query Example

The search argument is nonunique in this query.The search argument is nonunique in this query.

“List the salesperson numbers and salesperson names of those salespersons who have a commission percentage of 10.”

SELECT SPNUM, SPNAMEFROM SALESPERSONWHERE COMMPERCT=10;

9-9-1717

General Hardware Company General Hardware Company SQL Query Example, No SQL Query Example, No

WHEREWHERE

For a Relational Algebra Project operation, there is For a Relational Algebra Project operation, there is no need for a WHERE clause to limit which rows of no need for a WHERE clause to limit which rows of the table are included.the table are included.

“List the salesperson number and salesperson name of all of the salespersons.”

SELECT SPNUM, SPNAMEFROM SALESPERSON;

9-9-1818

General Hardware Company General Hardware Company SQL Query Example, *SQL Query Example, *

Retrieves an entire table, that is, the query places Retrieves an entire table, that is, the query places no restrictions on either the rows or the attributes.no restrictions on either the rows or the attributes.

“Retrieve all of the Salespersons.”

SELECT *FROM SALESPERSON;

9-9-1919

ComparisonsComparisons

In addition to equal (=), the standard In addition to equal (=), the standard comparison operators can be used in the comparison operators can be used in the WHERE clause.WHERE clause. Greater than (>)Greater than (>) Less than (<)Less than (<) Greater than or equal to (>=)Greater than or equal to (>=) Less than or equal to (<=)Less than or equal to (<=) Not equal to (<>)Not equal to (<>)

9-9-2020

General Hardware Company General Hardware Company SQL Query Example, <SQL Query Example, <

“List the salesperson numbers, salesperson names, and commission percentages of the salespersons whose commission percentage is less than 12.”

SELECT SPNUM, SPNAME, COMMPERCTFROM SALESPERSONWHERE COMMPERCT < 12;

9-9-2121

General Hardware Company General Hardware Company SQL Query Example, >=SQL Query Example, >=

“List the customer numbers and headquarters cities of the customers that have a customer number of at least 1700.”

SELECT CUSTNUM, HQCITY FROM CUSTOMER WHERE CUSTNUM >= 1700;

9-9-2222

General Hardware Company General Hardware Company SQL Query Example: ANDSQL Query Example: AND

“List the customer numbers, customer names, and headquarters cities of the customers that are headquartered in New York and that have a customer number higher than 1500.”

SELECT CUSTNUM, CUSTNAME, HQCITYFROM CUSTOMERWHERE HQCITY=’New York’AND CUSTNUM>1500;

With the AND operator, both conditions have to With the AND operator, both conditions have to be satisfied to be included in the result. be satisfied to be included in the result.

9-9-2323

General Hardware Company General Hardware Company SQL Query Example: ORSQL Query Example: OR

“List the customer numbers, customer names, and headquarters cities of the customers that are headquartered in New York or that have a customer number higher than 1500.”

SELECT CUSTNUM, CUSTNAME, HQCITYFROM CUSTOMERWHERE HQCITY=’New York’OR CUSTNUM>1500;

The OR operator really The OR operator really means one or the other or means one or the other or both.both.

9-9-2424

General Hardware Company General Hardware Company SQL Query Example: AND, ORSQL Query Example: AND, OR

AND is said to be AND is said to be “higher in “higher in precedence” than precedence” than OR.OR.

So all ANDs are So all ANDs are considered before considered before any ORs are any ORs are considered.considered.

“List the customer numbers, customer names, and headquarters cities of the customers that are headquartered in New York or that satisfy the two conditions of having a customer number higher than 1500 and being headquartered in Atlanta.”

9-9-2525

General Hardware Company General Hardware Company SQL Query Example: AND, ORSQL Query Example: AND, OR

“List the customer numbers, customer names, and headquarters cities of the customers that are headquartered in New York or that satisfy the two conditions of having a customer number higher than 1500 and being headquartered in Atlanta.”

SELECT CUSTNUM, CUSTNAME, HQCITYFROM CUSTOMERWHERE HQCITY=’New York’OR CUSTNUM>1500AND HQCITY=’Atlanta’;

9-9-2626

General Hardware Company General Hardware Company SQL Query Example: AND, ORSQL Query Example: AND, OR

SELECT CUSTNUM, CUSTNAME, HQCITYFROM CUSTOMERWHERE (HQCITY=’New York’OR CUSTNUM>1500)AND HQCITY=’Atlanta’;

If you really If you really wanted the OR wanted the OR to be to be considered considered first, you could first, you could force it by force it by writing the writing the query as:query as:

9-9-2727

General Hardware Company General Hardware Company SQL Query Example: BETWEENSQL Query Example: BETWEEN

“Find the customer records for those customers whose customer numbers are between 1000 and 1700, inclusive.”

SELECT *FROM CUSTOMERWHERE (CUSTNUM>=1000 AND CUSTNUM<=1700);

Allows you to specify a range Allows you to specify a range of numeric values in a of numeric values in a search.search.

SELECT *FROM CUSTOMERWHERE CUSTNUM BETWEEN 1000 AND 1700;

9-9-2828

General Hardware Company General Hardware Company SQL Query Example: INSQL Query Example: IN

“Find the customer records for those customers headquartered in Atlanta, Chicago, or Washington.”

SELECT *FROM CUSTOMERWHERE (HQCITY=’Atlanta’OR HQCITY=’Chicago’OR HQCITY=’Washington’);

SELECT *FROM CUSTOMERWHERE HQCITY IN (‘Atlanta’, ‘Chicago’, ‘Washington’);

9-9-2929

General Hardware Company General Hardware Company SQL Query Example: LIKESQL Query Example: LIKE

“Find the customer records for those customers whose names begin with the letter “A”.”

SELECT *FROM CUSTOMERWHERE CUSTNAME LIKE ‘A%’;

““%” character used as a “wildcard” to %” character used as a “wildcard” to represent any string of characters.represent any string of characters.

9-9-3030

General Hardware Company General Hardware Company SQL Query Example: LIKESQL Query Example: LIKE

“Find the customer records for those customers whose names have the letter “a” as the second letter of their names.”

SELECT *FROM CUSTOMERWHERE CUSTNAME LIKE ‘_a%’;

The single “_” character in the operator LIKE “_a%” The single “_” character in the operator LIKE “_a%” specifies that there will be one character followed by specifies that there will be one character followed by “a.”“a.”

9-9-3131

General Hardware Company General Hardware Company SQL Query Example: DISTINCTSQL Query Example: DISTINCT

“Which cities serve as headquarters cities for General Hardware customers?”

SELECT HQCITYFROM CUSTOMER;

Eliminate duplicate Eliminate duplicate rows in a query rows in a query result.result.

SELECT DISTINCT HQCITYFROM CUSTOMER;

9-9-3232

General Hardware Company General Hardware Company SQL Query Example: ORDER BYSQL Query Example: ORDER BY

“Find the customer numbers, customer names, and headquarters cities of those customers with customer numbers greater than 1000. List the results in alphabetic order by headquarters cities.”

SELECT CUSTNUM, CUSTNAME, HQCITYFROM CUSTOMERWHERE CUSTNUM>1000ORDER BY HQCITY;

Orders the results of an SQL query by one or more Orders the results of an SQL query by one or more specified attributes.specified attributes.

9-9-3333

General Hardware Company SQL General Hardware Company SQL Query Example: ORDER BYQuery Example: ORDER BY

The default order for ORDER BY is The default order for ORDER BY is ascending.ascending.

The clause can include the term ASC at The clause can include the term ASC at the end to make ascending explicit.the end to make ascending explicit.

The clause can include DESC for The clause can include DESC for descending order. descending order.

9-9-3434

General Hardware Company General Hardware Company SQL Query Example: AVGSQL Query Example: AVG

“Find the average number of units of the different products that Salesperson 137 has sold (i.e., the average of the quantity values in the first three records of the SALES table).”

SELECT AVG(QUANTITY)FROM SALESWHERE SPNUM=137;

AVG is a AVG is a built-inbuilt-in function of SQL. function of SQL.

9-9-3535

General Hardware Company General Hardware Company SQL Query Example: SUMSQL Query Example: SUM

SELECT SUM(QUANTITY)FROM SALESWHERE SPNUM=137;

“Find the total number of all products that Salesperson 137 has sold.”

SUM is a SUM is a built-inbuilt-in function of SQL. function of SQL.

9-9-3636

General Hardware Company General Hardware Company SQL Query Example: MAXSQL Query Example: MAX

“What is the largest number of units of Product Number 21765 that any individual salesperson has sold?”

SELECT MAX(QUANTITY)FROM SALESWHERE PRODNUM=21765;

MAX is a MAX is a built-inbuilt-in function of SQL. function of SQL.

9-9-3737

General Hardware Company General Hardware Company SQL Query Example: MINSQL Query Example: MIN

SELECT MIN(QUANTITY)FROM SALESWHERE PRODNUM=21765;

MIN is a MIN is a built-inbuilt-in function of SQL. function of SQL.

“What is the smallest number of units of Product Number 21765 that any individual salesperson has sold?”

9-9-3838

General Hardware Company General Hardware Company SQL Query Example: COUNTSQL Query Example: COUNT

“How many salespersons have sold Product Number 21765?”

SELECT COUNT(*)FROM SALES WHERE PRODNUM=21765;

COUNT counts the number of rows that COUNT counts the number of rows that satisfy a set of criteria.satisfy a set of criteria.

9-9-3939

General Hardware Company General Hardware Company SQL Query Example: GROUP BYSQL Query Example: GROUP BY

“Find the total number of units of all products sold by each salesperson.”

SELECT SPNUM, SUM(QUANTITY) FROM SALESGROUP BY SPNUM;

Used when calculations are to be made on Used when calculations are to be made on several different groups of rows.several different groups of rows.

9-9-4040

General Hardware Company General Hardware Company SQL Query Example: HAVINGSQL Query Example: HAVING

“Find the total number of units of all products sold by each salesperson whose salesperson number is at least 150. Only include salespersons whose total number of units sold is at least 5000.”

SELECT SPNUM, SUM(QUANTITY) FROM SALESWHERE SPNUM>=150GROUP BY SPNUMHAVING SUM(QUANTITY)>=5000;

HAVING limits the results of a GROUP BY based on HAVING limits the results of a GROUP BY based on the values calculated for each group with the built-in the values calculated for each group with the built-in functions.functions.

9-9-4141

The JoinThe Join

SQL SELECT allows you to join two or more tables.SQL SELECT allows you to join two or more tables.

Two specifications must be made in the SELECT Two specifications must be made in the SELECT statement.statement. The tables to be joined must be listed in the FROM clause.The tables to be joined must be listed in the FROM clause. The join attributes in the tables being joined must be declared The join attributes in the tables being joined must be declared

and matched to each other in the WHERE clause.and matched to each other in the WHERE clause.

A table name qualifier is required when different tables A table name qualifier is required when different tables have an attribute with the same name.have an attribute with the same name.

9-9-4242

General Hardware Company General Hardware Company SQL Query Example: JoinSQL Query Example: Join

“Find the name of the salesperson responsible for Customer Number 1525.”

SELECT SPNAMEFROM SALESPERSON, CUSTOMERWHERE SALESPERSON.SPNUM=CUSTOMER.SPNUM AND CUSTNUM=1525;

9-9-4343

General Hardware Company General Hardware Company SQL Query Example: JoinSQL Query Example: Join

“List the names of the products of which salesperson Adams has sold more than 2,000 units.”

SELECT PRODNAMEFROM SALESPERSON, PRODUCT, SALESWHERE SALESPERSON.SPNUM=SALES.SPNUMAND SALES.PRODNUM=PRODUCT.PRODNUMAND SPNAME=’Adams’AND QUANTITY>2000;

9-9-4444

SubqueriesSubqueries

One SELECT statement is “nested” within One SELECT statement is “nested” within another.another.

Nesting can go on through several levels of Nesting can go on through several levels of SELECT statements with each successive SELECT statements with each successive SELECT statement contained in a pair of SELECT statement contained in a pair of parentheses.parentheses.

The innermost SELECT statement is executed The innermost SELECT statement is executed first, and its results are then provided as input to first, and its results are then provided as input to the SELECT statement at the next level up.the SELECT statement at the next level up.

9-9-4545

General Hardware Company General Hardware Company SQL Query Example: SubquerySQL Query Example: Subquery

“Find the name of the salesperson responsible for Customer Number 1525.”

SELECT SPNAMEFROM SALESPERSONWHERE SPNUM=

(SELECT SPNUMFROM CUSTOMERWHERE CUSTNUM=1525);

Subquery as an alternative to Subquery as an alternative to joinjoin..

9-9-4646

General Hardware Company General Hardware Company SQL Query Example: SubquerySQL Query Example: Subquery

“Which salespersons with salesperson numbers greater than 200 have the lowest commission percentage of any such salesperson?” (We’ll identify salespersons by their salesperson number.)

SELECT SPNUMFROM SALESPERSONWHERE SPNUM>200AND COMMPERCT=

(SELECT MIN(COMMPERCT)FROM SALESPERSON)WHERE SPNUM>200);

A subquery is A subquery is required.required.

9-9-4747

A Strategy for Writing SQL A Strategy for Writing SQL SELECT CommandsSELECT Commands

Determine what the result of the query is to be and write Determine what the result of the query is to be and write the needed attributes and functions in the SELECT clause.the needed attributes and functions in the SELECT clause.

Determine which tables of the database will be needed for Determine which tables of the database will be needed for the query and write their names in the FROM clause.the query and write their names in the FROM clause.

If the query involves a join, begin constructing the WHERE If the query involves a join, begin constructing the WHERE clause by equating the join attributes from the tables that clause by equating the join attributes from the tables that are in the FROM clause.are in the FROM clause.

Continue filling in the details of the WHERE clause, the Continue filling in the details of the WHERE clause, the GROUP BY clause, and any subqueries.GROUP BY clause, and any subqueries.

9-9-4848

Example - Good Reading Example - Good Reading BookstoresBookstores

PUBNAME CITY COUNTRY TELEPHONE YRFOUND

PUBLISHER Table

AUTHORNUM AUTHORNAME YEARBORN YEARDIED

AUTHOR Table

BOOKNUM BOOKNAME PUBYEAR PAGES PUBNAME

BOOK Table

CUSTNUM CUSTNAME STREET CITY STATE COUNTRY

CUSTOMER Table

BOOKNUM AUTHORNUM

WRITING Table

BOOKNUM CUSTNUM DATE PRICE QUANTITY

SALE Table

9-9-4949

Sample QueriesSample Queries

“Find the book number, book name, and number of pages of all of the books published by London Publishing Ltd. List the results in order by book name.”

SELECT BOOKNUM, BOOKNAME, PAGES FROM BOOKWHERE PUBNAME=’London Publishing Ltd.’ ORDER BY BOOKNAME;

9-9-5050

Sample QueriesSample Queries

“How many books of at least 400 pages does Good Reading Bookstores carry that were published by publishers based in Paris, France?”

SELECT COUNT(*)FROM PUBLISHER, BOOKWHERE PUBLISHER.PUBNAME=BOOK.PUBNAME AND CITY=’Paris’AND COUNTRY=’France’AND PAGES>=400;

9-9-5151

Sample QueriesSample Queries

“List the publishers in Belgium, Brazil, and Singapore that publish books written by authors who were born before 1920.”

SELECT DISTINCT PUBNAMEFROM PUBLISHER, BOOK, WRITING, AUTHORWHERE PUBLISHER.PUBNAME=BOOK.PUBNAMEAND BOOK.BOOKNUM=WRITING.BOOKNUMAND WRITING.AUTHORNUM=AUTHOR.AUTHORNUM AND COUNTRY IN (‘Belgium’, ‘Brazil’, ‘Singapore’)AND YEARBORN<1920;

9-9-5252

Sample QueriesSample Queries

“How many books did each publisher in Oslo, Norway; Nairobi, Kenya; and Auckland, New Zealand, publish in 2001?”

SELECT PUBNAME, CITY, COUNTRY, COUNT(*)FROM PUBLISHER, BOOKWHERE PUBLISHER.PUBNAME=BOOK.PUBNAMEAND ((CITY=’Oslo’ AND COUNTRY=’Norway’)

OR (CITY=’Nairobi’ AND COUNTRY=’Kenya’)OR (CITY=’Auckland’ AND COUNTRY=’New Zealand’))

AND PUBYEAR=2001GROUP BY PUBNAME;

9-9-5353

Sample QueriesSample Queries

“Which publisher published the book that has the earliest publication year among all of the books that Good Reading Bookstores carries?”

SELECT DISTINCT PUBNAMEFROM BOOKWHERE PUBYEAR=

(SELECT MIN(PUBYEAR)FROM BOOK);

9-9-5454

Example - World Music Example - World Music AssociationAssociation

ORCHNAME CITY COUNTRY MUSICDIR

ORCHESTRA Table

MUSNUM MUSNAME INSTRUMENT ANNSALARY ORCHNAME

MUSICIAN Table

MUSNUM DEGREE UNIVERSITY YEAR

DEGREE Table

COMPOSERNAME COUNTRY DATEBIRTH

COMPOSER Table

COMPOSITIONNAME COMPOSERNAME YEAR

COMPOSITION Table

ORCHNAME COMPOSITIONNAME COMPOSERNAME YEAR PRICE

RECORDING Table

9-9-5555

Sample QueriesSample Queries

“What is the total annual salary cost for all of the violinists of the Berlin Symphony Orchestra?”

SELECT SUM(ANNSALARY)FROM MUSICIANWHERE ORCHNAME=’Berlin Symphony Orchestra’AND INSTRUMENT=’Violin’;

9-9-5656

Sample QueriesSample Queries

“Make a single list, in alphabetic order of all of the universities attended by the cellists of India.”

SELECT DISTINCT UNIVERSITYFROM ORCHESTRA, MUSICIAN, DEGREEWHERE ORCHESTRA.ORCHNAME=MUSICIAN.ORCHNAMEAND MUSICIAN.MUSNUM=DEGREE.MUSNUM AND INSTRUMENT=’Cello’AND COUNTRY=’India’ORDER BY UNIVERSITY;

9-9-5757

Sample QueriesSample Queries

“What is the total annual salary cost for all of the violinists of each orchestra located in Canada? Only include in the result those orchestras whose total annual salary for its violinists is in excess of $150,000.”

SELECT ORCHNAME, SUM(ANNSALARY)FROM ORCHESTRA, MUSICIANWHERE ORCHESTRA.ORCHNAME=MUSICIAN.ORCHNAME AND COUNTRY=’Canada’AND INSTRUMENT=’Violin’GROUP BY ORCHNAMEHAVING SUM(ANNSALARY)>150,000;

9-9-5858

Sample QueriesSample Queries

“What is the name of the most highly paid pianist?”

SELECT MUSNAMEFROM MUSICIANWHERE INSTRUMENT=’Piano’AND ANNSALARY=

(SELECT MAX(ANNSALARY)FROM MUSICIANWHERE INSTRUMENT=’Piano’);

9-9-5959

Sample QueriesSample Queries

“What is the name of the most highly paid pianist of any orchestra in Australia?”

SELECT MUSNAMEFROM MUSICIAN, ORCHESTRAWHERE MUSICIAN.ORCHNAME=ORCHESTRA.ORCHNAMEAND INSTRUMENT=’Piano’AND COUNTRY=’Australia’AND ANNSALARY=

(SELECT MAX(ANNSALARY)FROM MUSICIAN, ORCHESTRAWHERE MUSICIAN.ORCHNAME=ORCHESTRA.ORCHNAMEAND INSTRUMENT=’Piano’AND COUNTRY=’Australia’);

9-9-6060

Example - Lucky Rent-A-CarExample - Lucky Rent-A-CarMANUFNAME COUNTRY SALESREPNAME SALESREPPHONE

MANUFACTURER Table

CARNUM MODEL YEAR CLASS MANUFNAME

CAR Table

REPAIRNUM CARNUM DATE PROCEDURE MILEAGE REPAIRTIME

MAINTENANCE Table

CUSTNUM CUSTNAME CUSTADDR CUSTPHONE

CUSTOMER Table

CARNUM CUSTNUM RENTALDATE RETURNDATE COST

RENTAL Table

9-9-6161

Sample QueriesSample Queries

“List the manufacturers whose names begin with the letter C or the letter D and that are located in Japan.”

SELECT MANUFNAMEFROM MANUFACTURERWHERE (MANUFNAME LIKE ‘C%’OR MANUFNAME LIKE ‘D%’)AND COUNTRY=’Japan’;

9-9-6262

Sample QueriesSample Queries

“What was the average mileage of the cars that had tune-ups in August 2003?”

SELECT AVG(MILEAGE)FROM MAINTENANCEWHERE PROCEDURE=’Tune-Up’AND DATE BETWEEN ‘AUG-01-2003’ AND ‘AUG-31-2003’;

9-9-6363

Sample QueriesSample Queries

“How many different car models do manufacturers in Italy make?”

SELECT COUNT(DISTINCT MODEL)FROM MANUFACTURER, CARWHERE MANUFACTURER.MANUFNAME=CAR.MANUFNAMEAND COUNTRY=’Italy’;

9-9-6464

Sample QueriesSample Queries

“How many repairs were performed on each car manufactured by Superior Motors during the month of March 2004? Only include cars in the result that had at least three repairs.”

SELECT CAR.CARNUM, COUNT(*)FROM CAR, MAINTENANCEWHERE CAR.CARNUM=MAINTENANCE.CARNUMAND MANUFNAME=’Superior Motors’AND DATE BETWEEN ‘MAR-01-2004’ AND ‘MAR-31-2004’ GROUP BY CAR.CARNUMHAVING COUNT(*)>=3;

9-9-6565

Sample QueriesSample Queries“List the cars of any manufacturer that had an oil change in January 2004 and had at least as many miles as the highest mileage car manufactured by Superior Motors that had an oil change that same month.”

SELECT MAINTENANCE.CARNUMFROM MAINTENANCEWHERE PROCEDURE=’Oil Change’AND DATE BETWEEN ‘JAN-01-2004’ AND ‘JAN-31-2004’AND MILEAGE>=

(SELECT MAX(MILEAGE)FROM CAR, MAINTENANCEWHERE CAR.CARNUM, MAINTENANCE.CARNUM AND PROCEDURE=’Oil Change’AND DATE BETWEEN ‘JAN-01-2004’ AND ‘JAN-31-2004AND MANUFNAME=’Superior Motors’);

9-9-6666

Relational Query OptimizerRelational Query Optimizer

Relational DBMS PerformanceRelational DBMS Performance

Relational Query Optimizer ConceptsRelational Query Optimizer Concepts

9-9-6767

Relational Query Optimizer: Relational Query Optimizer: Relational DBMS PerformanceRelational DBMS Performance The speed with which the required data can be The speed with which the required data can be

retrieved. Performance regarding joins is a retrieved. Performance regarding joins is a particular problem.particular problem.

SolutionsSolutions Tuning of the database structure, physical database Tuning of the database structure, physical database

design.design.

Relational query optimizer software that evaluates Relational query optimizer software that evaluates each SQL SELECT statement and determines an each SQL SELECT statement and determines an efficient way to satisfy it.efficient way to satisfy it.

9-9-6868

Relational Query Optimizer: Relational Query Optimizer: ConceptsConcepts

All major SQL processors include a query All major SQL processors include a query optimizer.optimizer.

Using a query optimizer, SQL attempts to figure Using a query optimizer, SQL attempts to figure out the most efficient way of answering a query, out the most efficient way of answering a query, prior to actually responding to it.prior to actually responding to it.

The query optimizer uses the The query optimizer uses the relational relational catalogcatalog, an internal database., an internal database.

9-9-6969

Query Optimizer ConsiderationsQuery Optimizer Considerations

Which attributes have indexes built over them?Which attributes have indexes built over them?

How many rows does each table have?How many rows does each table have?

Which attributes are unique?Which attributes are unique?

How many records of a table are really needed How many records of a table are really needed for a particular join?for a particular join?

Which join algorithm is best for this query?Which join algorithm is best for this query?

9-9-7070

Join AlgorithmsJoin Algorithms

Nested-loop joinNested-loop join A Cartesian productA Cartesian product One of the two tables is selected for the outer One of the two tables is selected for the outer

loop and the other for the inner loop.loop and the other for the inner loop. Each of the records of the outer loop is Each of the records of the outer loop is

chosen in succession, and, for each, the inner chosen in succession, and, for each, the inner loop table is scanned for matches on the join loop table is scanned for matches on the join attribute.attribute.

9-9-7171

Join AlgorithmsJoin Algorithms

Merge-scan joinMerge-scan join More efficient than the nested-loop join.More efficient than the nested-loop join. Can only be used if certain conditions are Can only be used if certain conditions are

met.met.• Each of the two join attributes has to be in sorted Each of the two join attributes has to be in sorted

order, ororder, or• Each of the two join attributes has to have an index Each of the two join attributes has to have an index

built over it.built over it.

9-9-7272

“Copyright 2004 John Wiley & Sons, Inc. All rights reserved. Reproduction or translation of this work beyond that permitted in Section 117 of the 1976 United States Copyright Act without express permission of the copyright owner is unlawful. Request for further information should be addressed to the Permissions Department, John Wiley & Sons, Inc. The purchaser may make back-up copies for his/her own use only and not for distribution or resale. The Publisher assumes no responsibility for errors, omissions, or damages caused by the use of these programs or from the use of the information contained herein.”