Top Banner
Advanced SELECT Queries CS 146
27

Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Jan 05, 2016

Download

Documents

Dwight Miller
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Advanced SELECT Queries

CS 146

Page 2: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Review: Retrieving Data From a Single Table Syntax:

Limitation: Retrieves "raw" data Note the default formats…

SELECT column1, column2, …FROM tablenameWHERE search_condition(s)

Page 3: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

We can use the DBMS to manipulate retrieved data! Suppress duplicates Sort Format characters, numbers, & dates Perform arithmetic operations Summarize groups of data

Why not just do it in your program?

Page 4: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Suppressing Duplicate Outputs Use the DISTINCT qualifier

Ensures that only distinct rows are returned

SELECT DISTINCT cust_zipFROM candy_customer;

Page 5: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Sorting Query Output

Use the ORDER BY clause:

Always appears as the last item in a SELECT query

SELECT SELECT custnamecustnameFROM FROM customercustomerWHERE WHERE cust_type = 'P'cust_type = 'P'ORDER BY cust_nameORDER BY cust_name;;

Page 6: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Sorting Query Output Default sort order is ascending

Numbers: smallest to largest Characters: alphabetical Dates: 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: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Multiple Sort Keys You can sort output by multiple keys

Only makes sense when first sort key has repeating values…

SELECT purch_id, purch_dateFROM candy_purchaseORDER BY purch_date DESC, purch_id

Page 8: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Formatting Number Output Use the FORMAT function Format:FORMAT(number, decimal_places)

SELECT purch_id,FORMAT(pounds, 2)

FROM candy_purchase;

Page 9: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Formatting Number Output as Currency Use the CONCAT and FORMAT function

CONCAT joins two strings to create a single string

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

SELECT prod_id,CONCAT('$', FORMAT(prod_cost, 2))

FROM candy_product;

Page 10: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Formatting Date Output Use the DATE_FORMAT function Format:DATE_FORMAT(date, 'format')

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

Predefined format specifiers

Page 11: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Format Specifiers %b – abbreviated month name %e – day of the month, numeric, suppresses

leading zeroes %Y – year, numeric, 4 digits

More complete list of specifiers

Page 12: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Formatting Character Output MySQL has a variety of functions for

manipulating stringsFunction Description Example Query

CONCAT(<string1>, <string2>)

Concatenates (joins) two strings

SELECT CONCAT(cust_addr, cust_zip)FROM candy_customer;

UPPER(<string>), LOWER(<string>)

Returns the string, with all characters converted to upper/lower case

SELECT UPPER(username)FROM candy_customer;

LENGTH(<string>) Returns an integer representing the string length

SELECT LENGTH(password)FROM candy_customer;

LPAD(<string>, <number of characters to add>, <padding character>), RPAD(<string>, <total length of return value>, <padding character>)

Returns the value of the string, with sufficient padding characters added to the left/right edge so return value equals total length specified

SELECT LPAD(password, 8, '*')FROM candy_customer;

Page 13: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Default Query Output

Column names are database field names

Calculated column names are the formula

Page 14: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Column Aliases Provide an alternate column name What good are they?

You can use them in the ORDER BY clause You can reference them in embedded programs

NOTE: alias only has to be in single quotes if it contains blank spaces

SELECT LENGTH(cust_name) AS 'name length'FROM candy_customerORDER BY 'name length';

Page 15: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Performing Arithmetic Calculations in Queries Applications often perform arithmetic

operations on retrieved data You can perform basic arithmetic operations on

numbers and dates in a SQL query SELECT clause Rationale:

DBMS makes it easy to perform the operation Network needs to transmit only the data you need

Page 16: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

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

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

Only use on number data Prices, quantities, etc.

Page 17: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Performing Arithmetic Operations on Number Data Example:

SELECT prod_desc, prod_price - prod_costFROM candy_product;

Page 18: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

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

days after/before a stored date, add/subtract the number of days:

SELECT purch_id, purch_date, purch_date + 2FROM candy_purchase;

SELECT purch_id, purch_date, purch_date - 2FROM candy_purchase;

Page 19: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Performing Arithmetic Operations on Date Data To calculate the number of days between two

known dates, use DATEDIFF

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

Page 20: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Retrieving the Current Date Use the CURRENT_DATE() function

Function: code retrieving information that acts like a column in a SQL command

SELECT CURRENT_DATE();

Page 21: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Another Date Calculation Calculating someone’s age from their date of

birth

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

Page 22: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

SQL Group Functions Performs an operation on a field from a group

of retrieved records AVG (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 23: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

SQL Group Functions Examples

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

SELECT COUNT(*)FROM candy_customer;

Page 24: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

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

All of the columns in the select clause must be in a group function or

If not, the column must be listed in a GROUP BY clause

Page 25: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

Using the GROUP BY Clause Example:

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

Page 26: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

SUM and Statistical Functions SUM, AVG, MAX, MIN

Can only be used with NUMBER columns

SUM(pounds)

MAX(prod_cost)

MIN(prod_cost)

AVG(prod_cost)

Page 27: Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.

COUNT 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