single-table queries 2: advanced topics cs 320. review: retrieving data from a single table syntax:...

38
Single-Table Queries 2: Advanced Topics CS 320

Upload: melinda-powell

Post on 17-Jan-2018

216 views

Category:

Documents


0 download

DESCRIPTION

We can use the DBMS to further filter and manipulate data Suppress duplicates Sort Format characters, numbers, & dates Perform arithmetic operations Summarize data Why not just do it in your program?

TRANSCRIPT

Page 1: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Single-Table Queries 2: Advanced TopicsCS 320

Page 2: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Review: Retrieving Data From a Single Table Syntax:

Limitation: Retrieves "raw" data

SELECT field1, field2, …FROM tablenameWHERE search_condition(s)

Page 3: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

We can use the DBMS to further filter and manipulate data Suppress duplicates Sort Format characters, numbers, & dates Perform arithmetic operations Summarize data

Why not just do it in your program?

Page 4: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Suppressing Duplicate Outputs Use the DISTINCT qualifier

Ensures that only distinct rows are returned

SELECT DISTINCT cust_zipFROM candy_customer;

SELECT DISTINCT fieldnameFROM tablenameWHERE search_condition(s);

Page 5: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Sorting Query Output Use the ORDER BY clause:

Always appears as the last item in a SELECT query

SELECT field1, field2, …FROM tablenameWHERE search_condition(s)ORDER BY field_a;

SELECT cust_id, cust_phoneFROM candy_customerWHERE cust_type = 'P'ORDER BY cust_name;

Page 6: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Sort Order Default sort order is ascending

Numbers: smallest to largestCharacters: alphabeticalDates: oldest to newest

To force a descending sort order, add the DESC modifier:

SELECT purch_id, purch_dateFROM candy_purchaseORDER BY purch_date DESC

Page 7: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Multiple Sort Fields You can sort output by multiple fields

Only makes sense when first sort field has repeating values

SELECT purch_id, purch_dateFROM candy_purchaseORDER BY purch_date DESC, purch_id

Page 8: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Modifying Default Data Formats

Default formats:Floating point numbers: shows values exactly

as entered 1.1, 2.25

Dates and times: default formats DDDD-MM-DD HH:MI:SS

Page 9: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Formatting Retrieved Data Floating point number fields: Use the

FORMAT function

SELECT purch_id, FORMAT(purch_pounds, 2)FROM candy_purchase;

FORMAT(fieldname, decimal_places)

Page 10: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Formatting Number Output as Currency Use the CONCAT and FORMAT functions

together CONCAT joins two strings to create a single string

SELECT prod_id, CONCAT('$', FORMAT(prod_cost, 2))FROM candy_product;

CONCAT('$', FORMAT(fieldname, decimal_places))

Page 11: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Formatting Date Output Use the DATE_FORMAT function

Returns a binary data type, so you have to use the CONVERT function to convert it to a text string

SELECT purch_id, CONVERT(DATE_FORMAT(purch_date, '%b %e, %Y') USING latin1)FROM candy_purchase;

Predefined format specifiers

CONVERT(DATE_FORMAT(fieldname, 'format') USING latin1)

blankspaces

comma%b – abbreviated month name%e – day of the month, numeric, suppresses leading zeroes%Y – year, numeric, 4 digits

Page 12: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Performing Arithmetic Calculations in Queries Applications often perform arithmetic

operations on retrieved dataYou can perform basic arithmetic operations on

numbers and dates in a SQL query SELECT clause

Rationale:DBMS makes it easy to perform the operationNetwork needs to transmit only the data you need

Page 13: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Performing Arithmetic Operations on Number Data Operators: +, -, *, /

Order of evaluation: *, / +, - To force a different order, use parentheses

SELECT prod_desc, prod_price – prod_costFROM candy_product;

Page 14: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Performing Arithmetic Operations on Date Data To retrieve a date that is a specific number

of days from a retrieved date, add/subtract the number of days:

SELECT purch_id, purch_date, purch_date + 2, purch_date – 2FROM candy_purchase;

Page 15: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Performing Arithmetic Operations on Date Data Another way to calculate the number of

days between two known dates is to use DATEDIFF

SELECT purch_id, purch_date, purch_delivery_date, DATEDIFF(purch_delivery_date, purch_date)FROM candy_purchase;

Page 16: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Retrieving the Current Date Use the CURRENT_DATE() function

SELECT CURRENT_DATE();

Page 17: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Calculating someone’s age from their date of birth:

SELECT (DATEDIFF(CURRENT_DATE(), '1986-11-20')) / 365.25;

Page 18: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Formatting Column Names By default:

Column names are database field namesCalculated column names are the formula

Page 19: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Column Aliases Provide an alternate column name Uses:

You can use them in the ORDER BY clause You can reference them in server-side programs

SELECT purch_id, purch_date, purch_delivery_date, DATEDIFF(purch_delivery_date, purch_date) AS delivery_daysFROM candy_purchaseORDER BY delivery_days;

SELECT fieldname AS alias …

Page 20: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

SQL Group Functions Performs an operation on values from a

group of retrieved recordsAVG (average of all retrieved values)COUNT (number of records retrieved)MAX (maximum value retrieved)MIN (minimum value retrieved)SUM (sum of all retrieved values)

Page 21: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

AVG, MAX, MIN, and SUM Examples

SELECT MAX(prod_cost), MIN(prod_cost), AVG(prod_cost), SUM(prod_cost)FROM candy_product;

Page 22: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

COUNT Group Function Displays the number of records that a query will

retrieve Can be used on a column of any data type

Forms: COUNT(*) – displays total number of records,

regardless if the record has fields that contain NULL values

COUNT(fieldname) – displays the number of retrieved records in which the specified field is NOT NULL

Page 23: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

COUNT Function Examples

SELECT COUNT(*)FROM candy_customer;

SELECT COUNT(cust_phone)FROM candy_customer;

Page 24: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Using the GROUP BY Clause Whenever you use a group function:

If any of the columns in the SELECT clause involve a group function, then columns not in group functions must be listed in a GROUP BY clause

SELECT purch_status, MAX(purch_pounds)FROM candy_purchaseGROUP BY purch_status

Page 25: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Using the GROUP BY Clause

Another example:

SELECT purch_date, MAX(purch_pounds), MIN(purch_pounds), AVG(purch_pounds)FROM candy_purchaseGROUP BY purch_date;

Page 26: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Using the HAVING Clause

Sometimes you want to use the result of a group function in a search condition

To do this, use HAVING instead of WHERE:

SELECT prod_id, AVG(purch_pounds)FROM candy_purchaseGROUP BY prod_idHAVING AVG(purch_pounds) > 5;

Page 27: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Using the HAVING Clause NOTE: if you use a group function in the

HAVING clause and retrieve a non-group-function value in the SELECT clause, you must group the output by the non-group-function field:

SELECT prod_idFROM candy_purchaseGROUP BY prod_idHAVING AVG(purch_pounds) > 5

Page 28: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: In which order does the following query retrieve the CUST_ID values?

a. 5, 2, 4, 3, 1b. 5, 2, 3, 4, 1c. 1, 2, 4, 3, 5d. None of the above

SELECT cust_idFROM candy_customerWHERE cust_id <= 5ORDER BY cust_type DESC, cust_name

Page 29: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: In which order does the following query retrieve the CUST_ID values?

a. 5, 2, 4, 3, 1b. 5, 2, 3, 4, 1c. 1, 2, 4, 3, 5d. None of the above

SELECT cust_idFROM candy_customerWHERE cust_id <= 5ORDER BY cust_type DESC, cust_name

Page 30: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: What does the following query retrieve?

a. 3.5b. 2.5c. -2.4d. None of the above

SELECT (purch_id + cust_id)/prod_id – purch_poundsFROM candy_purchaseWHERE purch_id = 1

Page 31: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: What does the following query retrieve?

a. 3.5b. 2.5c. -2.4d. None of the above

SELECT (purch_id + cust_id)/prod_id – purch_poundsFROM candy_purchaseWHERE purch_id = 1

Page 32: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: What does the following query retrieve?

SELECT count(*)FROM candy_purchase;

a. 9b. 14c. 8d. None of the above

Page 33: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: What does the following query retrieve?

SELECT count(*)FROM candy_purchase;

a. 9b. 14c. 8d. None of the above

Page 34: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: How many records will the following query retrieve?

a. 4b. 9c. 14d. None of the above

SELECT purch_delivery_date, SUM(purch_pounds) FROM candy_purchaseGROUP BY purch_delivery_date;

Page 35: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: How many records will the following query retrieve?

a. 4b. 9c. 14d. None of the above

SELECT purch_delivery_date, SUM(purch_pounds) FROM candy_purchaseGROUP BY purch_delivery_date;

Page 36: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: What does the following query retrieve?

SELECT count(purch_delivery_date)FROM candy_purchase;

a. 1b. 10c. 9d. None of the above

Page 37: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Test Yourself: What does the following query retrieve?

SELECT count(purch_delivery_date)FROM candy_purchase;

a. 1b. 10c. 9d. None of the above

Page 38: Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,

Your Turn: Create a new MySQL script file, then create the following queries:

1.Retrieve the purchase ID, purchase date, delivery date, and pounds of all purchases that have been delivered (delivery date is not NULL). Sort the output first by delivery date (ascending) and then by pounds (descending).

2.Retrieve the CUST_ID of every customer who has made a purchase. Do not display duplicate ID values.

3.Retrieve the purchase ID and the number of days between the purchase date and current system date for every purchase.

4.Retrieve the purchase ID, purchase date, and delivery date for every order. Display the dates in numeric ‘MM.DD.YYYY’ format (for example 10.06.2007). Create descriptive column aliases of your choice for the outputs.

5.Retrieve the purchase ID, status, and sum of the total pounds of each purchase. Sort the output by the status values.