CMP-3440 Database Systems

Similar documents
STRUCTURED QUERY LANGUAGE (SQL)

Chapter 6. SQL Data Manipulation

CMP-3440 Database Systems

Chapter 6. SQL: SubQueries

CS317 File and Database Systems

CMP-3440 Database Systems

Relational Algebra and Relational Calculus. Pearson Education Limited 1995,

3ISY402 DATABASE SYSTEMS

COMP102: Introduction to Databases, 5 & 6

CS317 File and Database Systems

In SQL window, type SHOW TABLE STATUS; and discuss INNODB vs. MyISAM (foreign key support; transactions; row-level locking)

Subquery: There are basically three types of subqueries are:

Database Management Systems,

Chapter 7 Advanced SQL. Objectives

ADVANCED QUERY AND VIEWS

CS317 File and Database Systems

Chapter 5. Relational Algebra and Relational Calculus

Standard Query Language. SQL: Data Definition Transparencies

Lecture 6 Structured Query Language (SQL)

Lecture 5 Data Definition Language (DDL)

Intermediate SQL: Aggregated Data, Joins and Set Operators

Example 1 - Create Horizontal View. Example 2 - Create Vertical View. Views. Views

What Are Group Functions? Reporting Aggregated Data Using the Group Functions. Objectives. Types of Group Functions

RELATIONAL DATA MODEL

ÇALIŞMA TEST SORULARI

KORA. RDBMS Concepts II

Relational Data Model ( 관계형데이터모델 )

Institute of Southern Punjab, Multan

Aggregation. Lecture 7 Section Robb T. Koether. Hampden-Sydney College. Wed, Jan 29, 2014

Lecture 07. Spring 2018 Borough of Manhattan Community College

SQL Data Query Language

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

Cheltenham Courseware Microsoft Access 2003 Manual - Advanced Level SAMPLE

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

Querying Data with Transact SQL

DB Creation with SQL DDL

Lecture 03. Spring 2018 Borough of Manhattan Community College

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

Assignment 6: SQL III Solution

Reporting Aggregated Data Using the Group Functions. Copyright 2004, Oracle. All rights reserved.

Aggregate Functions. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Dept. Database Lab (ECOM 4113)

Set theory is a branch of mathematics that studies sets. Sets are a collection of objects.

2.2.2.Relational Database concept

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

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

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

Objectives. After completing this lesson, you should be able to do the following:

SQL QUERIES. CS121: Relational Databases Fall 2017 Lecture 5

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

Database Technologies. Madalina CROITORU IUT Montpellier

Relational Database Management Systems for Epidemiologists: SQL Part II

Lecture 03. Fall 2017 Borough of Manhattan Community College

SQL queries II. Set operations and joins

The Relational Algebra

Slicing and Dicing Data in CF and SQL: Part 1

1) Introduction to SQL

Structured Query Language Continued. Rose-Hulman Institute of Technology Curt Clifton

Intermediate SQL ( )

Sql Server Syllabus. Overview

Assignment 6: SQL III

SQL: Advanced Queries, Assertions, Triggers, and Views. Copyright 2012 Ramez Elmasri and Shamkant B. Navathe

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

Lecture 06. Fall 2018 Borough of Manhattan Community College

GIFT Department of Computing Science. CS-217: Database Systems. Lab-4 Manual. Reporting Aggregated Data using Group Functions

Lab # 6. Data Manipulation Language (DML)

T-SQL Training: T-SQL for SQL Server for Developers

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

Lecture 05. Spring 2018 Borough of Manhattan Community College

Relational Model. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Oracle Syllabus Course code-r10605 SQL

Databases - 5. Problems with the relational model Functions and sub-queries

Database 2: Slicing and Dicing Data in CF and SQL

Querying Data with Transact-SQL

RDBMS- Day 4. Grouped results Relational algebra Joins Sub queries. In today s session we will discuss about the concept of sub queries.

Join, Sub queries and set operators

An Introduction to Structured Query Language

An Introduction to Structured Query Language

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

Querying Data with Transact-SQL

An Introduction to Structured Query Language

Introduction to Oracle9i: SQL

Transforming ER to Relational Schema

Structure Query Language (SQL)

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

Objective. The goal is to review material covered in Chapters 1-5. Do the following questions from the book.

An Introduction to Structured Query Language

An Introduction to Structured Query Language

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

SQL STRUCTURED QUERY LANGUAGE

Chapter 6 - Part II The Relational Algebra and Calculus

Relational Database Management Systems for Epidemiologists: SQL Part I

Outline. Note 1. CSIE30600 Database Systems More SQL 2

Query Processing Transparencies. Pearson Education Limited 1995, 2005

SQL Data Querying and Views

SQL (Structured Query Language)

Chapter 3. The Relational database design

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

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

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

Transcription:

CMP-3440 Database Systems Advanced SQL Lecture 07 zain 1

Select Statement - Aggregates ISO standard defines five aggregate functions: COUNT returns number of values in specified column. SUM returns sum of values in specified column. AVG returns average of values in specified column. MIN returns smallest value in specified column. MAX returns largest value in specified column. 2

Select Statement - Aggregates Each operates on a single column of a table and return single value. COUNT, MIN, and MAX apply to numeric and non-numeric fields, but SUM and AVG may be used on numeric fields only. Apart from COUNT(*), each function eliminates nulls first and operates only on remaining non-null values. COUNT(*) counts all rows of a table, regardless of whether nulls or duplicate values occur. Can use DISTINCT before column name to eliminate duplicates. DISTINCT has no effect with MIN/MAX (it eliminates duplicates itself), but may have with SUM/AVG, e.g. select avg(sal) from emp select avg(distinct sal) from emp; 3

Select Statement - Aggregates Aggregate functions can be used only in SELECT list and in HAVING clause. If SELECT list includes an aggregate function and there is no GROUP BY clause, SELECT list cannot reference a column outwith an aggregate function. For example, following is illegal: SELECT staffno, COUNT(salary) FROM Staff; 4

Select Statement - Aggregates Use of COUNT(*) How many properties cost more than 350 per month to rent? SELECT COUNT(*) AS count FROM PropertyForRent WHERE rent > 350; 5

Select Statement - Aggregates Use of COUNT(DISTINCT) How many different properties viewed in May 01? SELECT COUNT(DISTINCT propertyno) AS count FROM Viewing WHERE date BETWEEN 1-May-01 AND '31-May-01'; 6

Select Statement - Aggregates Use of COUNT and SUM Find number of Managers and sum of their salaries. SELECT COUNT(staffNo) AS count, SUM(salary) AS sum FROM Staff WHERE position = 'Manager'; 7

Select Statement - Aggregates Use of MIN, MAX, AVG Find minimum, maximum, and average staff salary. SELECT FROM Staff; MIN(salary) AS min, MAX(salary) AS max, AVG(salary) AS avg 8

Select Statement Column Grouping Count the number of customers with addresses in each state to which we ship. SELECT CustomerState, COUNT (CustomerState) FROM Customer_T GROUP BY CustomerState; SELECT CustomerState, COUNT (CustomerState) FROM Customer_T GROUP BY CustomerState HAVING COUNT (CustomerState) > 1; Use GROUP BY clause to get sub-totals. Useful when paired with aggregate functions, SUM or COUNT 9

Example Column Grouping Find number of staff in each branch and their total salaries. SELECT branchno, COUNT(staffNo) AS count, SUM(salary) AS sum FROM Staff GROUP BY branchno ORDER BY branchno; 10

Restricted Grouping Having Clause HAVING clause is designed for use with GROUP BY to restrict groups that appear in final result table. For each branch with more than 1 member of staff, find number of staff in each branch and sum of their salaries. SELECT branchno, COUNT(staffNo) AS count, SUM(salary) AS sum FROM Staff GROUP BY branchno HAVING COUNT(staffNo) > 1 ORDER BY branchno; 11

Processing Multiple Tables Relational Table Primary key from one table and a foreign key that references the table with the primary key will share a common domain and are frequently used to establish a join. Join A relational table that causes two tables (recommended upto 10 tables) with a common domain to be combined into a single table or view. Joins without Relationships Occasionally, joins will be established using columns that share a common domain but not the primary / foreign key relationship, and that also works. 12

Equi-Join The joining condition is based on equality between values in the common columns. Number of rows is equal from each table. Query: What are the customer IDs and names of all customers, along with the order IDs for all the orders they have placed? SELECT Customer_T.CustomerID, Order_T.CustomerID, CustomerName, OrderID FROM Customer_T, Order_T WHERE Customer_T.CustomerID = Order_T. CustomerID ORDER BY OrderID; 13

Equi-Join Query: What are the customer IDs and names of all customers, along with the order IDs for all the orders they have placed? SELECT Customer_T.CustomerID, Order_T.CustomerID, CustomerName, OrderID FROM Customer_T INNER JOIN Order_T ON Customer_T.CustomerID = Order_T.CustomerID ORDER BY OrderID; SELECT Customer_T.CustomerID, Order_T.CustomerID, CustomerName, OrderID FROM Customer_T INNER JOIN Order_T USING CustomerID ORDER BY OrderID ; 14

Natural-Join Most commonly used form of join operation. Same as an equi-join, except that it is performed over matching columns, and one of the duplicate columns is eliminated in the result table. Query: For each customer who has placed an order, what is the customer s ID, name, and order number? SELECT Customer_T.CustomerID, CustomerName, OrderID FROM Customer_T NATURAL JOIN Order_T ON Customer_T.CustomerID = Order_T.CustomerID; 15

Outer-Join Rows that do not have matching values in common columns are also included. Null values appear in columns where there is not a match between tables. OUTER JOIN syntax does not apply easily to a join condition of more than two tables. Left Outer Join For all rows in A that have no matching rows in B Right Outer Join For all rows in B that have no matching rows in A Full Outer Join Returns all rows from A and B, extended with nulls if they do not satisfy the join condition 16

Outer-Join Left Outer Join Query: List customer name, identification number, and order number for all customers listed in the Customer table. Include the customer identification number and name even if there is no order available for that customer. SELECT Customer_T.CustomerID, CustomerName, OrderID FROM Customer_T LEFT OUTER JOIN Order_T ON WHERE Customer_T.CustomerID = Order_T. CustomerID; 17

Outer-Join Right Outer Join Query: List customer name, identification number, and order number for all orders listed in the Order table. Include the order number, even if there is no customer name and identification number available. SELECT Customer_T.CustomerID,CustomerName, OrderID FROM Customer_T RIGHT OUTER JOIN Order_T ON Customer_T.CustomerID = Order_T.CustomerID; 18

Multiple Tables Join Query: Assemble all information necessary to create an invoice for order number 1006. 19

Multiple Tables Join SELECT Customer_T.CustomerID, CustomerName, CustomerAddress, CustomerCity, CustomerState, CustomerPostalCode, Order_T.OrderID, OrderDate, OrderedQuantity, ProductDescription, StandardPrice, (OrderedQuantity * ProductStandardPrice) FROM Customer_T, Order_T, OrderLine_T, Product_T WHERE Order_T.CustomerID = Customer_T.CustomerID AND Order_T.OrderID = OrderLine_T.OrderID AND OrderLine_T.ProductID = Product_T.ProductID; AND Order_T.OrderID = 1006; 20

Self-Join Unary relationship: Joining a table with itself. Query: What are the employee ID and name of each employee and the name of his or her supervisor (label the supervisor s name Manager)? SELECT E.EmployeeID, E.EmployeeName, M.EmployeeName AS Manager FROM Employee_T E, Employee_T M WHERE E.EmployeeSupervisor = M.EmployeeID; 21

Subqueries Some SQL statements can have a SELECT embedded within them. A subselect can be used in WHERE and HAVING clauses of an outer SELECT, where it is called a subquery or nested query. Subselects may also appear in INSERT, UPDATE, and DELETEs. 22

Subquery with Equality List staff who work in branch at '163 Main St'. SELECT staffno, fname, lname, position FROM Staff WHERE branchno = (SELECT branchno FROM Branch WHERE street = '163 Main St'); Inner SELECT finds branch number for branch at '163 Main St' ('B003'). Outer SELECT then retrieves details of all staff who work at this branch. 23

Subquery with Aggregate List all staff whose salary is greater than the average salary, and show by how much. SELECT staffno, fname, lname, position, salary (SELECT AVG(salary) FROM Staff) As SalDiff FROM Staff WHERE salary > (SELECT AVG(salary) FROM Staff); 24

Nested Subquery Use of IN List properties handled by staff at '163 Main St'. SELECT propertyno, street, city, postcode, type, rooms, rent FROM PropertyForRent WHERE staffno IN (SELECT staffno FROM Staff WHERE branchno = (SELECT branchno FROM Branch WHERE street = '163 Main St')); 25

Nested Subquery ANY and ALL ANY and ALL may be used with subqueries that produce a single column of numbers. With ALL, condition will only be true if it is satisfied by all values produced by subquery. With ANY, condition will be true if it is satisfied by any values produced by subquery. If subquery is empty, ALL returns true, ANY returns false. SOME may be used in place of ANY. 26

Nested Subquery Use of ANY/SOME Find staff whose salary is larger than salary of at least one member of staff at branch B003. SELECT staffno, fname, lname, position, salary FROM Staff WHERE salary > SOME (SELECT salary FROM Staff WHERE branchno = 'B003'); 27

Nested Subquery Use of ALL Find staff whose salary is larger than salary of every member of staff at branch B003. SELECT staffno, fname, lname, position, salary FROM Staff WHERE salary > ALL (SELECT salary FROM Staff WHERE branchno = 'B003'); 28

EXISTS and NOT EXISTS EXISTS and NOT EXISTS are for use only with subqueries. Produce a simple true/false result. True if and only if there exists at least one row in result table returned by subquery. False if subquery returns an empty result table. NOT EXISTS is the opposite of EXISTS. As (NOT) EXISTS check only for existence or non-existence of rows in subquery result table, subquery can contain any number of columns. Common for subqueries following (NOT) EXISTS to be of form: (SELECT *...) 29

Query using EXISTS Find all staff who work in a London branch. SELECT staffno, fname, lname, position FROM Staff s WHERE EXISTS (SELECT * FROM Branch b WHERE s.branchno = b.branchno AND city = 'London'); 30

Use of UNION List all cities where there is either a branch or property. (SELECT city FROM Branch WHERE city IS NOT NULL) UNION (SELECT city FROM PropertyForRent WHERE city IS NOT NULL); 31

Use of INTERSECT List all cities where there is both a branch and rental property. (SELECT city FROM Branch) INTERSECT (SELECT city FROM PropertyForRent); Could rewrite this query without INTERSECT operator: SELECT b.city FROM Branch b PropertyForRent p WHERE b.city = p.city; 32

Use of EXCEPT List of all cities where there is a branch but no properties. (SELECT city FROM Branch) city FROM EXCEPT (SELECT PropertyForRent); Could rewrite this query without EXCEPT: SELECT DISTINCT city FROM Branch WHERE city NOT IN (SELECT city FROM PropertyForRent); 33

INSERT SELECT Populate StaffPropCount using Staff and PropertyForRent tables. INSERT INTO StaffPropCount (SELECT s.staffno, fname, lname, COUNT(*) FROM Staff s, PropertyForRent p WHERE s.staffno = p.staffno GROUP BY s.staffno, fname, lname); 34