SQL queries ordering and grouping. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result SQL.

Slides:



Advertisements
Similar presentations
Database Queries and Structured Query Language (SQL) J.G. Zheng May 16 th 2008.
Advertisements

Microsoft Excel Working with Excel Lists, Subtotals and Pivot Tables.
1 CSE Students: Please do not log in yet. Check-in with Brian in the back. Review Days 3 and 4 in the book. Others: Please save your work and logout.
Querying a Database Using the Select Query Window
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 6: Set Functions.
Mary K. Olson PS Reporting Instance – Query Tool 101.
Concepts of Database Management Sixth Edition
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.
CORE 2: Information systems and Databases STORAGE & RETRIEVAL 2 : SEARCHING, SELECTING & SORTING.
Computer Science 101 Web Access to Databases SQL – Extended Form.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Download three SQL script files from wiki page.
Xin  Syntax ◦ SELECT field1 AS title1, field2 AS title2,... ◦ FROM table1, table2 ◦ WHERE conditions  Make a query that returns all records.
Chapter 3 Single-Table Queries
With Microsoft Office 2007 Introductory© 2008 Pearson Prentice Hall1 PowerPoint Presentation to Accompany GO! with Microsoft ® Office 2007 Introductory.
CS&E 1111 AcQueries Querying in Access Sorting data Aggregating Data Performing Calculations Objectives: Learn how to use the Access Query Design Tool.
Practical Session 13 Structured Data Bases Structured Query Language Exam Questions Factory Method Pattern Abstract Factory Pattern.
Copyright 2007, Paradigm Publishing Inc. ACCESS 2007 Chapter 4 BACKNEXTEND 4-1 LINKS TO OBJECTIVES Query Design Query Criteria Modify a Query Using OR.
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,
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
Database Systems Microsoft Access Practical #3 Queries Nos 215.
Querying a Database - A question or an inquiry (dictionary.com) - WHAT ARE WE ASKING QUESTIONS ABOUT? THE DATA - BY ASKING QUESTIONS OF THE DATA WE OBTAIN?
JDBC Java and Databases. RHS – SOC 2 JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
SQL queries subqueries and joining. RHS – SOC 2 SQL query – beyond one table So far, we have only applied queries to a single table It is possible – and.
SQL queries ordering and grouping and joins
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Select your database – Your database name is.
Course ILT Forms and queries Unit objectives Create forms by using AutoForm and the Form Wizard, and add or modify form headers and footers Open and enter.
Pasewark & Pasewark 1 Access Lesson 3 Creating Queries Microsoft Office 2007: Introductory.
Database Applications – Microsoft Access Lesson 4 Working with Queries 36 Slides in Presentation.
Nikolay Kostov Telerik Corporation
SQL queries basics. RHS – SOC 2 SQL query An SQL query is an SQL statement, which specifies a subset of the data in the database A subset in terms of.
Copyright © Curt Hill Queries in SQL More options.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
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.
SQL queries Data Maintenance. RHS – SOC 2 Data maintenance In addition to asking question to the database (queries), we can also maintain the data itself.
Databases Competency Explain advanced database concepts and functions.
Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,
Structured Query Language SQL Unit 4 Solving Problems with SQL.
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.
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.
Aggregating Data Using Group Functions. What Are Group Functions? Group functions operate on sets of rows to give one result per group.
Practical Session 13 Factory Method Pattern Abstract Factory Pattern Structured Data Bases Structured Query Language Exam Questions.
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.
Paul A. Harris, Ph.D. Director, GCRC Informatics How to use query function in Microsoft Access.
Structured Query Language SQL-II IST 210 Organization of Data IST2101.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
Relational Databases Today we will look at: Different ways of searching a database Creating queries Aggregate Queries More complex queries involving different.
Structured Query Language used for defining and manipulating data in Relational DBs aimed at: –reducing training costs –increasing productivity –improve.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Querying in Access Objectives: Learn how to use the Access Query Design Tool manipulate data in Access: Sorting data Aggregating Data Performing Calculations.
The Database Exercises Fall, 2009.
Q or R Contains a new field called Total Sales which is calculated at run-time. In this field you will multiply the Price by the Sold field Has the Total.
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
CIS16 Application Programming with Visual Basic
SQL – Entire Select.
Chapter 4 Summary Query.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Access: SQL Participation Project
CS4222 Principles of Database System
M1G Introduction to Database Development
Section 4 - Sorting/Functions
Projecting output in MySql
Presentation transcript:

SQL queries ordering and grouping

RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result SQL allows us to order the result by any of the fields in the result We use the keyword ORDER BY

RHS – SOC 3 SQL query - ordering SELECT FROM WHERE ORDER BY Which fields do I want From what table do I want the fields What conditions must the fields fulfill What order are the results sorted in

RHS – SOC 4 SQL query - ordering We use a movie information database as example Movie movieid title country prodyear genre oscars Actor actorid name country birth living oscars Casting movieid actorid

RHS – SOC 5 SQL query - ordering movieidtitlecountryprodyeargenreoscars 1E.T.USA1982Sci-Fi4 2TaxiFrance1998Comedy0 3HungerDenmark1966Drama1 4LeonFrance1994Thriller0 5Hard BoiledHK1992Action UK1984Sci-Fi2 7SevenUSA1995Thriller1 SELECT * FROM Movie ORDER BY title

RHS – SOC 6 SQL query - ordering movieidtitlecountryprodyeargenreoscars 61984UK1984Sci-Fi2 1E.T.USA1982Sci-Fi4 5Hard BoiledHK1992Action0 3HungerDenmark1966Drama1 4LeonFrance1994Thriller0 7SevenUSA1995Thriller1 2TaxiFrance1998Comedy0 SELECT * FROM Movie ORDER BY title

RHS – SOC 7 SQL query - ordering movieidtitlecountryprodyeargenreoscars 1E.T.USA1982Sci-Fi4 2TaxiFrance1998Comedy0 3HungerDenmark1966Drama1 4LeonFrance1994Thriller0 5Hard BoiledHK1992Action UK1984Sci-Fi2 7SevenUSA1995Thriller1 SELECT title, prodyear FROM Movie WHEREoscars > 0 ORDER BY title

RHS – SOC 8 SQL query - ordering movieidtitlecountryprodyeargenreoscars 1E.T.USA1982Sci-Fi4 2TaxiFrance1998Comedy0 3HungerDenmark1966Drama1 4LeonFrance1994Thriller0 5Hard BoiledHK1992Action UK1984Sci-Fi2 7SevenUSA1995Thriller1 SELECT title, prodyear FROM Movie WHEREoscars > 0 ORDER BY title

RHS – SOC 9 SQL query - ordering titleprodyear 1984 E.T.1982 Hunger1966 Seven1995 SELECT title, prodyear FROM Movie WHEREoscars > 0 ORDER BY title

RHS – SOC 10 SQL query - ordering We can even specifiy more than one field for ordering – secondary fields used if primary fields are identical We can choose between descending and ascending order, using the keywords DESC and ASC, respectively ORDER BY oscars DESC, prodyear ASC

RHS – SOC 11 SQL query - functions We can even do some (simple) arithmetic in SQL, using a basic set of functions –COUNT –SUM –AVG –MIN –MAX These are called aggregate functions

RHS – SOC 12 SQL query - functions A aggregate function works on the values of a specific field (column) The set of values is determined by the search conditions SELECT COUNT(title) FROM Movie WHERE (oscars > 0) How many movies have won an Oscar

RHS – SOC 13 SQL query - functions This query can also be written as SELECT COUNT(title) AS OscarWinners FROM Movie WHERE (oscars > 0) The AS keyword allows us to rename a column in the search result Only cosmetic, but useful… NB!

RHS – SOC 14 SQL query - functions SELECTCOUNT(title) AS OscarWinners, AVG(oscars) AS averageOscars, MAX(oscars) AS maximalOscars FROMMovie WHERE(oscars > 0)

RHS – SOC 15 SQL query - functions OscarWinnersaverageOscarsmaximalOscars

RHS – SOC 16 Exercise 4 – SQL queries Use the MovieInformation database, defined in exercise 1 With the data in place, run the below queries on the database –SELECT * FROM Movie ORDER BY prodyear ASC –SELECT title, prodyear FROM Movie ORDER BY title –SELECT MAX(prodyear) AS maxUSA FROM Movie WHERE country = ’USA’ –SELECT AVG(prodyear) AS loserYear FROM Movie WHERE (oscars = 0) Now formulate queries yourself, in order to retrieve the below data: –Get all oscar-winning movies ordered by year (oldest movie first) –Get a sorted list of movie title for movies made in France –Get the year for the oldest movie not winning any Oscars –Get the average number of Oscars for Sci-Fi movies –Get the total number of Oscars won by movies from USA

RHS – SOC 17 SQL query - grouping The aggregate functions are good for calculating properties for the entire result of the search We may sometimes wish to find proper- ties for a certain group within the result This can be done using WHERE… …but can be cumbersome if the groups are very numerous

RHS – SOC 18 SQL query - grouping Suppose we have a full movie database, with movies for more than 100 countries ”Find the total number of movies made in each country” SELECT COUNT(title) AS MovieCount FROM Movies WHERE country = ’…’ More than 100 queries…

RHS – SOC 19 SQL query - grouping A much easier way is to use GROUP BY Syntax: SELECT FROM GROUP BY Produces a result for each group, specified in the field list

RHS – SOC 20 SQL query - grouping movieidtitlecountryprodyeargenreoscars 1E.T.USA1982Sci-Fi4 2TaxiFrance1998Comedy0 3HungerDenmark1966Drama1 4LeonFrance1994Thriller0 5Hard BoiledHK1992Action UK1984Sci-Fi2 7SevenUSA1995Thriller1 SELECT country, COUNT(title) AS MovieCount FROM Movie GROUP BY country

RHS – SOC 21 SQL query - grouping movieidtitlecountryprodyeargenreoscars 1E.T.USA1982Sci-Fi4 2TaxiFrance1998Comedy0 3HungerDenmark1966Drama1 4LeonFrance1994Thriller0 5Hard BoiledHK1992Action UK1984Sci-Fi2 7SevenUSA1995Thriller1 SELECT country, COUNT(title) AS MovieCount FROM Movie GROUP BY country

RHS – SOC 22 SQL query - grouping CountryMovieCount Denmark1 France2 HK1 UK1 USA2

RHS – SOC 23 SQL query - grouping CountryOscarTotal Denmark1 France0 HK0 UK2 USA5 SUM(oscars) AS …

RHS – SOC 24 SQL query - grouping In the last example, it might be desirable to leave out results where total is zero In general; only include groups which fulfill some criteria This can be done using the HAVING keyword

RHS – SOC 25 SQL query - grouping Syntax: SELECT FROM GROUP BY HAVING

RHS – SOC 26 SQL query - grouping movieidtitlecountryprodyeargenreoscars 1E.T.USA1982Sci-Fi4 2TaxiFrance1998Comedy0 3HungerDenmark1966Drama1 4LeonFrance1994Thriller0 5Hard BoiledHK1992Action UK1984Sci-Fi2 7SevenUSA1995Thriller1 SELECT country, SUM(oscars) AS OscarTotal FROM Movie GROUP BY country HAVING(SUM(oscars) > 0)

RHS – SOC 27 SQL query - grouping movieidtitlecountryprodyeargenreoscars 1E.T.USA1982Sci-Fi4 2TaxiFrance1998Comedy0 3HungerDenmark1966Drama1 4LeonFrance1994Thriller0 5Hard BoiledHK1992Action UK1984Sci-Fi2 7SevenUSA1995Thriller1 SELECT country, SUM(oscars) AS OscarTotal FROM Movie GROUP BY country HAVING(SUM(oscars) > 0)

RHS – SOC 28 SQL query - grouping CountryOscarTotal USA5 France0 UK2 HK0 Denmark1

RHS – SOC 29 SQL query - grouping CountryOscarTotal USA5 UK2 Denmark1

RHS – SOC 30 SQL query - grouping But wait… …isn’t HAVING the same as WHERE..? Not quite –WHERE is for filtering out specific records –HAVING is for filtering out specific groups from the final result We cannot use an aggregate function in a WHERE clause

RHS – SOC 31 Exercise 5 – SQL queries Use the MovieInformation database, defined in exercise 1 With the data in place, run the below queries on the database –SELECT genre, AVG(oscars) FROM Movie GROUP BY genre –SELECT oscars, MAX(prodyear) FROM Movie WHERE (oscars > 0) GROUP BY oscars –SELECT genre, AVG(oscars) FROM Movie GROUP BY genre HAVING (COUNT(title) > 1) Now formulate queries yourself, in order to retrieve the below data: –Get a list of the total count of movies, grouped by country. Within each contry group, the count should be grouped by genre –Get a list of the average number of oscars won by movies, grouped by country –Get a list of the total count of movies, grouped by country. Only include movies made after 1985