Database Management Fall 2003 Midterm Review Chapters 1 & 2.

Slides:



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

© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
The Many-to-Many Relationship Fearful concatenation of circumstances Daniel Webster.
BUSINESS DRIVEN TECHNOLOGY Plug-In T4 Designing Database Applications.
The Many-to-Many Relationship. A sales form The many-to-many relationship Create a third entity to map an m:m relationship –An associative entity The.
The Many-to-Many Relationship Fearful concatenation of circumstances Daniel Webster.
Database Management Fall 2003 The one-to-one and recursive relationships.
One-to-One and Recursive Relationships Self-reflection is the school of wisdom Baltastar Gracián.
This presentation prepared for MIS 421 / MBA 575 at Western Washington University. Material in this presentation drawn from Richard T. Watson, Data Management:
The Relational Database Model
Data Modeling Man is a knot, a web, a mesh into which relationships are tied. Only those relationships matter Saint-Exupéry.
The Relational Database Model
The Relational Database Model:
The Relational Database Model. 2 Objectives How relational database model takes a logical view of data Understand how the relational model’s basic components.
Database Systems More SQL Database Design -- More SQL1.
3 1 Chapter 3 The Relational Database Model Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Chapter 11.1 and 11.2 Data Manipulation: Relational Algebra and SQL Brian Cobarrubia Introduction to Database Management Systems October 4, 2007.
Relational Databases What is a relational database? What would we use one for? What do they look like? How can we describe them? How can you create one?
Michael F. Price College of Business Chapter 6: Logical database design and the relational model.
DATA, DATABASES, AND QUERIES Managing Data in Relational Databases CS1100Microsoft Access - Introduction1.
3 The Relational Model MIS 304 Winter Class Objectives That the relational database model takes a logical view of data That the relational model’s.
The Relational Database Model
1 Nassau Community CollegeProf. Vincent Costa Acknowledgements: Introduction to Database Management, All Rights ReservedIntroduction to Database Management.
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.
Chapter 3 Single-Table Queries
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Database Management The single entity, the single table, plus some basic SQL.
Database. Basic Definitions Database: A collection of related data. Database Management System (DBMS): A software package/ system to facilitate the creation.
CHAPTER 8: MANAGING DATA RESOURCES. File Organization Terms Field: group of characters that represent something Record: group of related fields File:
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
The Relational Database Model
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
Dr Gordon Russell, Napier University Unit SQL 2 - V2.0 1 SQL 2 Unit 1.3.
1 Relational Databases and SQL. Learning Objectives Understand techniques to model complex accounting phenomena in an E-R diagram Develop E-R diagrams.
SQL- DQL (Oracle Version). 2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list]
3 1 Chapter 3 The Relational Database Model Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
Information Technologies and Microsoft SQL Server Day 2 by Alper Özpınar
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Concepts of Database Management, Fifth Edition Chapter 6: Database Design 2: Design Methodology.
3 1 Chapter 3 The Relational Database Model Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 3 The Relational Database Model.
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.
The Many-to-Many Relationship Fearful concatenation of circumstances Daniel Webster.
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.
Department of Mathematics Computer and Information Science1 CS 351: Database Systems Christopher I. G. Lanclos Chapter 3: The Relational Database Model.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
3 1 Database Systems The Relational Database Model.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Logical Database Design and the Relational Model.
3 1 Chapter 3 The Relational Database Model Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
Query Processing – Implementing Set Operations and Joins Chap. 19.
One-to-One and Recursive Relationships Self-reflection is the school of wisdom Baltastar Gracián.
CHAPTER 2 : RELATIONAL DATA MODEL Prepared by : nbs.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 3 The Relational Database Model.
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.
Rationale Databases are an integral part of an organization. Aspiring Database Developers should be able to efficiently design and implement databases.
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
More SQL: Complex Queries,
The Relational Database Model
The Many-to-Many Relationship
One-to-One and Recursive Relationships
One-to-One and Recursive Relationships
The Many-to-Many Relationship
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Database Systems: Design, Implementation, and Management
Presentation transcript:

Database Management Fall 2003 Midterm Review Chapters 1 & 2

Desirable attributes: o shareable o transportable osecure oaccurate otimely orelevant Management of data Typical problems: o redundancy oinconsistency o lack of control oaccess problems -poor interfaces -long delays olack of richness olack of integration

Relational Databases E F Codd, 1970 Hierarchical systems –Redundant –Difficult to maintain –Costly Relational –Relations = Grouping of related data (tables) –Data stored only once –Query language for accessing data

Database Management Systems TSP (Transaction Processing System) –Many transactions –Short transactions –Volatile data Decision Support –Data Warehouse, Data Mining –Fewer transactions –Longer transactions –Static data

Database Management System Design Design decisions have significant future impact Reliability Scalability Security

Sample Questions 1.Name 3 undesirable attributes of data. 2.Which of the following are desirable attributes of data? 1.Timely 2.Numeric 3.Redundant 4.Accurate 3.Describe one way in which transaction processing databases differ from decision support databases. 4.Describe one advantage that relation database systems (RDBMS) have over traditional flat-file databases.

Chapter 3 The single entity, the single table, plus some basic SQL

Essential Terminology Entity A category representing a type of person, place, thing or event. In the OO world, this is called a “class.” Relation A two-dimensional table, with rows (or records) representing real-world instances of the entity in question, and columns (or fields) representing the attributes of interest. Identifier (primary key) A field (or combination of fields) that takes on a unique value for each record in the relation, and is used to distinguish that record from all others.

Primary Key Unique Not Null Null No Value Not zero Not empty string, “”

Data modeling – representing the single entity Watson’s looks like this: Ours will look like this: Underline = primary key Asterix = primary key

o An entity in the data model becomes a table (relation) in the database. o The attributes of the entity in the data model become the fields (columns) in the table in the database. o The entity’s unique identifier in the data model becomes the table’s primary key in the database. Plus: Instances are represented by records (rows) in the table. Database design for beginners:

The select statement SELECT col1, col2, … FROM table1, table2, … [ WHERE search_condition AND search_condition OR search_condition] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ]]

The SELECT statement: Retrieving records.  Retrieving selected fields, or “projection.”  Retrieving selected records, or “restriction” (WHERE clause, logical AND, logical OR, comparison operators, IN & NOT IN).  Ordering columns.  Ordering records (ORDER BY, DESC).  Derived data through SQL functions (COUNT, AVG, SUM, MIN, MAX).  Creating an alias for a results column (AS)  Pattern matching (LIKE, %, _ )  Eliminating duplicate records (DISTINCT) Query Options

Query Functions and Operators Arithmetic: + - * / Aggregate: sum, avg, max, min Comparison: =, =, >, between Logical: not, or, and Set: count, distinct, in

Report a firm’s name and price–earnings ratio. SELECT shrfirm, shrpe FROM shr Get all firms with a price-earnings ratio less than 12. SELECT * FROM shr WHERE shrpe < 12 Report firms whose code is AR. SELECT * FROM shr WHERE shrcode = 'AR' Report data on firms with codes of FC, AR, or SLG. SELECT * FROM shr WHERE shrcode IN ('FC','AR','SLG') List all firms where PE is at least 12, and order by descending PE. SELECT * FROM shr WHERE shrpe >= 12 ORDER BY shrpe DESC List all firms with a name starting with ‘F’. SELECT shrfirm FROM shr WHERE shrfirm LIKE 'F%' Find the number of different PE ratios. SELECT COUNT(DISTINCT shrpe) AS ‘Unique PE' FROM shr

Sample Questions 1.Find all shares where the firm name begins with 'B’ 2.Find all shares where the total dividend is greater than 20,000 3.Find the P/E ratio for the firms Freedonia Copper and Canadian Sugar 4.Display all details of shares in descending order of the share price

Solutions 1.select * from shr where shrfirm like 'B%' 2.select shrfirm, shrqty*shrdiv as dividend from shr where shrqty*shrdiv > select shrpe from shr where shrcode in ('FC', 'CS') -- or 3. select shrpe from shr where shrcode = 'FC' or shrcode = 'CS' 4. select * from shr order by shrprice desc

Chapter 4 The one-to-many relationship Joins, Views, Subqueries & Group by

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

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

Sample Questions 1.Draw a data model for the following scenarios: A.A bank tracks it’s customers’ bank accounts. Each customer may have multiple bank accounts, but each account belongs to only one customer. B.A library database has book titles and authors. Each author may have one or more books, but each book has only one author. 2.Select the name and total value of all firms in the USA converted to English pounds 3.Which of the following select statements displays the nations where the total number of shares is more than 200,000: A.select natcode, sum(stkqty) from stock group by natcode where sum(stkqty) > B.select natcode, sum(stkqty) from stock where sum(stkqty) > group by natcode C. select natcode, sum(stkqty) from stock group by natcode having sum(stkqty) > D select natcode, sum(stkqty) from stock group by natcode having stkqty > What is a foreign key and what is it used for?

Solutions select stkfirm, stkqty*stkprice*exchrate from stock, nation where stock.natcode = nation.natcode and nation.natcode = 'USA' 3. C 4. A foreign key is a column that refers to a primary key in another table. It is used to create a one-to-many relationship

Chapter 5 The many-to-many relationship: data modeling and some SQL

M:M relationships are common in business… consider a “classic” – the sale of products. A relational DBMS doesn’t “understand” the M:M… so you need a third entity as a “go-between”, commonly called: an associative entity You need an associative entity wherever you have a M:M… but often the data (attributes) that belong to the associative entity make it obvious that it’s needed. Why the M:M relationship… and why are there actually three entities?

Data modeling – the M:M relationship Us: Watson:

o Doing a three-table join using a pair of conditions in the WHERE clause brought together by an AND – to join the table for the associative entity to each of its companions. o Using EXISTS in connection with a subquery to determine which records on the 1 side of a 1:M have a relationship with one or more records on the M side. o Combining NOT and EXISTS in connection with a subquery to determine which records on the 1 side of a 1:M have no relationships with any records on the M side. o Using UNION to bring together the results of two separate SELECT statements (i.e., logical-OR). More SQL

The many-to-many relationship Create a third entity to map an m:m relationship –An associative entity The vertical bar on the crow's foot indicates that LINEITEM is identified by concatenating saleno and lineno SALE *saleno saledate saletext LINEITEM *lineno lineqty lineprice ITEM *itemno itemname itemtype itemcolor

A three table join List the names of the three tables after FROM Specify two matching conditions with the associative table in both join conditions SELECT * FROM sale, lineitem, item WHERE sale.saleno = lineitem.saleno AND item.itemno = lineitem.itemno;

A three table join List the names of items, quantity, and value of items sold on January 16, 2003 SELECT itemname, lineqty, lineprice, lineqty*lineprice AS total FROM sale, lineitem, item WHERE lineitem.saleno = sale.saleno AND item.itemno = lineitem.itemno AND saledate = ' '; itemnamelineqtylinepricetotal Pocket knife—Avon10.00 Safari chair Hammock Tent—8 person Tent—2 person160.00

EXISTS Existential qualifier Returns true or false Returns true if the table contains at least one row satisfying the specified condition Report all clothing items (type “C”) for which a sale is recorded SELECT itemname, itemcolor FROM item WHERE itemtype = 'C' AND EXISTS (SELECT * FROM lineitem WHERE lineitem.itemno = item.itemno); itemnameitemcolor Hat—Polar ExplorerRed Boots—snake proofBlack Pith helmetWhite StetsonBlack

NOT EXISTS Returns true if the table contains no rows satisfying the specified condition Report all clothing items (type “C”) that have not been sold SELECT itemname, itemcolor FROM item WHERE itemtype = 'C' AND NOT EXISTS (SELECT * FROM lineitem WHERE item.itemno = lineitem.itemno); itemnameitemcolor Hat—Polar ExplorerWhite Boots—snake proofGreen Pith helmetKhaki StetsonBrown

itemname Hammock Map case Pocket knife—Avon Pocket knife—Nile Safari chair Stetson Tent—2 person Tent—8 person UNION List all items that were sold on January 16, 2003, or are brown. SELECT itemname FROM item, lineitem, sale WHERE item.itemno = lineitem.itemno AND lineitem.saleno = sale.saleno AND saledate = ' ' UNION SELECT itemname FROM item WHERE itemcolor = 'Brown ';

Sample Questions 1.Draw a data model for the following: An employee database records timesheet information. A timesheet entry records the number of hours worked in a particular day for an employee. Each month is a pay period identified by month and year. Each employee will have entries for many pay periods and for each pay period there are many timesheet entries. 2.Write the SQL code to determine how many clothing items were sold on Jan 15, 1995

3. Which SQL statement displays the sales where no black item was sold? A. select sale.saleno from item, lineitem, sale where item.itemno = lineitem.itemno and lineitem.saleno = sale.saleno and not exists (select sale.saleno from item, lineitem, sale where item.itemno = lineitem.itemno and lineitem.saleno = sale.saleno and item.itemcolor = 'Black') B. select a.saleno from item, lineitem, sale a where item.itemno = lineitem.itemno and lineitem.saleno = a.saleno and not exists (select b.saleno from item, lineitem, sale b where item.itemno = lineitem.itemno and lineitem.saleno = b.saleno and a.saleno = b.saleno and item.itemcolor = 'Black') C. select sale.saleno from item, lineitem, sale where item.itemno = lineitem.itemno and lineitem.saleno = sale.saleno and itemcolor <> 'BLACK'

Solutions select count(*) from item, lineitem, sale where item.itemno = lineitem.itemno and lineitem.saleno = sale.saleno and item.itemtype = 'C' and sale.saledate = ' ' 3. B

Chapter 6 The one-to-one and recursive relationships

Modeling a 1:1 relationship 1:1 relationship is labeled –A relationship descriptor Obvious relationships are not labeled DEPT deptname deptfloor deptphon e Department ’ s boss EMP empno empfname empsalary empno (FK) deptname (FK)

Modeling a recursive relationship A recursive relationship relates an entity to itself Label recursive relationships See Watson, p. 137 This recursive relationship is one-to-many

Querying a recursive relationship Use table aliases to join table to itself. Find the salary of Nancy’s boss. SELECT wrk.empfname, wrk.empsalary, boss.empfname, boss.empsalary FROM emp wrk, emp boss WHERE wrk.empfname = 'Nancy' AND wrk.bossno = boss.empno; wrk.empfnamewrk.empsalaryboss.empfnameboss.empsalary Nancy22000Todd3800

Querying a recursive relationship Another perspective: display all data in a single row. Find the names of employees who earn more than their boss. SELECT wrk.empfname FROM emp wrk, emp boss WHERE wrk.bossno = boss.empno AND wrk.empsalary > boss.empsalary; wrkboss empnoempfnameempsalarydeptnamebossnoempnoempfnameempsalarydeptnamebossno 2Ned45,000Marketing11Alice75,000Management 3Andrew25,000Marketing22Ned45,000Marketing1 4Clare22,000Marketing22Ned45,000Marketing1 5Todd38,000Accounting11Alice75,000Management 6Nancy22,000Accounting55Todd38,000Accounting1 7Brier43,000Purchasing11Alice75,000Management 8Sarah56,000Purchasing77Brier43,000Purchasing1 9Sophie35,000Personnel & PR11Alice75,000Management empfname Sarah

Modeling a 1:1 recursive relationship The English monarchy succession MONARCH monarch type monarch name monarch number reign begin date previous mon name (FK) previous mon number (FK)

The m:m recursive relationship … See Watson, p. 146 Bill of materials (bom) problem A product can appear as part of many other products and can be made up of many products

Querying an m:m recursive relationship List the product identifier of each component of the animal photography kit. SELECT subprodid FROM product, assembly WHERE proddesc = 'Animal photography kit' AND product.prodid = assembly.prodid; subprodid

Querying an m:m recursive relationship List the product description and cost of each component of the animal photography kit. SELECT proddesc, prodcost FROM product WHERE prodid IN (SELECT subprodid FROM product, assembly WHERE proddesc = 'Animal photography kit' AND product.prodid = assembly.prodid); proddescprodcost 35mm camera Camera case zoom lens zoom lens Photographer’s vest25.00 Lens cleaning cloth1.00 Tripod exp. 100ASA 35mm col neg0.85

Sample Questions 1.list the name of each employee and their manager 2.Model the relationship where employees may have a mentor who is also an employee. Each employee has at most one mentor or is the mentor of at most one employee.

Solutions 1. select wrk.empfname as employee, boss.empfname as manager from emp wrk, emp boss where wrk.bossno = boss.empno 2.

Chapter 7 Ternary relationships and subtyping

Degree of relationship: unary vs. binary vs. ternary

Car Rental Agency Example AGENT agentid CUSTOMER custid AUTOMOBILE autoid AUTOMOBILE- AGENT AUTOMOBILE- CUSTOMER AGENT- CUSTOMER autoid (FK) custid (FK) autoid (FK) agentid (FK) custid (FK) custname custaddress automake automodel agentname agentloc Problem: where does car rental information belong?

A ternary relationship… (Watson, Chapter 7) (here, an associative entity implements a ternary relationship) AUTOMOBILE autoid AGENT... Customer custid LEASE autoid (FK) agentid... agentid (FK) custid (FK)

The building blocks Entity Attribute Relationship Identifier

Entity types Independent Dependent Associative Aggregate Subordinate

Independent Often a starting point Prominent in the client's mind Often related to other independent entities Can exist on their own

Dependent Relies on another entity for its existence and identification Can become independent if given an arbitrary identifier REGION regname regpop regarea … CITY cityname citypop cityarea … regname

Associative A by-product of an m:m relationship Typically between independent entities Can store current or historical data Can become independent if given an arbitrary identifier

Aggregate Created from several different entities that have a common prefix or suffix Commonly used with addresses or names

Subordinate An entity with data that can vary among instances

Sample Questions 1.Name 3 basic building blocks of a data model 2.What kind of entity is Registration in the model below? A.Independent B.Dependent C.Subordinate D.Associative

Solutions 1. Entity Attribute Relationship Identifier 2. D