single-table queries 2: advanced topics cs 320. review: retrieving data from a single table syntax:...
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
Single-Table Queries 2: Advanced TopicsCS 320
Review: Retrieving Data From a Single Table Syntax:
Limitation: Retrieves "raw" data
SELECT field1, field2, …FROM tablenameWHERE search_condition(s)
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?
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);
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;
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
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
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
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)
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))
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
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
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;
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;
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;
Retrieving the Current Date Use the CURRENT_DATE() function
SELECT CURRENT_DATE();
Calculating someone’s age from their date of birth:
SELECT (DATEDIFF(CURRENT_DATE(), '1986-11-20')) / 365.25;
Formatting Column Names By default:
Column names are database field namesCalculated column names are the formula
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 …
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)
AVG, MAX, MIN, and SUM Examples
SELECT MAX(prod_cost), MIN(prod_cost), AVG(prod_cost), SUM(prod_cost)FROM candy_product;
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
COUNT Function Examples
SELECT COUNT(*)FROM candy_customer;
SELECT COUNT(cust_phone)FROM candy_customer;
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
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;
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;
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
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
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
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
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
Test Yourself: What does the following query retrieve?
SELECT count(*)FROM candy_purchase;
a. 9b. 14c. 8d. None of the above
Test Yourself: What does the following query retrieve?
SELECT count(*)FROM candy_purchase;
a. 9b. 14c. 8d. None of the above
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;
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;
Test Yourself: What does the following query retrieve?
SELECT count(purch_delivery_date)FROM candy_purchase;
a. 1b. 10c. 9d. None of the above
Test Yourself: What does the following query retrieve?
SELECT count(purch_delivery_date)FROM candy_purchase;
a. 1b. 10c. 9d. None of the above
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.