In This Lecture. Yet More SQL SELECT ORDER BY. SQL SELECT Overview. ORDER BY Example. ORDER BY Example. Yet more SQL

Similar documents
In This Lecture. More SQL Select. SQL SELECT Overview. Aliases. Example. Example. More SQL Select. Database Systems Lecture 8 Natasha Alechina

SQL Data Query Language

G64DBS Database Systems. Lecture 7 SQL SELECT. The Data Dictionary. Data Dictionaries. Different Sections of SQL (DDL) Different Sections of SQL (DCL)

Data Manipulation Language (DML)

CSC Web Programming. Introduction to SQL

Oracle Database 11g: SQL and PL/SQL Fundamentals

CS 582 Database Management Systems II

COMP 244 DATABASE CONCEPTS & APPLICATIONS

Querying Data with Transact SQL

A. It executes successfully and displays rows in the descending order of PROMO_CATEGORY.

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Physical DB Issues, Indexes, Query Optimisation. Database Systems Lecture 13 Natasha Alechina

Oracle Database: SQL and PL/SQL Fundamentals NEW

CMPT 354: Database System I. Lecture 3. SQL Basics

Computing for Medicine (C4M) Seminar 3: Databases. Michelle Craig Associate Professor, Teaching Stream

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

1) Introduction to SQL

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

Querying Data with Transact-SQL

Lecture 6 - More SQL

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

Oracle Syllabus Course code-r10605 SQL

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Carnegie Mellon Univ. Dept. of Computer Science Database Applications. General Overview - rel. model. Overview - detailed - SQL

SQL (Structured Query Language)

II (The Sequel) We will use the following database as an example throughout this lab, found in students.db.

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

You can write a command to retrieve specified columns and all rows from a table, as illustrated

1Z Oracle Database 11g - SQL Fundamentals I Exam Summary Syllabus Questions

SQL Part 2. Kathleen Durant PhD Northeastern University CS3200 Lesson 6

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations. SQL: Structured Query Language

SQL and Incomp?ete Data

SQL 2 (The SQL Sequel)

CMP-3440 Database Systems

CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries

SQL - Lecture 3 (Aggregation, etc.)

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

Handout 9 CS-605 Spring 18 Page 1 of 8. Handout 9. SQL Select -- Multi Table Queries. Joins and Nested Subqueries.

INTERMEDIATE SQL GOING BEYOND THE SELECT. Created by Brian Duffey

Key Points. COSC 122 Computer Fluency. Databases. What is a database? Databases in the Real-World DBMS. Database System Approach

In this Lecture. More SQL Data Definition. Deleting Tables. Creating Tables. ALTERing Columns. Changing Tables. More SQL

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

Lesson 2. Data Manipulation Language

Language. f SQL. Larry Rockoff COURSE TECHNOLOGY. Kingdom United States. Course Technology PTR. A part ofcenqaqe Learninq

SQL - Data Query language

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

This lecture. Databases - SQL II. Counting students. Summary Functions

SQL: Data Querying. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 4

12. MS Access Tables, Relationships, and Queries

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

Databases - SQL II. (GF Royle, N Spadaccini ) Structured Query Language II 1 / 22

Full file at

SQL Data Querying and Views

Information Systems Engineering. SQL Structured Query Language DML Data Manipulation (sub)language

Intermediate SQL: Aggregated Data, Joins and Set Operators

Database Systems CSE 303. Outline. Lecture 06: SQL. What is Sub-query? Sub-query in WHERE clause Subquery

Relational Database Management Systems for Epidemiologists: SQL Part I

CSE 344 Introduction to Data Management. Section 2: More SQL

CGS 3066: Spring 2017 SQL Reference

Querying Data with Transact-SQL

Database Management Systems,

4. SQL - the Relational Database Language Standard 4.3 Data Manipulation Language (DML)

Oracle 1Z Oracle Database 11g SQL Fundamentals I. Download Full Version :

STIDistrict Query (Basic)

1 SQL Structured Query Language

In This Lecture. The Relational Model. The Relational Model. Relational Data Structure. Unnamed and named tuples. New thing:scheme (and attributes)

Instructor: Craig Duckett. Lecture 11: Thursday, May 3 th, Set Operations, Subqueries, Views

Chapter 3: Introduction to SQL

COSC 122 Computer Fluency. Databases. Dr. Ramon Lawrence University of British Columbia Okanagan

Databases II: Microsoft Access

Unit Assessment Guide

Instructor: Craig Duckett. Lecture 03: Tuesday, April 3, 2018 SQL Sorting, Aggregates and Joining Tables

HKTA TANG HIN MEMORIAL SECONDARY SCHOOL SECONDARY 3 COMPUTER LITERACY. Name: ( ) Class: Date: Databases and Microsoft Access

Relational Database Management Systems for Epidemiologists: SQL Part II

SQL BASICS WITH THE SMALLBANKDB STEFANO GRAZIOLI & MIKE MORRIS

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

Querying Data with Transact SQL Microsoft Official Curriculum (MOC 20761)

3. Getting data out: database queries. Querying

1Z0-071 Exam Questions Demo Oracle. Exam Questions 1Z Oracle Database 12c SQL.

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design

Sql Server Syllabus. Overview

1Z0-071 Exam Questions Demo Oracle. Exam Questions 1Z Oracle Database 12c SQL.

The SQL data-definition language (DDL) allows defining :

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

SQL. Char (30) can store ram, ramji007 or 80- b

CSCB20 Week 4. Introduction to Database and Web Application Programming. Anna Bretscher Winter 2017

SQL Data Manipulation Language. Lecture 5. Introduction to SQL language. Last updated: December 10, 2014

AO3 - Version: 2. Oracle Database 11g SQL

Database Usage (and Construction)

4. SQL - the Relational Database Language Standard 4.3 Data Manipulation Language (DML)

SQL queries II. Set operations and joins

In This Lecture. SQL Data Definition SQL SQL. Non-Procedural Programming. Notes. Database Systems Lecture 5 Natasha Alechina

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Simple SQL Queries (2)

1 SQL Structured Query Language

Transcription:

In This Lecture Yet More SQL Database Systems Lecture 9 Natasha Alechina Yet more SQL ORDER BY Aggregate functions and HAVING etc. For more information Connoly and Begg Chapter 5 Ullman and Widom Chapter 6.4 SQL Overview ORDER BY [DISTINCT ALL] <column-list> FROM <table-names> [WHERE <condition>] [ORDER BY <column-list>] [ <column-list>] [HAVING <condition>] ([]- optional, -or) The ORDER BY clause sorts the results of a query You can sort in ascending (default) or descending order Multiple columns can be given <columns> FROM <tables> WHERE <condition> ORDER BY <cols> [ASCENDING DESCENDING ASC DESC ] ORDER BY Example * ORDER BY Mark ORDER BY Example * ORDER BY Code ASC, Mark DESC 1

Constants and Arithmetic Aggregate Functions As well as column names, you can select constants, compute arithmetic expressions and evaluate functions in a statement Mark/100 Salary + Bonus FROM Employee 1.175*Price FROM Products Aggregate functions compute summaries of data in a table Most aggregate functions (all except COUNT) work on a single column of numeric data Use an alias to name the result Aggregate functions COUNT: The number of rows SUM: The sum of the entries in a column AVG: The average entry in a column MIN, MAX: The minimum and maximum entries in a column Aggregate Functions Aggregate Functions COUNT(*) AS Count SUM(Mark) AS Total MAX(Mark) AS Best Count 6 Total 320 Best 72 You can combine aggregate functions using arithmetic MAX(Mark)-MIN(Mark) AS Range MAX(Mark) = 72 MIN(Mark) = 35 Range 37 Example Modules Code Title Credits DBS Database Sys. 10 GRP Group Project 20 PRG Programming 10 John DBS 60 Mark GRP 47 Mary PRG 56 Find John s average mark, weighted by the credits of each module SUM(Mark*Credits)/SUM(Credits) FROM Modules, WHERE Modules.Code=.Code AND.Name = John Sometimes we want to apply aggregate functions to groups of rows Example, find the average mark of each student The clause does this <cols1> FROM <tables> <cols2> 2

<cols1> FROM <tables> <cols2> Every entry in <cols1> must be in <cols2>, be a constant, or be an aggregate function You can have WHERE and ORDER BY clauses as well as a clause Name, Name Average John 64 Mary 60 Mark 39 Jane 54 Sales Month Department Value March Fiction 20 March Travel 30 March Technical 40 April Fiction 10 April Fiction 30 April Travel 25 April Fiction 20 May Fiction 20 May Technical 50 Find the total value of the sales for each department in each month Can group by Month then Department or Department then Month Same results, but in a different order Month, Department, SUM(Value) AS Total FROM Sales Month, Department Month Department Total April Fiction 60 April Travel 25 March Fiction 20 March Technical 40 March Travel 30 May Fiction 20 May Technical 50 Month, Department, SUM(Value) AS Total FROM Sales Department, Month Month Department Total April Fiction 60 March Fiction 20 May Fiction 20 March Technical 40 May Technical 50 April Travel 25 March Travel 30 HAVING WHERE and HAVING HAVING is like a WHERE clause, except that it applies to the results of a query It can be used to select groups which satisfy a given condition Name, HAVING AVG(Mark) >= 40 Name Average John 64 Mary 60 Jane 54 WHERE refers to the rows of tables, and so cannot use aggregate functions HAVING refers to the groups of rows, and so cannot use columns which are not in the Think of a query being processed as follows: Tables are combined WHERE clauses and Aggregates Column selection HAVING clauses ORDER BY 3

, etc., INTERSECT, and EXCEPT These treat the tables as sets and are the usual set operators of union, intersection, and difference We ll concentrate on Oracle has MINUS instead of EXCEPT They all combine the results from two select statements The results of the two selects must have the same columns and data types Jane IAI 52 Find, in a single query, the average mark for each student, and the average mark overall The average for each student: Name, The average overall Total AS Name, Note - this has the same columns as the average by student Name 'Total' as Name, Name Average Jane 52 John 64 Mark 39 Mary 60 Total 53 A Final Example Tables for the Example Examiners reports We want a list of students and their average mark For first and second years the average is for that year For finalists it is 40% of the second year plus 60% of the final year average. We want the results Sorted by year then average mark (High to low) then last name, first name, and finally ID To take into account the number of credits each module is worth Produced by a single query Student ID First Last Year Grade ID Code Mark YearTaken Module Code Title Credits 4

We ll Need a We ll need to Join the Tables Finalists are treated differently Write one query for the finalists Write a second query for the first and second years Use a to join them together <QUERY FOR FINALISTS> <QUERY FOR OTHERS> Both of the subqueries need information from all the tables The student ID, name and year The marks for each module and the year taken The number of credits for each module This is a natural join operation We could use a NATURAL JOIN statement, and hope that our version of SQL can do it Safer to just use a WHERE clause The Query So Far <some information> AND <student is in third year> <some information> AND <student is in first or second year> Information for Finalists We need to retrieve Compute average mark, weighted 40-60 across years 2 and 3 First year marks need to be ignored The ID, Name, and Year are needed as they are used for ordering The average is hard We don t have any statement to separate years 2 and 3 easily We can exploit the fact that 40 = 20*2 and 60 = 20*3, so YearTaken and the weighting have a simple relationship Information for Finalists Year, Student.ID, Last, First, SUM((20*YearTaken/100)*Mark*Credits)/120 AS AverageMark AND YearTaken IN (2,3) AND Year = 3 Year, Student.ID, First, Last Information for Other Students Other students are easier than finalists We just need to average their marks where YearTaken and Year are the same As before we need the ID, Name, and Year for ordering 5

Information for Other Students Year, Student.ID, Last, First, SUM(Mark*Credits)/120 AS AverageMark AND YearTaken = Year AND Year IN (1,2) Year, Student.ID, First, Last The Final Query Year, Student.ID, Last, First, SUM((20*YearTaken/100)*Mark*Credits)/120 AS AverageMark AND YearTaken IN (2,3) AND Year = 3 Year, Student.ID, First, Last Year, Student.ID, Last, First, SUM(Mark*Credits)/120 AS AverageMark AND YearTaken = Year AND Year IN (1,2) Year, Student.ID, First, Last ORDER BY Year desc, AverageMark desc, First, Last, ID Next Lecture Missing Information NULLs and three-valued logic NULLs and the relational model OUTER JOINs Default values For more information Ullman and Widom 6.1.5, 6.1.6, 6.3.8 Yet More SQL 6