Copyright © 2003-2008 Curt Hill Queries in SQL More options.

Slides:



Advertisements
Similar presentations
1 Query-by-Example (QBE). 2 v A “GUI” for expressing queries. –Based on the Domain Relational Calulus (DRC)! –Actually invented before GUIs. –Very convenient.
Advertisements

Database Management Systems 3ed, Online chapter, R. Ramakrishnan and J. Gehrke1 Query-by-Example (QBE) Online Chapter Example is the school of mankind,
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Query-by-Example (QBE) Chapter 6 Example is the school of mankind, and they will learn at no.
4 Copyright © 2004, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions.
5 Copyright © 2007, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions.
4 การใช้ SQL Functions. Copyright © 2007, Oracle. All rights reserved What Are Group Functions? Group functions operate on sets of rows to give.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Structured Query Language – Continued Rose-Hulman Institute of Technology Curt Clifton.
Temple University – CIS Dept. CIS331– Principles of Database Systems V. Megalooikonomou Query by example (based on notes by Silberchatz,Korth, and Sudarshan.
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.
Computer Science 101 Web Access to Databases SQL – Extended Form.
Sorting data and Other selection Techniques Ordering data results Allows us to view our data in a more meaningful way. Rather than just a list of raw.
Chapter 3 Single-Table Queries
Copyright © Curt Hill Index Creation SQL.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
SQL (Chapter 2: Simple queries; Chapter 7 and 8: Nested and DML queries) Many of the examples in this document are based on the tables in the next slide.
INLS 623– S QL Instructor: Jason Carter. SQL SELECT DISTINCT SELECT DISTINCT column_name, column_name FROM table_name ;
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
4 Copyright © 2004, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions.
1 TAC2000/ Protocol Engineering and Application Research Laboratory (PEARL) Structured Query Language Introduction to SQL Structured Query Language.
Copyright © Curt Hill Query Evaluation Translating a query into action.
Instructor: Jinze Liu Fall Basic Components (2) Relational Database Web-Interface Done before mid-term Must-Have Components (2) Security: access.
Using Special Operators (LIKE and IN)
Copyright Curt Hill SQL Queries Yet Another Set of Query Features.
©Silberschatz, Korth and Sudarshan5.1Database System Concepts Chapter 5: Other Relational Languages Query-by-Example (QBE)
Copyright © Curt Hill Joins Revisited What is there beyond Natural Joins?
INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS Dr. Adam Anthony Fall 2012.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Source: Database System Concepts, Silberschatz etc Edited: Wei-Pang Yang, IM.NDHU, Introduction to Database CHAPTER 5 Other Relational Languages.
1 Querying a Single Table Structured Query Language (SQL) - Part II.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Copyright 2003 Curt Hill Queries in SQL Syntax and semantics.
SQL Aggregation Oracle and ANSI Standard SQL Lecture 9.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Query Processing – Implementing Set Operations and Joins Chap. 19.
MIS2502: Data Analytics SQL – Getting Information Out of a Database.
SQL queries ordering and grouping. SWC – SQL query - ordering In a query producing a large result, it may be beneficial to order the result SQL.
Sorting data and Other selection Techniques Ordering data results Allows us to view our data in a more meaningful way. Rather than just a list of raw.
Aggregating Data Using Group Functions. What Are Group Functions? Group functions operate on sets of rows to give one result per group.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
Copyright © Curt Hill SQL The Data Manipulation Language.
Computer Science & Engineering 2111 Inner Joins and Advanced Queries 1CSE 2111 Lecture-Advanced Queries.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
More SQL: Complex Queries,
Aggregating Data Using Group Functions
Query-by-Example (QBE)
The Database Exercises Fall, 2009.
Aggregating Data Using Group Functions
(SQL) Aggregating Data Using Group Functions
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
SQL – Entire Select.
Chapter 4 Summary Query.
Aggregating Data Using Group Functions
Access: SQL Participation Project
CS4222 Principles of Database System
Reporting Aggregated Data Using the Group Functions
Section 4 - Sorting/Functions
Projecting output in MySql
Reporting Aggregated Data Using the Group Functions
Reporting Aggregated Data Using the Group Functions
分组函数 Schedule: Timing Topic 35 minutes Lecture 40 minutes Practice
Aggregating Data Using Group Functions
Join Implementation How is it done? Copyright © Curt Hill.
Presentation transcript:

Copyright © Curt Hill Queries in SQL More options

Copyright © Curt Hill Duplicates A select usually joins several tables creating large unique tuples Temporary table has an unspecified key If the select removes portions of the key, then duplicates can occur Consider the query that links faculty to the students taking any of their classes

The query SELECT f_name, s_name FROM faculty, c_teach, students, grades WHERE f_naid = ct_naid AND ct_dept = g_dept AND ct_number = g_course AND s_id = g_naid This produces 238 rows What is the key? Copyright © Curt Hill

The Key Does not need to be specified In this case it is the linking fields –F_naid (or ct_naid) –Ct_dept –Ct_number –S_id Since some of these fields will be removed by the Select duplicates occur Copyright © Curt Hill

Removing duplicates In this query duplicates occurs when a student takes multiple classes from the teacher The result is not a set (which eliminates duplicates) but a multi-set (which allows duplicates) Placing the reserved word DISTINCT immediately after the Select removes these The new query follows: Copyright © Curt Hill

Revised query SELECT DISTINCT f_name, s_name FROM faculty, c_teach, students, grades WHERE f_naid = ct_naid AND ct_dept = g_dept AND ct_number = g_course AND s_id = g_naid This produces 213 rows Copyright © Curt Hill

How does this work? Removing duplicates is not trivial There are several ways, but all are work One possibility is to sort the tuples –Duplicates then must be adjacent Another is to hash them –Duplicates have the same key Small queries could be done in memory, larger ones cannot We will consider sorting and hashing later Copyright © Curt Hill

Deception The difference between the two queries is just one keyword That keyword forces the DBMS to do substantial extra work Looks like no big deal but actually is Hence the query is deceptively different However, make the database do its job Copyright © Curt Hill

All The opposite of the Distinct is the All Specifies that duplicates should not be eliminated Since elimination is expensive, it is usually not done –Thus All gives same result whether present or absent

Order The order of the output table is dependent on many unpredictable things Different DBMSs may give different orderings, even with same data –Based on how they process the data The order of the above queries is different on Oracle and MySQL Worse yet neither will put all the students from one faculty together Copyright © Curt Hill

Order by clause Order by follows the Where It specifies a sort order for the output May specify one or more fields Fields do not have to be displayed

Sorted query 1 SELECT DISTINCT f_name, s_name FROM faculty, c_teach, students, grades WHERE f_naid = ct_naid AND ct_dept = g_dept AND ct_number = g_course AND s_id = g_naid ORDER BY f_name, S_name Copyright © Curt Hill

Sorting The default behavior is to sort: –Case sensitive way –Ascending order (lowest to highest) Usually we sort on the display values –Oracle only allows this –SQL Server and MySQL allow sorts on other fields Copyright © Curt Hill

Sorted query 2 SELECT DISTINCT f_name, s_name FROM faculty, c_teach, students, grades WHERE f_naid = ct_naid AND ct_dept = g_dept AND ct_number = g_course AND s_id = g_naid ORDER BY f_naid, S_id Copyright © Curt Hill

Sort Order The default is sort in ascending order for all sort keys The key may be followed by ASC or DESC ASC makes ascending order DESC is descending order These may not be spelled out If left out ASC is default Copyright © Curt Hill

Sorted query 3 SELECT DISTINCT f_name, s_name FROM faculty, c_teach, students, grades WHERE f_naid = ct_naid AND ct_dept = g_dept AND ct_number = g_course AND s_id = g_naid ORDER BY f_name DESC, s_name ASC Copyright © Curt Hill

Aggregate operations We can collapse several rows into one This produces a summary report Several rows of table become one row of output This requires the Group By clause with Aggregate functions The Group By follows Where Aggregate functions are in Select Copyright © Curt Hill

Group By and Aggregate functions Each of these Aggregate functions specify a field: –Count –Avg –Sum –Max –Min Usually used with Group by but not always Group by follows Where Specifies the groups as changes in fields Copyright © Curt Hill

Grouped Query 1 SELECT f_name, count(s_name) FROM faculty, c_teach, students, grades WHERE f_naid = ct_naid AND ct_dept = g_dept AND ct_number = g_course AND s_id = g_naid GROUP BY f_name This produces 16 rows Copyright © Curt Hill

Commentary Group by forces a sort This is only means to ensure that the items are together The DISTINCT keyword may be used within aggregate functions: –Count –Avg –Sum

Grouped Query 2 SELECT f_name, count(DISTINCT s_name) FROM faculty, c_teach, students, grades WHERE f_naid = ct_naid AND ct_dept = g_dept AND ct_number = g_course AND s_id = g_naid GROUP BY f_name This produces 16 rows but different counts Copyright © Curt Hill

Secondary Selection The Where does an initial selection –It eliminates numerous combinations of tuples of no interest We may also wish to remove aggregated rows This must occur after the Where but before final table This is done with the HAVING clause of the GROUP BY

Having The Having clause follows the Group By fields It gives a selection criteria for rows Usually based upon the aggregate functions Form: Having comparison See following Copyright © Curt Hill

Grouped Query 3 SELECT f_name, count(DISTINCT s_name) FROM faculty, c_teach, students, grades WHERE f_naid = ct_naid AND ct_dept = g_dept AND ct_number = g_course AND s_id = g_naid GROUP BY f_name HAVING count(*)>10 Copyright © Curt Hill

Commentary This produces 9 rows Notice the * is the parameter of count Other Aggregate functions could be used as well A Having without a Group By is like a Where Copyright © Curt Hill

Ungrouped Query Suppose we just want a count or sum Then we can use an aggregate function without Group By This will generally collapse the entire table into a single row Consider the next screen Copyright © Curt Hill

Aggregates Counting rows: Select count(*) from faculty –Results in one row with count of 19 Sum of student balances: Select sum(s_balance) from students –Results in one row with the sum: Copyright © Curt Hill

Variations Recall this query SELECT f_name, count(DISTINCT s_name) … GROUP BY f_name Suppose f_naid were included in the Select SELECT f_name, f_naid, In Oracle and SQL Server it would also have to be part of the Group By –But not in MySQL Copyright © Curt Hill

Bad Oracle Query SELECT f_name, f_naid, count(DISTINCT s_name) FROM faculty, c_teach, students, grades WHERE f_naid = ct_naid AND ct_dept = g_dept AND ct_number = g_course AND s_id = g_naid GROUP BY f_name –Receives an error: ORA-00979: not a GROUP BY expression Copyright © Curt Hill