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

Slides:



Advertisements
Similar presentations
Concepts of Database Management Seventh Edition
Advertisements

Concepts of Database Management Sixth Edition
Chapter 11 Group Functions
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)
Introduction to Structured Query Language (SQL)
Introduction to Oracle9i: SQL1 SQL Group Functions.
Introduction to Oracle9i: SQL1 Selected Single-Row Functions.
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
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.
Concepts of Database Management, Fifth Edition
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 6 Group Functions. Chapter Objectives  Differentiate between single-row and multiple-row functions  Use the SUM and AVG functions for numeric.
Chapter 3 Single-Table Queries
Chapter 5 Selected Single-Row Functions. Chapter Objectives  Use the UPPER, LOWER, and INITCAP functions to change the case of field values and character.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Concepts of Database Management Seventh Edition
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.
Oracle 11g: SQL Chapter 10 Selected Single-Row Functions.
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.
In this session, you will learn to: Use functions to customize the result set Summarize and group data Objectives.
IFS Intro to Data Management Chapter 5 Getting More Than Simple Columns.
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.
Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join.
1 Creating and Maintaining Database Objects Part 1 Database Systems.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,
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.
Introduction to Databases Queries CS 146. Sample Database: CANDY_CUSTOMER CANDY_PURCHASE CANDY_CUST_TYPE CANDY_PRODUCT.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
1 ORACLE I 3 – SQL 1 Salim Phone: YM: talim_bansal.
SQL Query Getting to the data ……..
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Writing Basic SQL SELECT Statements
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
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Access: SQL Participation Project
Section 4 - Sorting/Functions
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

Advanced SELECT Queries CS 146

Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT column1, column2, … FROM tablename WHERE search_condition(s)

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?

Suppressing Duplicate Outputs  Use the DISTINCT qualifier  Ensures that only distinct rows are returned SELECT DISTINCT cust_zip FROM candy_customer;

Sorting Query Output Use the ORDER BY clause: Always appears as the last item in a SELECT query SELECT custname FROM customer WHERE cust_type = 'P' ORDER BY cust_name;

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_date FROM candy_purchase ORDER BY purch_date DESC

Multiple Sort Keys  You can sort output by multiple keys  Only makes sense when first sort key has repeating values… SELECT purch_id, purch_date FROM candy_purchase ORDER BY purch_date DESC, purch_id

Formatting Number Output  Use the FORMAT function  Format: FORMAT(number, decimal_places) SELECT purch_id, FORMAT(pounds, 2) FROM candy_purchase;

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;

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

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 More complete list of specifiers

Formatting Character Output  MySQL has a variety of functions for manipulating strings FunctionDescriptionExample Query CONCAT(, )Concatenates (joins) two strings SELECT CONCAT(cust_addr, cust_zip) FROM candy_customer; UPPER( ), LOWER( ) Returns the string, with all characters converted to upper/lower case SELECT UPPER(username) FROM candy_customer; LENGTH( )Returns an integer representing the string length SELECT LENGTH(password) FROM candy_customer; LPAD(,, ), RPAD(,, ) 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;

Default Query Output  Column names are database field names  Calculated column names are the formula

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_customer ORDER BY 'name length';

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:  * / then + -  To force a different order, use parentheses  Only use on number data  Prices, quantities, etc.

Performing Arithmetic Operations on Number Data  Example: SELECT prod_desc, prod_price - prod_cost FROM candy_product;

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 + 2 FROM candy_purchase; SELECT purch_id, purch_date, purch_date - 2 FROM candy_purchase;

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;

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();

Another Date Calculation  Calculating someone’s age from their date of birth SELECT (DATEDIFF(CURRENT_DATE(), ' ')) / ;

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)

SQL Group Functions  Examples SELECT MAX(prod_cost), MIN(prod_cost), AVG(prod_cost) FROM candy_product; SELECT COUNT(*) FROM candy_customer;

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

Using the GROUP BY Clause  Example: SELECT purch_date, MAX(pounds), MIN(pounds), AVG(pounds) FROM candy_purchase GROUP BY purch_date;

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)

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