CS 338 Join, Aggregate and Group SQL Queries



Similar documents
Chapter 8. SQL-99: SchemaDefinition, Constraints, and Queries and Views

Introduction to SQL: Data Retrieving

SQL Nested & Complex Queries. CS 377: Database Systems

Part 4: Database Language - SQL

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

Summary on Chapter 4 Basic SQL

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Relational Schema. CS 4700/6700 A Sample of Small Database Design Using Microsoft Access

SQL-99: Schema Definition, Basic Constraints, and Queries

The Relational Algebra

How To Create A Table In Sql (Ahem)

CSC 443 Data Base Management Systems. Basic SQL

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Relational Database: Additional Operations on Relations; SQL

Lab Manual. Database Systems COT-313 & Database Management Systems Lab IT-216

CHAPTER 8: SQL-99: SCHEMA DEFINITION, BASIC CONSTRAINTS, AND QUERIES

Lab Assignment Creating a Relational Database Schema from ER Diagram, Populating the Database and Querying over the database with SQL

VIEWS virtual relation data duplication consistency problems

Structured Query Language (SQL)

Relational Algebra. Query Languages Review. Operators. Select (σ), Project (π), Union ( ), Difference (-), Join: Natural (*) and Theta ( )

Information Systems SQL. Nikolaj Popov

1. SELECT DISTINCT f.fname FROM Faculty f, Class c WHERE f.fid = c.fid AND c.room = LWSN1106

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

b. Examine the following histories. Draw their serialization graph and identify which of them is serializable given reasons.

Performing Queries Using PROC SQL (1)

ER & EER to Relational Mapping. Chapter 9 1

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

SQL SELECT Query: Intermediate

Oracle SQL. Course Summary. Duration. Objectives

Introduction to Microsoft Jet SQL

New York University Computer Science Department Courant Institute of Mathematical Sciences

Programming with SQL

10CS54: DATABASE MANAGEMENT SYSTEM

{ PreviousEducation ( CollegeName, StartDate, EndDate, { Degree (DegreeName, Month, Year) }, { Transcript (CourseName, Semester, Year, Grade) } ) }

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

Chapter 1 Overview of the SQL Procedure

Advance DBMS. Structured Query Language (SQL)

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Physical Design. Phases of database design. Physical design: Inputs.

Introduction to database design

Oracle Database: SQL and PL/SQL Fundamentals

Databases 2011 The Relational Model and SQL

Chapter 5. SQL: Queries, Constraints, Triggers

Lab # 5. Retreiving Data from Multiple Tables. Eng. Alaa O Shama

1 Structured Query Language: Again. 2 Joining Tables

More SQL: Assertions, Views, and Programming Techniques

SQL Server 2008 Core Skills. Gary Young 2011

4. SQL. Contents. Example Database. CUSTOMERS(FName, LName, CAddress, Account) PRODUCTS(Prodname, Category) SUPPLIERS(SName, SAddress, Chain)

Oracle Database: SQL and PL/SQL Fundamentals NEW

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Figure 14.1 Simplified version of the

SQL. by Steven Holzner, Ph.D. ALPHA. A member of Penguin Group (USA) Inc.

Oracle Database: SQL and PL/SQL Fundamentals

SQL: QUERIES, CONSTRAINTS, TRIGGERS

CIS 631 Database Management Systems Sample Final Exam

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Oracle/SQL Tutorial 1

Distributed Database Systems. Prof. Dr. Carl-Christian Kanne

The SQL Query Language. Creating Relations in SQL. Referential Integrity in SQL. Basic SQL Query. Primary and Candidate Keys in SQL

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Lecture 4: More SQL and Relational Algebra

Introduction to tuple calculus Tore Risch

IT2305 Database Systems I (Compulsory)

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Query-by-Example (QBE)

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves

Unit 3. Retrieving Data from Multiple Tables

There are five fields or columns, with names and types as shown above.

Lecture 25: Database Notes

SQL: Queries, Programming, Triggers

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables

SUBQUERIES AND VIEWS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Query optimization. DBMS Architecture. Query optimizer. Query optimizer.

IT2304: Database Systems 1 (DBS 1)

6 QUERY-BY-EXAMPLE (QBE)

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Database Administration with MySQL

GET DATA FROM MULTIPLE TABLES QUESTIONS

Introduction to SQL C H A P T E R3. Exercises

DATABASE DESIGN AND IMPLEMENTATION II SAULT COLLEGE OF APPLIED ARTS AND TECHNOLOGY SAULT STE. MARIE, ONTARIO. Sault College

University of Massachusetts Amherst Department of Computer Science Prof. Yanlei Diao

Distributed Database Management Systems

Beginning C# 5.0. Databases. Vidya Vrat Agarwal. Second Edition

3. Relational Model and Relational Algebra

Join Example. Join Example Cart Prod Comprehensive Consulting Solutions, Inc.All rights reserved.

Relational Databases

Relational Algebra and SQL

Mini User's Guide for SQL*Plus T. J. Teorey

COURSE CODE: CIT 844 COURSE TITLE: ADVANCED DATABASE MANAGEMENT SYSTEM

BIG DATA HANDS-ON WORKSHOP Data Manipulation with Hive and Pig

Big Data and Scripting map/reduce in Hadoop

Introduction to SQL ( )

featuring data privacy Andres Avelino Campos Sainz A Project submitted in partial fulfillment of the requirements for the degree of

Effective Use of SQL in SAS Programming

Define terms Write single and multiple table SQL queries Write noncorrelated and correlated subqueries Define and use three types of joins

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

SQL: Queries, Programming, Triggers

Aggregating Data Using Group Functions

Overview of Database Management

Transcription:

CS 338 Join, Aggregate and Group SQL Queries Bojana Bislimovska Winter 2016

Outline SQL joins Aggregate functions in SQL Grouping in SQL HAVING clause

SQL Joins Specifies a table resulting from a join operation of other tables in the FROM clause Join conditions can be specified in the WHERE clause NATURAL JOIN No join condition explicitly specified Join between attributes with the same name from the different relations It is possible to rename the attributes first so that they match Each pair of attributes is included only once in the resulting relation SELECT Fname, Lname, Address FROM (EMPLOYEE NATURAL JOIN DEPARTMENT AS DEPT(Dname, Dno, Mssn, MsDate))) WHERE Dname= Research ;

SQL Joins INNER JOIN (default type) A tuple is included in the result only if a matching tuple exists in the other relation OUTER JOIN LEFT OUTER JOIN- every tuple in the left table must appear in the result If it does not have a matching tuple, it is padded with NULL values for the attributes of the right table SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S ON E.Super_ssn=S.Ssn);

SQL Joins OUTER JOIN keyword OUTER may be omitted RIGHT OUTER JOIN- every tuple in the right table must appear in the result If it does not have a matching tuple, it is padded with NULL values for the attributes of the left table FULL OUTER JOIN every tuple in the right table and every tuple in the left table must appear in the result CROSS JOIN cartesian product of the two tables, returning all posible combinations of all tuples Multiway join join multiple tables in a single joined table, nesting join specifications SELECT Pnumber, Dnum, Lname, Address, Bdate FROM ((PROJECT JOIN DEPARTMENT ON Dnum=Dnumber) JOIN EMPLOYEE ON Mgr_ssn=Ssn) WHERE Plocation= Stafford ;

Aggregate Functions in SQL Major research Used to summarize information from multiple tuples into a singletuple summary Common built-in aggregate functions: COUNT, SUM, AVG, MAX, MIN Examples 1. SELECT SUM (Salary) FROM (EMPLOYEE JOIN DEPARTMENT ON Dno=Dnumber) WHERE Dname= Research 2. SELECT COUNT(*) FROM EMPLOYEE 3. SELECT COUNT(DISTINCT SALARY) FROM EMPLOYEE

Grouping in SQL Creates subgroups of tuples before aggregation Example: Find average salary of employees in each department Partition the relation into nonoverlapping tuples that have same value of some (grouping) attribute(s) Apply function to each tuple independently to produce summary information about each group GROUP BY clause specifies the grouping attributes Grouping attributes must also appear in the SELECT clause SELECT Dno, AVG(Salary) FROM EMPLOYEE GROUP BY Dno;

Grouping in SQL WHERE clause can be used SELECT Dno, COUNT(*) FROM EMPLOYEE WHERE Salary>25000 GROUP BY Dno; Results can be ordered and the aggregate column can have a name SELECT Dno, COUNT(*) AS NO_EMP FROM EMPLOYEE WHERE Salary>25000 GROUP BY Dno ORDER BY Dno

HAVING clause in SQL Provides condition on the summary information regarding the group of tuples associated with each value of the grouping attributes Only groups that satisfy the condition are retrieved as a result of the query SELECT Dname, COUNT(*) FROM DEPARTMENT, EMPLOYEE WHERE Dnumber=Dno AND Salary>40000 GROUP BY Dname HAVING COUNT(*)>5; HAVING clause cannot reference individual tuples It selects individual groups of tuples WHERE applies to individual tuples WHERE clause is executed first, HAVING clause is applied later

Exercises 1. Consider the following relations: Emp(eno, ename, title, city) Proj(pno, pname, budget, city) Works(eno, pno, resp, dur) Pay(title, salary) where the primary keys are underlined, and Emp.title is a foreign key to Pay.title, Works.eno is a foreign key to Emp.eno, and Works.pno is a foreign key to Proj.pno. Write the following SQL queries: 1) Find average salary of all employees working on the project XYZ. 2) For each city, how many projects are located in that city and what is the total budget over all projects in the city?

Exercises 2. A database for an organization that shelters animals, and people can go and adopt animals that they shelter, has the following set of relations: Animals(ID: integer, Name: string, Owner: integer, DateAdmitted: date, Type:string) Adopter(PID: integer, Name: string, Address: string) Adoption(AnimalID:integer, PID:integer, AdoptDate: date, chipno: integer) where the type of each attribute is given following the attribute (e.g., ID: integer), and the primary keys are underlined. Furthermore, (a) Animals stores information about the animals. Each is given an ID, and their names (attribute Name) together with the PID of their owners (attribute Owner) if they have been adopted, and their date of admission is recorded (so Owner is a foreign key to Adopter.PID). Type refers to the type of animal (dog, cat, etc). Note that this is a historical table, so it keeps track of all admitted animals, even if some of them have been adopted. (b) Adopter is the relation that holds information about animal adopters. The PID of the person who has adopted an animal is recorded as well as his/her Name and Address. (c) Adoption.AnimalID refers to Animals.ID and has the same type. Similarly, Adoption.PID refers to Adopter. PID and has the same type. Attribute chipno stores the number on the microchip that is implanted on the animal for tracking.

Exercises Formulate the following queries in SQL: 1) Retrieve the total number of dogs that were brought to the shelter on 18 April 2015. 2) For each animal type, list the animal type and total number of adoptions on 14 June 2015. 3) For each adopter who has made at least two adoptions, list their names and addresses.