Database Management Fall 2003 The one-to-many relationship Joins, Views, Subqueries & Group by.

Slides:



Advertisements
Similar presentations
DB glossary (focus on typical SQL RDBMS, not XQuery or SPARQL)
Advertisements

© Abdou Illia MIS Spring 2014
February 18, 2012 Lesson 3 Standard SQL. Lesson 3 Standard SQL.
The One-to-Many Relationship. The one-to-many relationship Entities are related to other entities A 1:m relationship.
The One-to-Many Relationship Cow of many-well milked and badly fed Spanish proverb.
The single entity. Modeling reality A database must mirror the real world if it is to answer questions about the real world Data modeling is a design.
The Relational Database Model
Relational Databases Chapter 4.
Midterm Review Lecture 14b. 14 Lectures So Far 1.Introduction 2.The Relational Model 3.Disks and Files 4.Relational Algebra 5.File Org, Indexes 6.Relational.
Fundamentals, Design, and Implementation, 9/e Chapter 4 The Relational Model and Normalization.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
Database Design Conceptual –identify important entities and relationships –determine attribute domains and candidate keys –draw the E-R diagram Logical.
SQL The questing beast Sir Thomas Mallory. SQL A standard ANSI ISO SQL skills are in demand Developed by IBM Object-oriented extensions created.
Populating and Querying tables Insert and mostly View (DML)
RELATIONSHIP  THE WAY TABLES ARE RELATED  A TABLE MUST PARTICIPATE IN AT LEAST ONE RELATIONSHIP  IN A BINARY RELATIONSHIP TWO ENTITIES PARTICIPATE 
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 7 Using SQL in Applications.
Database Systems More SQL Database Design -- More SQL1.
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
Define Table Relationships—1 of 3 One of the most powerful features of a relational database management system, such as Access, is its ability to define.
This presentation prepared for MIS 421 / MBA 575 at Western Washington University. Material in this presentation drawn from Richard T. Watson, Data Management:
Chapter 4 The Relational Model.
The single entity I want to be alone Greta Garbo.
The single entity I want to be alone Greta Garbo.
Chapter 3 Single-Table Queries
Database Management The single entity, the single table, plus some basic SQL.
Learningcomputer.com SQL Server 2008 – Entity Relationships in a Database.
Component 4/Unit 6f Topic VI: Create simple querying statements for the database The SELECT statement Clauses Functions Joins Subqueries Data manipulation.
Microsoft Access 2003 Define some key Access terminology: Field – A single characteristic or attribute of a person, place, object, event, or idea. Record.
Constraints  Constraints are used to enforce rules at table level.  Constraints prevent the deletion of a table if there is dependencies.  The following.
MIS 301 Information Systems in Organizations Dave Salisbury ( )
IE 423 – Design of Decision Support Systems Database development – Relationships and Queries.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
RDBMSSection Relational DBMS DATABASE DEVELOPMENT And Franchise Colleges By MANSHA NAWAZ.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Using Special Operators (LIKE and IN)
One-to-many relationship Relational databases link several entities based on relationships that exist (based on modeling reality) 1:m relationship example:
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
Microsoft Access Intro Class 6 Relationships.
Access 2007 ® Use Databases How can Microsoft Access 2007 help you structure your database?
Pasewark & Pasewark 1 Access Lesson 3 Creating Queries Microsoft Office 2007: Introductory.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
SQL LANGUAGE and Relational Data Model TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 16 Using Relational Databases.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
Views, Algebra Temporary Tables. Definition of a view A view is a virtual table which does not physically hold data but instead acts like a window into.
Physical Database Design Purpose- translate the logical description of data into the technical specifications for storing and retrieving data Goal - create.
MIS 3053 Database Design And Applications The University Of Tulsa Professor: Akhilesh Bajaj Normal Forms Lecture 1 © Akhilesh Bajaj, 2000, 2002, 2003.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
The One-to-Many Relationship Cow of many-well milked and badly fed Spanish proverb.
Query Processing – Implementing Set Operations and Joins Chap. 19.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
Mapping ER to Relational Model Each strong entity set becomes a table. Each weak entity set also becomes a table by adding primary key of owner entity.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Microsoft Access CS 110 Fall Entity Relationship Model Entities Entities Principal data object about which information is to be collectedPrincipal.
 MySQL  DDL ◦ Create ◦ Alter  DML ◦ Insert ◦ Select ◦ Update ◦ Delete  DDL(again) ◦ Drop ◦ Truncate.
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
I want to be alone Greta Garbo
The questing beast Sir Thomas Mallory
The One-to-Many Relationship
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
The Relational Model Textbook /7/2018.
The questing beast Sir Thomas Mallory
CMSC-461 Database Management Systems
Manipulating Data Lesson 3.
Presentation transcript:

Database Management Fall 2003 The one-to-many relationship Joins, Views, Subqueries & Group by

stock stkcodestkfirmstkpricestkqtystkdivstkpe FCFreedonia Copper PTPatagonian Tea ARAbyssinian Ruby SLGSri Lankan Gold ILZIndian Lead &Zinc BEBurmese Elephant BSBolivian Sheep NGNigerian Geese CSCanadian Sugar ROFRoyal Ostrich Farms MGMinnesota Gold GPGeorgia Peach NENarembeen Emu QDQueensland Diamond IRIndooroopilly Ruby BDBombay Duck Add exchange rate information

stock stkcodestkfirmstkpricestkqtystkdivstkpenatnameexchrate FCFreedonia Copper United Kingdom1.00 PTPatagonian Tea United Kingdom1.00 ARAbyssinian Ruby United Kingdom1.00 SLGSri Lankan Gold United Kingdom1.00 ILZIndian Lead &Zinc United Kingdom1.00 BEBurmese Elephant United Kingdom1.00 BSBolivian Sheep United Kingdom1.00 NGNigerian Geese United Kingdom1.00 CSCanadian Sugar United Kingdom1.00 ROFRoyal Ostrich Farms United Kingdom1.00 MGMinnesota Gold USA0.67 GPGeorgia Peach USA0.67 NENarembeen Emu Australia0.46 QDQueensland Diamond Australia0.46 IRIndooroopilly Ruby Australia0.46 BDBombay Duck India

stock stkcodestkfirmstkpricestkqtystkdivstkpenatnameexchrate FCFreedonia Copper United Kingdom1.00 PTPatagonian Tea United Kingdom1.00 ARAbyssinian Ruby United Kingdom1.00 SLGSri Lankan Gold United Kingdom1.00 ILZIndian Lead &Zinc United Kingdom1.00 BEBurmese Elephant United Kingdom1.00 BSBolivian Sheep United Kingdom1.00 NGNigerian Geese United Kingdom1.00 CSCanadian Sugar United Kingdom1.00 ROFRoyal Ostrich Farms United Kingdom1.00 MGMinnesota Gold USA0.67 GPGeorgia Peach USA0.67 NENarembeen Emu Australia 0.51 QDQueensland Diamond Australia0.46 IRIndooroopilly Ruby Australia0.46 BDBombay Duck India Update Anomaly

stock stkcodestkfirmstkpricestkqtystkdivstkpenatnameexchrate FCFreedonia Copper United Kingdom1.00 PTPatagonian Tea United Kingdom1.00 ARAbyssinian Ruby United Kingdom1.00 SLGSri Lankan Gold United Kingdom1.00 ILZIndian Lead &Zinc United Kingdom1.00 BEBurmese Elephant United Kingdom1.00 BSBolivian Sheep United Kingdom1.00 NGNigerian Geese United Kingdom1.00 CSCanadian Sugar United Kingdom1.00 ROFRoyal Ostrich Farms United Kingdom1.00 Japan0.85 MGMinnesota Gold USA0.67 GPGeorgia Peach USA0.67 NENarembeen Emu Australia0.46 QDQueensland Diamond Australia0.46 IRIndooroopilly Ruby Australia0.46 BDBombay Duck India Insert Anomaly

stock stkcodestkfirmstkpricestkqtystkdivstkpenatnameexchrate FCFreedonia Copper United Kingdom1.00 PTPatagonian Tea United Kingdom1.00 ARAbyssinian Ruby United Kingdom1.00 SLGSri Lankan Gold United Kingdom1.00 ILZIndian Lead &Zinc United Kingdom1.00 BEBurmese Elephant United Kingdom1.00 BSBolivian Sheep United Kingdom1.00 NGNigerian Geese United Kingdom1.00 CSCanadian Sugar United Kingdom1.00 ROFRoyal Ostrich Farms United Kingdom1.00 MGMinnesota Gold USA0.67 GPGeorgia Peach USA0.67 NENarembeen Emu Australia0.46 QDQueensland Diamond Australia0.46 IRIndooroopilly Ruby Australia0.46 Delete Anomaly – India exchrate data lost

NATION and STOCK nation natcodenatnameexchrate UKUnited Kingdom1.00 USAUnited States0.67 AUSAustralia0.46 INDIndia stock stkcodestkfirmstkpricestkqtystkdivstkpenatcode FCFreedonia Copper UK PTPatagonian Tea UK ARAbyssinian Ruby UK SLGSri Lankan Gold UK ILZIndian Lead &Zinc UK BEBurmese Elephant UK BSBolivian Sheep UK NGNigerian Geese UK CSCanadian Sugar UK ROFRoyal Ostrich Farms UK MGMinnesota Gold USA GPGeorgia Peach USA NENarembeen Emu AUS QDQueensland Diamond AUS IRIndooroopilly Ruby AUS BDBombay Duck IND Foreign Key

nation natcodenatnameexchrate UKUnited Kingdom1.00 USAUnited States0.67 AUSAustralia 0.51 INDIndia stock stkcodestkfirmstkpricestkqtystkdivstkpenatcode FCFreedonia Copper UK PTPatagonian Tea UK ARAbyssinian Ruby UK SLGSri Lankan Gold UK ILZIndian Lead &Zinc UK BEBurmese Elephant UK BSBolivian Sheep UK NGNigerian Geese UK CSCanadian Sugar UK ROFRoyal Ostrich Farms UK MGMinnesota Gold USA GPGeorgia Peach USA NENarembeen Emu AUS QDQueensland Diamond AUS IRIndooroopilly Ruby AUS BDBombay Duck IND Update anomaly eliminated

nation natcodenatnameexchrate UKUnited Kingdom1.00 USAUnited States0.67 AUSAustralia0.46 INDIndia JPJapan0.85 stock stkcodestkfirmstkpricestkqtystkdivstkpenatcode FCFreedonia Copper UK PTPatagonian Tea UK ARAbyssinian Ruby UK SLGSri Lankan Gold UK ILZIndian Lead &Zinc UK BEBurmese Elephant UK BSBolivian Sheep UK NGNigerian Geese UK CSCanadian Sugar UK ROFRoyal Ostrich Farms UK MGMinnesota Gold USA GPGeorgia Peach USA NENarembeen Emu AUS QDQueensland Diamond AUS IRIndooroopilly Ruby AUS BDBombay Duck IND Insert anomaly eliminated

nation natcodenatnameexchrate UKUnited Kingdom1.00 USAUnited States0.67 AUSAustralia0.46 INDIndia stock stkcodestkfirmstkpricestkqtystkdivstkpenatcode FCFreedonia Copper UK PTPatagonian Tea UK ARAbyssinian Ruby UK SLGSri Lankan Gold UK ILZIndian Lead &Zinc UK BEBurmese Elephant UK BSBolivian Sheep UK NGNigerian Geese UK CSCanadian Sugar UK ROFRoyal Ostrich Farms UK MGMinnesota Gold USA GPGeorgia Peach USA NENarembeen Emu AUS QDQueensland Diamond AUS IRIndooroopilly Ruby AUS Delete anomaly eliminated

Data modeling – representing the 1:M relationship Watson’s looks like this: Ours will look like this:

Foreign keys A foreign key is a column that is a primary key of another table –natcode in stock is a foreign key because natcode is the primary key of nation Record a 1:m relationship the foreign key goes on the M side foreign key-primary key matching Names for a foreign key and the corresponding primary key are often the same, but not always

Referential integrity constraint For every value of a foreign key there is a primary key with that value For every value of natcode in stock there is a value of natcode in nation A foreign key can never be null A primary key must exist before the foreign key can be defined –Must create the nation before its stocks

Creating the tables CREATE TABLE nation ( natcodeCHAR(3), natnameVARCHAR(20), exchrateDECIMAL(9,5), PRIMARY KEY (natcode)); CREATE TABLE stock ( stkcodeCHAR(3), stkfirmVARCHAR(20), stkpriceDECIMAL(6,2), stkqtyDECIMAL(8), stkdivDECIMAL(5,2), stkpeDECIMAL(5), natcodeCHAR(3), PRIMARY KEY(stkcode), CONSTRAINT fk_stock_nation FOREIGN KEY(natcode) REFERENCES nation)

o Doing a join using WHERE with = (an equijoin) and qualification. o Using GROUP BY with one or more operations (e.g., COUNT, SUM) that produce a single result (results row) for each group. o Using HAVING (functionally similar to WHERE) to pick a subset of the groups identified by a GROUP BY. o Using a subquery (inner query, nested SELECT) to define a condition to evaluate in the WHERE clause of an outer query. Also – the correlated subquery. o Using CREATE VIEW to create a view or virtual table. Other basic SQL

stkcodestkfirmstkpricestkqtystkdivstkpenatcodenatcode1natnameexchrate NENarembeen Emu AUS Australia IRIndooroopilly Ruby AUS Australia QDQueensland Diamond AUS Australia BDBombay Duck IND India ROFRoyal Ostrich Farms UK United Kingdom CSCanadian Sugar UK United Kingdom FCFreedonia Copper UK United Kingdom BSBolivian Sheep UK United Kingdom BEBurmese Elephant UK United Kingdom ILZIndian Lead & Zinc UK United Kingdom SLGSri Lankan Gold UK United Kingdom ARAbyssinian Ruby UK United Kingdom PTPatagonian Tea UK United Kingdom NGNigerian Geese UK United Kingdom MGMinnesota Gold US United States GPGeorgia Peach US United States Join Create a new table from two existing tables by matching on a common column SELECT * FROM stock, nation WHERE stock.natcode = nation.natcode

Report the value of each stock holding in UK pounds. Sort the report by nation and firm. SELECT natname, stkfirm, stkprice, stkqty, exchrate, stkprice*stkqty*exchrate AS stkvalue FROM stock, nation WHERE stock.natcode = nation.natcode ORDER BY natname, stkfirm Join

natnamestkfirmstkpricestkqtyexchratestkvalue AustraliaIndooroopilly Ruby AustraliaNarembeen Emu AustraliaQueensland Diamond IndiaBombay Duck United KingdomAbyssinian Ruby United KingdomBolivian Sheep United KingdomBurmese Elephant United KingdomCanadian Sugar United KingdomFreedonia Copper United KingdomIndian Lead & Zinc United KingdomNigerian Geese United KingdomPatagonian Tea United KingdomRoyal Ostrich Farms United KingdomSri Lankan Gold United StatesGeorgia Peach United StatesMinnesota Gold

GROUP BY - reporting by groups Report by nation the total value of stockholdings. SELECT natname, SUM(stkprice*stkqty*exchrate) AS stkvalue FROM stock, nation WHERE stock.natcode = nation.natcode GROUP BY natname natnamestkvalue Australia India United Kingdom United States

HAVING - the WHERE clause of groups Report the total value of stocks for nations with two or more listed stocks. SELECT natname, SUM(stkprice*stkqty*exchrate) AS stkvalue FROM stock, nation WHERE stock.natcode = nation.natcode GROUP BY natname HAVING COUNT(*) >= 2; natnamestkvalue Australia United Kingdom United States

Subqueries A query nested within another query Report the names of all Australian stocks: SELECT stkfirm FROM stock WHERE natcode IN (SELECT natcode FROM nation WHERE natname = 'Australia') stkfirm Narembeen Emu Queensland Diamond Indooroopilly Ruby

Correlated subquery Solves the inner query many times Find those stocks where the quantity is greater than the average for that country: SELECT natname, stkfirm, stkqty FROM stock, nation WHERE stock.natcode = nation.natcode AND stkqty > (SELECT AVG(stkqty) FROM stock WHERE stock.natcode = nation.natcode) natnamestkfirmstkqty AustraliaQueensland Diamond89251 United KingdomBolivian Sheep United KingdomRoyal Ostrich Farms United StatesMinnesota Gold816122

Views - virtual tables An imaginary table constructed by the DBMS when required Only the definition of the view is stored, not the result CREATE VIEW stkvalue (nation, firm, price, qty, exchrate, value) AS SELECT natname, stkfirm, stkprice, stkqty, exchrate, stkprice*stkqty*exchrate FROM stock, nation WHERE stock.natcode = nation.natcode

Views - querying Query exactly as if a table SELECT nation, firm FROM stkvalue WHERE value > nationfirm AustraliaNarembeen Emu AustraliaIndooroopilly Ruby AustraliaQueensland Diamond United KingdomRoyal Ostrich Farms United KingdomCanadian Sugar United KingdomFreedonia Copper United KingdomBolivian Sheep United KingdomIndian Lead & Zinc United KingdomSri Lankan Gold United KingdomAbyssinian Ruby United KingdomPatagonian Tea United KingdomNigerian Geese United StatesMinnesota Gold United StatesGeorgia Peach

Key ideas (… so to speak) o the foreign key goes on the M side othe foreign key doesn’t go on the 1 side (this would create a multi-valued attribute – bad) o foreign key-primary key matching o names for a foreign key and the corresponding primary key are often the same, but not always oreferential integrity constraint: … when a record (row) on the M side references a record on the 1 side, the latter must exist! This implies that the 1-side record must be added first; it also implies that it cannot be deleted as long as any record on the M side references it. Implementing the 1:M relationship in the actual database …