Hassan Tariq MULTIPLE TABLES: SQL provides a convenient operation to retrieve information from multiple tables.SQL provides a convenient operation to.

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 2
Advertisements

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.
1 Advanced SQL Queries. 2 Example Tables Used Reserves sidbidday /10/04 11/12/04 Sailors sidsnameratingage Dustin Lubber Rusty.
Review Session ER and Relational –ER  Relational –Constraints, Weak Entities, Aggregation, ISA Relational Algebra  Relational Calculus –Selections/Projections/Joins/Division.
SQL: The Query Language Jianlin Feng School of Software SUN YAT-SEN UNIVERSITY courtesy of Joe Hellerstein and etc for some slides.
CS 405G: Introduction to Database Systems
Introduction to Oracle9i: SQL1 Subqueries. Introduction to Oracle9i: SQL2 Chapter Objectives Determine when it is appropriate to use a subquery Identify.
SQL 2 – The Sequel R&G, Chapter 5 Lecture 10. Administrivia Homework 2 assignment now available –Due a week from Sunday Midterm exam will be evening of.
1 SQL (Simple Query Language). 2 Query Components A query can contain the following clauses –select –from –where –group by –having –order by Only select.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
Matthew P. Johnson, OCL1, CISDD CUNY, F20041 OCL1 Oracle 8i: SQL & PL/SQL Session #3 Matthew P. Johnson CISDD, CUNY Fall, 2004.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #9 Matthew P. Johnson Stern School of Business, NYU Spring, 2005.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #10 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
Matthew P. Johnson, OCL4, CISDD CUNY, Sept OCL4 Oracle 10g: SQL & PL/SQL Session #3 Matthew P. Johnson CISDD, CUNY June, 2005.
1 The Oracle Database System Querying the Data Database Course The Hebrew University of Jerusalem.
1 Lecture 02: Basic SQL. 2 Outline Data in SQL Simple Queries in SQL Queries with more than one relation Reading: Chapter 3, “Simple Queries” from SQL.
1 Lecture 2: SQL Wednesday, January 7, Agenda Leftovers from Monday The relational model (very quick) SQL Homework #1 given out later this week.
Inner join, self join and Outer join Sen Zhang. Joining data together is one of the most significant strengths of a relational database. A join is a query.
1 Lecture 3: More SQL Friday, January 9, Agenda Homework #1 on the web site today. Sign up for the mailing list! Next Friday: –In class ‘activity’
1 Information Systems Chapter 6 Database Queries.
CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006.
+ From Relational Algebra to SQL W2013 CSCI 2141.
Structured Query Language Introduction to SQL What is SQL? – –When a user wants to get some information from a database file, he can issue a query.1.
1. Midterm summary Types of data on the web: unstructured, semi- structured, structured Scale and uncertainty are key features Main goals are to model,
IM433-Industrial Data Systems Management Lecture 5: SQL.
Intro. to SQL DSC340 Mike Pangburn. Learning Objectives Understand the data-representation terminology underlying relational databases Understand core.
More SQL: Complex Queries, Triggers, Views, and Schema Modification UMM AL QURA UNIVERSITY College of Computer Dr. Ali Al Najjar 1.
Chapter 9 Joining Data from Multiple Tables
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L6_SQL(1) 1 SQL: Queries, Constraints, Triggers Chapter 5 – Part 1.
SQL Part I: Standard Queries. COMP-421: Database Systems - SQL Queries I 2 Example Instances sid sname rating age 22 debby debby lilly.
Week 10 Quiz 9 Answers Group 28 Christine Hallstrom Deena Phadnis.
SQL SQL Review. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92.
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
Unit 4 Queries and Joins. Key Concepts Using the SELECT statement Statement clauses Subqueries Multiple table statements Using table pseudonyms Inner.
Join, Subqueries and set operators. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
Structured Query Language ( 結構化查詢語言 ) Lesson Review What is S Q L?L? When a user wants to get some information from a database file, he can issue a _______.
Chapter 12 Subqueries and Merge Statements
CMPT 258 Database Systems SQL Queries (Chapter 5).
1 Introduction to Database Systems CSE 444 Lecture 02: SQL September 28, 2007.
1 Lecture 02: SQL Friday, September 30, Administrivia Homework 1 is out. Due: Wed., Oct. 12 Did you login on IISQLSRV ? Did you change your password.
Subqueries.
Lectures 2&3: Introduction to SQL. Lecture 2: SQL Part I Lecture 2.
Hassan Tariq INTRODUCTION TO SQL What is SQL? –When a user wants to get some information from a database file, he can issue a query. – A query is a user–request.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
SQL: The Query Language Part 1 R &G - Chapter 5 The important thing is not to stop questioning. Albert Einstein.
1 SQL: The Query Language. 2 Example Instances R1 S1 S2 v We will use these instances of the Sailors and Reserves relations in our examples. v If the.
SQL BY MR.PRASAD SAWANT INDIA Introduction to SQL What is SQL? –When a user wants to get some information from a database file, he can issue a query.1.
Chapter 7 Subqueries. Chapter Objectives  Determine when it is appropriate to use a subquery  Identify which clauses can contain subqueries  Distinguish.
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
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 practice session
SQL – Part 2.
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
© פרופ' יהושע שגיב, האוניברסיטה העברית
SQL The Query Language R & G - Chapter 5
Server-Side Application and Data Management IT IS 3105 (FALL 2009)
Structured Query Language
Database Applications (15-415) SQL-Part II Lecture 9, February 04, 2018 Mohammad Hammoud.
Cse 344 January 12th –joins.
CS 405G: Introduction to Database Systems
Structured Query Language (II) (結構化查詢語言)
Introduction to SQL Wenhao Zhang October 5, 2018.
? Data Science 100 Databases Part 2 (The SQL) Slides by:
CS4222 Principles of Database System
SQL: Structured Query Language
Presentation transcript:

Hassan Tariq

MULTIPLE TABLES: SQL provides a convenient operation to retrieve information from multiple tables.SQL provides a convenient operation to retrieve information from multiple tables. This operation is called join.This operation is called join. The join operation will combine the tables into one large table with all possible combinations (Math: Cartesian Product), and then it will filter the rows of this combined table to yield useful information.The join operation will combine the tables into one large table with all possible combinations (Math: Cartesian Product), and then it will filter the rows of this combined table to yield useful information.

INNER JOIN 1 LEFT OUTER JOIN 2 RIGHT OUTER JOIN 3 FULL OUTER JOIN 4

9  Connect two or more tables: PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Company CNameStockPriceCountry GizmoWorks25USA Canon65Japan Hitachi15Japan What is the Connection between them ?

10 Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 Join between Product and Company

11 PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Company CnameStockPriceCountry GizmoWorks25USA Canon65Japan Hitachi15Japan PNamePrice SingleTouch$ SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200

12 Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all countries that manufacture some product in the ‘Gadgets’ category. SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’

13 PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Company CnameStockPriceCountry GizmoWorks25USA Canon65Japan Hitachi15Japan Country ?? What is the problem ? What’s the solution ? SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’

NATURAL JOIN / INNER JOIN A Natural Join is a join operation that joins two tables bytheir common column. This operation is similar to the setting relation of two tables. SELECT a.comcol, a.col1, b.col2, expr1, expr2 ; FROM table1 a, table2 b ; WHERE a.comcol = b.comcol

NATURAL JOIN / INNER JOIN Musicid typeStudent idnameclass Productidnameclasstype Same id Join eg. 25 Make a list of students and the instruments they learn. (Natural Join) eg. 25 Make a list of students and the instruments they learn. (Natural Join)

SELECT s.class, s.name, s.id, m.type ; FROM student s, music m ; WHERE s.id=m.id ORDER BY class, name NATURAL JOIN / INNER JOIN Result eg. 25 Make a list of students and the instruments they learn. (Natural Join) eg. 25 Make a list of students and the instruments they learn. (Natural Join)

eg. 26 Find the number of students learning piano in each class. eg. 26 Find the number of students learning piano in each class. NATURAL JOIN Three Parts : (1)Natural Join. (2)Condition: m.type="Piano" (3)GROUP BY class

NATURAL JOIN Music Student Product Join Condition m.type= "Piano" Group By class eg. 26 eg. 26

eg. 26 Find the number of students learning piano in each class. eg. 26 Find the number of students learning piano in each class. SELECT s.class, COUNT(*) ; FROM student s, music m ; WHERE s.id=m.id AND m.type="Piano" ; GROUP BY class ORDER BY class NATURAL JOIN Result

An Outer Join is a join operation that includes rows that have a match, plus rows that do not have a match in the other table. Used when rows from one table should be part of the result there are no related rows in a second table Direction must be specified – Left/Right specify which table has the rows which should always be included – Full specifies that rows from both tables should be included even if no match between rows

Left Outer Join returns all matched rows, plus all unmatched rows from the table on the left of the join clause (use nulls in fields of non-matching tuples) SELECT s.sid, s.name, r.bid FROM Sailors s LEFT OUTER JOIN Reserves r ON s.sid = r.sid Returns all sailors & information on whether they have reserved boats

Right Outer Join returns all matched rows, plus all unmatched rows from the table on the right of the join clause SELECT r.sid, b.bid, b.name FROM Reserves r RIGHT OUTER JOIN Boats b ON r.bid = b.bid Returns all boats & information on which ones are reserved.

Full Outer Join returns all (matched or unmatched) rows from the tables on both sides of the join clause SELECT r.sid, b.bid, b.name FROM Reserves r FULL OUTER JOIN Boats b ON r.bid = b.bid Returns all boats & all information on reservations

Note: in this case it is the same as the ROJ because bid is a foreign key in reserves, so all reservations must have a corresponding tuple in boats.

 Typically used to generate lots of data quickly  Match each row from table 1 with every row from table 2  Result is (table 1 row count)*(table 2 row count)  Using table list: SELECT * FROM Publishers, Titles  Using CROSS JOIN keywords: SELECT * FROM Publishers CROSS JOIN Titles

 A subquery must be enclosed in the parenthesis.  A subquery must be put in the right hand of the comparison operator  A subquery cannot contain a ORDER-BY clause.  A query can contain more than one sub-queries.

 3 Subquery Types 1. Single-row subquery - where the subquery returns only one row. 2. Multiple-row subquery - where the subquery returns multiple rows. 3. Multiple column subquery - where the subquery returns multiple columns.  Another name for these query types is: Correlated Subquery.

Correlated Subqueries  Are dependent on the their outer query*  Will be executed many times while it’s outer queries is being processed, running once for each row selected by the outer query.  Can be in the HAVING OR WHERE clauses

SELECT s.store_name, sl.store_sales, FROM store s, sales sl WHERE s.store_key = sl.store_key and sl.store_sales >=( SELCECT AVG(store_sales) FROM sales)