References: Text Chapters 8 and 9

Slides:



Advertisements
Similar presentations
Advanced SQL (part 1) CS263 Lecture 7.
Advertisements

Multiple Table Queries
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Chapter 4 Joining Multiple Tables
A Guide to SQL, Seventh Edition. Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables.
Structure Query Language (SQL) COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
Introduction to Structured Query Language (SQL)
Introduction to Oracle9i: SQL1 Basic SQL SELECT Statements.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
Chapter 7 Advanced SQL Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
Introduction to Structured Query Language (SQL)
Chapter 6 SQL: Data Manipulation Cont’d. 2 ANY and ALL u ANY and ALL used with subqueries that produce single column of numbers u ALL –Condition only.
Chapter 3 Single-Table Queries
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 8 Advanced SQL.
Introduction to Databases Chapter 7: Data Access and Manipulation.
Chapter 9 Joining Data from Multiple Tables
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
A Guide to MySQL 5. 2 Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables Use a subquery.
Lecture8:Data Manipulation in SQL Advanced SQL queries Ref. Chapter5 Lecture8 1.
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
Lecture6:Data Manipulation in SQL, Simple SQL queries Prepared by L. Nouf Almujally Ref. Chapter5 Lecture6 1.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
Chapter 6 SQL: Data Manipulation (Advanced Commands) Pearson Education © 2009.
Lecture7:Data Manipulation in SQL Advanced Queries Prepared by L. Nouf Almujally Ref. Chapter5 Lecture7 1.
Chapter 4 Multiple-Table Queries
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
1 Multiple Table Queries. 2 Objectives  Retrieve data from more than one table by joining tables  Using IN and EXISTS to query multiple tables  Nested.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Chapter 12 Subqueries and Merge Statements
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 Five Multiple-Table Queries.
SQL: Sub-queries Single-value sub-queries Single-column sub-queries Sub-queries that produce tables Correlated sub-queries D. Christozov / G.Tuparov INF.
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.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
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.
Slide 1 of 32ASH-Training Querying and Managing Data Using SQL Server 2014 By: Segla In this session, you will learn to: Query data by using joins Query.
Database Design lecture 3_2 Slide 1 Database Design Lecture 3_2 Data Manipulation in SQL Simple SQL queries References: Text Chapter 8 Oracle SQL Manual.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
IFS180 Intro. to Data Management Chapter 10 - Unions.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Chapter 11 SQL: Data Manipulation
More SQL: Complex Queries,
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
Database Systems: Design, Implementation, and Management Tenth Edition
Schedule Today: Next After that Subqueries, Grouping and Aggregation.
SQL: Structured Query Language DML- Queries Lecturer: Dr Pavle Mogin
Writing Basic SQL SELECT Statements
David M. Kroenke and David J
CS 405G: Introduction to Database Systems
MENAMPILKAN DATA DARI SATU TABEL (Chap 2)
Chapter Name SQL: Data Manipulation
JOINS (Joinining multiple tables)
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
CS4222 Principles of Database System
CMPT 354: Database System I
SQL: Structured Query Language
Chapter Name SQL: Data Manipulation
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Database Systems: Design, Implementation, and Management Tenth Edition
JOINS (Joinining multiple tables)
Presentation transcript:

References: Text Chapters 8 and 9 Database Design Lecture 4 Advanced SQL References: Text Chapters 8 and 9 Oracle SQL Manual Database Design lecture 4Ses Slide 1

General Syntax of SELECT command SELECT [DISTINCT | ALL] Advanced queries General Syntax of SELECT command SELECT [DISTINCT | ALL] {* | [columnExpression [AS newName]] [,...] } FROM TableName [alias] [, ...] [WHERE condition] [GROUP BY columnList] [HAVING condition] [ORDER BY columnList] Order of the clauses cannot be changed. Only SELECT and FROM are mandatory Database Design lecture 4Ses Slide 2

Use GROUP BY clause to get sub-totals. Use of GROUP BY Use GROUP BY clause to get sub-totals. SELECT and GROUP BY closely integrated: each item in SELECT list must be single-valued per group, and SELECT clause may only contain: Column names in the group by clause Aggregate functions Constants Expression involving combinations of the above If WHERE is used with GROUP BY, WHERE is applied first, then groups are formed from rows satisfying condition. Database Design lecture 4Ses Slide 3

List the quantity of each product ordered during Jan 2003. Example 1 List the quantity of each product ordered during Jan 2003. SELECT prodNo, sum(quantity) FROM orders WHERE ordDate>='01-jan-2003' AND ordDate<'01-Feb-2003' GROUP BY prodNo; Database Design lecture 4Ses Slide 4

Example 1-continued ordNo ordDate custNo prodNo quantity 1 01-jan-2003 100 2 4 3 02-jan-2003 101 5 03-jan-2003 102 6 06-mar-2003 10 Database Design lecture 4Ses Slide 5

Use of HAVING HAVING clause is designed for use with GROUP BY to restrict groups that appear in final result table. Similar to WHERE, but WHERE filters individual rows whereas HAVING filters groups. Column names in HAVING clause must also appear in the GROUP BY list or be contained within an aggregate function. Database Design lecture 4Ses Slide 6

SELECT prodNo, sum(quantity) FROM orders Example 2 List the product number and the quantity ordered for each product which has a total order of more than 2 in Jan 2003. SELECT prodNo, sum(quantity) FROM orders WHERE ordDate>='01-jan-2003' AND ordDate<'01-Feb-2003' GROUP BY prodNo HAVING sum(quantity)>2; Database Design lecture 4Ses Slide 7

Question Are the the following statements legal? If yes do they generate the same result? SELECT prodNo, sum(quantity) FROM orders WHERE ordDate>='01-jan-2003' HAVING prodno=100 GROUP BY prodNo; WHERE ordDate>='01-jan-2003' and prodno=100 WHERE ordDate>='01-jan-2003' and prodno=100; Database Design lecture 4Ses Slide 8

SELECT prodNo, sum(quantity) FROM orders Example 3 List the product number and the quantity ordered for each product which was ordered by two or more distinct customers since 01/01/2003. SELECT prodNo, sum(quantity) FROM orders WHERE ordDate>='01-jan-2003' HAVING count(distinct custNo)>=2 GROUP BY prodNo; Database Design lecture 4Ses Slide 9

Example 3 -continued ordNo ordDate custNo prodNo quantity 1 01-jan-2003 100 2 4 3 6 06-mar-2003 10 02-jan-2003 101 5 03-jan-2003 102 Database Design lecture 4Ses Slide 10

AS is used to give a name (alias) to a column in the result table Use of AS – column alias AS is used to give a name (alias) to a column in the result table Alias rather than original column name will be displayed In Oracle, AS is optional In Oracle, if the alias has spaces or special characters, it has to be double quoted SELECT prodNo, sum(quantity) AS sum, count(distinct custNo) AS noOfCust FROM orders WHERE ordDate>='01-jan-2003' HAVING count(distinct custNo)>=2 GROUP BY prodNo; Database Design lecture 4Ses Slide 11

Alias example SQL> column "room number" format a20 SQL> column "hotel number" format a20 SQL> select RoomNo "room number", hotelno "hotel number" from room; room number hotel number -------------------- -------------------- 001 H01 002 H01 003 H01 004 H01 005 H01 006 H01 001 H02 002 H02 003 H02 004 H02 10 rows selected. Database Design lecture 4Ses Slide 12

Selecting from Multiple Tables (Joins) Often two or more tables are needed at the same time to find all required data These tables must be "joined" together The formal JOIN operation will be explained later, basically it computes a new table from those to be joined, the new table contains data in the matching rows of the individual tables. Database Design lecture 4Ses Slide 13

SQL Examples of Joins List customers (by customer number, name and address) who have ordered the product 100. SELECT c.custNo, custName, custSt, custCity FROM customer c, orders o WHERE c.custNo=o.custNo AND prodNo=100; ordNo ordDate custNo prodNo quantity 1 01-jan-2003 100 2 02-jan-2003 101 3 102 4 5 03-jan-2003 6 06-mar-2003 10 custNo custName custSt custCity age 1 C1 Smith St Gold Coast 20 2 C2 Mains St Brisbane 30 3 C3 Mains Rd 25 4 C4 Sydney 5 C5 Database Design lecture 4Ses Slide 14

Example Find the total price of the products ordered by customer 1. SELECT sum(price*quantity) FROM orders, product WHERE orders.prodNo = product.prodNo AND custNo = 1; Note: relation name or alias can be used to qualify column names when there is ambiguity. prodNo prodName prodDes price 100 P0 Food 101 P1 healthy food 102 P2 200 103 P3 self_raising flour,80%wheat 300 104 P4 network 80x ordNo ordDate custNo prodNo quantity 1 01-jan-2003 100 2 02-jan-2003 101 3 102 4 5 03-jan-2003 6 06-mar-2003 10 Database Design lecture 4Ses Slide 15

Left outer Join of tables r and s Outer Joins The outer join of two tables is a new table which not only contains the matching rows, but also contains non-matching rows. Left outer Join of tables r and s keeps every tuple in the left relation r, if no matching tuple in s, pad values with nulls Right outer join keeps every tuple in the right relation s, if no matching tuple in r, pad values with nulls Database Design lecture 4Ses Slide 16

Outer Joins in Oracle SQL Put an (+) on the potentially deficient side, ie the side where nulls may be padded. Example: List all customers, and the products ordered if they have ordered some products. SELECT c.custNo, o.prodNo, quantity FROM customer c, orders o WHERE c.custNo = o.custNo(+); Note: a table may be outer joined with only one other table. Which table column to use is important, eg, in above example, do not use o.custNo in place of c.custNo in the SELECT list. Database Design lecture 4Ses Slide 17

Query results are tables, which can also be queried. Nested Queries (1) Query results are tables, which can also be queried. SELECT * FROM (SELECT prodNo, sum(quantity) as sum FROM orders GROUP BY prodNo) WHERE sum>10; Equivalent to SELECT prodNo, sum(quantity) as sum GROUP BY prodNo HAVING sum(quantity)>10; The inner query is referred to as a subquery Database Design lecture 4Ses Slide 18

Example: Find products with price more than average Nested Queries (2) If the query result is a single value, it can be treated as a value, and be compared with other values. Example: Find products with price more than average SELECT prodNo, price FROM product WHERE price > (SELECT AVG(price) FROM product); Database Design lecture 4Ses Slide 19

List the products ordered by customers living in Brisbane. Use of IN List the products ordered by customers living in Brisbane. SELECT prodNo FROM orders WHERE custNo IN (SELECT custNo FROM customer WHERE custCity ='Brisbane'); This query is equivalent to FROM orders o, customer c WHERE o.custNo =c.custNo AND custCity = 'Brisbane'; Database Design lecture 4Ses Slide 20

Find all customers who have ordered some products. SELECT * EXISTS Find all customers who have ordered some products. SELECT * FROM customer c WHERE exists (SELECT * FROM orders o WHERE o.custNo =c.custNo); If the subquery is not empty, then the exists condition is true. Database Design lecture 4Ses Slide 21

WHERE NOT EXISTS (SELECT * FROM orders o WHERE o.custNo = c.custNo Find all customers such that no order made by them has a quantity less than 2. SELECT * FROM customer c WHERE NOT EXISTS (SELECT * FROM orders o WHERE o.custNo = c.custNo AND quantity <2); Database Design lecture 4Ses Slide 22

Correlated and Uncorrelated Subqueries A correlated subquery is one in which the inner query is referenced by the outer query such that the inner query may be thought being executed repeatedly SELECT * FROM customer c WHERE exists (SELECT * FROM orders o WHERE o.custNo =c.custNo); A uncorrelated subquery is one where the subquery can be executed independently of the outer query. Database Design lecture 4Ses Slide 23

Subqueries versus Joins Subqueries can often be used in place of joins. Eg The query SELECT distinct c.custNo, custName, custSt, custCity FROM customer c, orders o WHERE c.custNo=o.custNo AND prodNo=100; may be replaced with SELECT custNo, custName, custSt, custCity FROM customer WHERE custNo IN (SELECT custNo FROM orders WHERE prodNo=100); or FROM customer c WHERE EXISTS (SELECT * FROM orders WHERE prodNo=100 and custNo = c.custNo) Database Design lecture 4Ses Slide 24

UNION, MINUS and INTERSECT SELECT prodNo FROM product MINUS SELECT prodNo FROM orders; //difference from the two queries SELECT custNo FROM customer WHERE custCity='Brisbane' UNION SELECT custNo FROM orders WHERE prodNo=102; // union of the two queries INTERSECT WHERE prodNo=102; // intersect of the two queries Database Design lecture 4Ses Slide 25