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

Slides:



Advertisements
Similar presentations
Chapter 11 Group Functions
Advertisements

Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320.
Action Queries CS 320. Review: SQL Command Types  Data Definition Language (DDL)  Used to create and modify database objects  Data Manipulation Language.
Introduction to Structured Query Language (SQL)
A Guide to Oracle9i1 Using SQL Queries to Insert, Update, Delete, and View Data Chapter 3.
Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data
Structured Query Language Part I Chapter Three CIS 218.
Introduction to Structured Query Language (SQL)
Creating Database Tables CS 320. Review: Levels of data models 1. Conceptual: describes WHAT data the system contains 2. Logical: describes HOW the database.
Databases Tutorial 2 Further Select Statements. Objectives for Week Data types Sort retrieved data Formatting output.
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Microsoft Access 2010 Chapter 7 Using SQL.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Tutorial 5: Working with Excel Tables, PivotTables, and PivotCharts
Guide to Oracle10G1 Using SQL Queries to Insert, Update, Delete, and View Data Chapter 3.
Using SQL Queries to Insert, Update, Delete, and View Data Date Retrieval from a single table & Calculations © Abdou Illia MIS Spring 2015.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 3 Single-Table Queries
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Single-Table Queries 1: Basics CS 320 Online. Review: SQL Command Types  Data Definition Language (DDL)  Used to create and modify database objects.
Using Special Operators (LIKE and IN)
ADVANCED SQL SELECT QUERIES CS 260 Database Systems.
SQL SELECT QUERIES CS 260 Database Systems. Overview  Introduction to SQL  Single-table select queries  Using the DBMS to manipulate data output 
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Copyright 2008 McGraw-Hill Ryerson 1 TECHNOLOGY PLUG-IN T7 PROBLEM SOLVING USING ACCESS.
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
Introduction to Databases Queries CS 146. Sample Database: CANDY_CUSTOMER CANDY_PURCHASE CANDY_CUST_TYPE CANDY_PRODUCT.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
Multiple Table Queries 1: Inner Joins CS 320. Introduction: Join Queries Usually queries combine data from multiple tables:  List how much (pounds) of.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
1 Creating and Maintaining Database Objects Part 1 Database Systems.
SQL ACTION QUERIES AND TRANSACTION CONTROL CS 260 Database Systems.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
Structured Query Language SQL Unit 2 An Introduction to Organizing and Retrieving Data with SQL.
Chapter 14 Formatting Readable Output. Chapter Objectives  Add a column heading with a line break to a report  Format the appearance of numeric data.
T7-1 LEARNING OUTCOMES – ACCESS PROBLEM SOLVING 1.Describe the process of using the Simple Query Wizard using Access 2.Describe the process of using the.
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
SQL: Single Table Queries SELECT FROM WHERE ORDER D. Christozov / G.Tuparov INF 280 Database Systems: Single Table Queries 1.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Lecture3b - Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data Guide to Oracle 10g ITBIS373 Database Development.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
Join Queries CS 146. Introduction: Join Queries  So far, our SELECT queries have retrieved data from a single table  Usually queries combine data from.
1 Copyright © 2007, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
Database Design lecture 3_2 Slide 1 Database Design Lecture 3_2 Data Manipulation in SQL Simple SQL queries References: Text Chapter 8 Oracle SQL Manual.
Introduction to Databases Queries CS 146. Sample Database: CANDY_CUSTOMER CANDY_PURCHASE CANDY_CUST_TYPE CANDY_PRODUCT.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
SQL Query Getting to the data ……..
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Writing Basic SQL SELECT Statements
Basic select statement
Writing Basic SQL SELECT Statements
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
SQL – Entire Select.
Chapter 4 Summary Query.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Access: SQL Participation Project
Writing Basic SQL SELECT Statements
Reporting Aggregated Data Using the Group Functions
Query Functions.
Section 4 - Sorting/Functions
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

Single-Table Queries 2: Advanced Topics CS 320

Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2, … FROM tablename WHERE 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_zip FROM candy_customer; SELECT DISTINCT fieldname FROM tablename WHERE 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 tablename WHERE search_condition(s) ORDER BY field_a; SELECT cust_id, cust_phone FROM candy_customer WHERE cust_type = 'P' ORDER BY cust_name;

Sort Order 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_date FROM candy_purchase ORDER 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_date FROM candy_purchase ORDER 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) blank spaces 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 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

Performing Arithmetic Operations on Number Data Operators: +, -, *, /  Order of evaluation: *, / +, - To force a different order, use parentheses SELECT prod_desc, prod_price – prod_cost FROM 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 – 2 FROM 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(), ' ')) / ;

Formatting Column Names By default:  Column names are database field names  Calculated 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_days FROM candy_purchase ORDER BY delivery_days; SELECT fieldname AS alias …

SQL Group Functions Performs an operation on values 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)

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_purchase GROUP BY purch_status

Using the GROUP BY Clause Another example: SELECT purch_date, MAX(purch_pounds), MIN(purch_pounds), AVG(purch_pounds) FROM candy_purchase GROUP 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_purchase GROUP BY prod_id HAVING 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_id FROM candy_purchase GROUP BY prod_id HAVING AVG(purch_pounds) > 5

Test Yourself: In which order does the following query retrieve the CUST_ID values? a. 5, 2, 4, 3, 1 b. 5, 2, 3, 4, 1 c. 1, 2, 4, 3, 5 d. None of the above SELECT cust_id FROM candy_customer WHERE cust_id <= 5 ORDER 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, 1 b. 5, 2, 3, 4, 1 c. 1, 2, 4, 3, 5 d. None of the above SELECT cust_id FROM candy_customer WHERE cust_id <= 5 ORDER BY cust_type DESC, cust_name

Test Yourself: What does the following query retrieve? a. 3.5 b. 2.5 c d. None of the above SELECT (purch_id + cust_id)/prod_id – purch_pounds FROM candy_purchase WHERE purch_id = 1

Test Yourself: What does the following query retrieve? a. 3.5 b. 2.5 c d. None of the above SELECT (purch_id + cust_id)/prod_id – purch_pounds FROM candy_purchase WHERE purch_id = 1

Test Yourself: What does the following query retrieve? SELECT count(*) FROM candy_purchase; a. 9 b. 14 c. 8 d. None of the above

Test Yourself: What does the following query retrieve? SELECT count(*) FROM candy_purchase; a. 9 b. 14 c. 8 d. None of the above

Test Yourself: How many records will the following query retrieve? a. 4 b. 9 c. 14 d. None of the above SELECT purch_delivery_date, SUM(purch_pounds) FROM candy_purchase GROUP BY purch_delivery_date;

Test Yourself: How many records will the following query retrieve? a. 4 b. 9 c. 14 d. None of the above SELECT purch_delivery_date, SUM(purch_pounds) FROM candy_purchase GROUP BY purch_delivery_date;

Test Yourself: What does the following query retrieve? SELECT count(purch_delivery_date) FROM candy_purchase; a. 1 b. 10 c. 9 d. None of the above

Test Yourself: What does the following query retrieve? SELECT count(purch_delivery_date) FROM candy_purchase; a. 1 b. 10 c. 9 d. 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 ). 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.