Presentation is loading. Please wait.

Presentation is loading. Please wait.

Database Management Fall 2003 Midterm Review Chapters 1 & 2.

Similar presentations


Presentation on theme: "Database Management Fall 2003 Midterm Review Chapters 1 & 2."— Presentation transcript:

1 Database Management Fall 2003 Midterm Review Chapters 1 & 2

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

3 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

4 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

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

6 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.

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

8 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.

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

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

11 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:

12 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 ]]

13 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

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

15 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

16 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

17 Solutions 1.select * from shr where shrfirm like 'B%' 2.select shrfirm, shrqty*shrdiv as dividend from shr where shrqty*shrdiv > 20000 3. 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

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

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

20 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

21 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

22 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

23 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) > 200000 B.select natcode, sum(stkqty) from stock where sum(stkqty) > 200000 group by natcode C. select natcode, sum(stkqty) from stock group by natcode having sum(stkqty) > 200000 D select natcode, sum(stkqty) from stock group by natcode having stkqty > 200000 4. What is a foreign key and what is it used for?

24 Solutions 1. 2. 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

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

26 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?

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

28 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

29 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

30 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;

31 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 = '2003-01-16'; itemnamelineqtylinepricetotal Pocket knife—Avon10.00 Safari chair5036.001800.00 Hammock5040.502025.00 Tent—8 person8153.001224.00 Tent—2 person160.00

32 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

33 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

34 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 = '2003-01-16' UNION SELECT itemname FROM item WHERE itemcolor = 'Brown ';

35 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

36 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'

37 Solutions 1. 2. select count(*) from item, lineitem, sale where item.itemno = lineitem.itemno and lineitem.saleno = sale.saleno and item.itemtype = 'C' and sale.saledate = '01-15-1995' 3. B

38 Chapter 6 The one-to-one and recursive relationships

39 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)

40 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

41 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

42 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

43 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)

44 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

45 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 101 106 107 105 104 103 102 108

46 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 camera150.00 Camera case10.00 70-210 zoom lens125.00 28-85 zoom lens115.00 Photographer’s vest25.00 Lens cleaning cloth1.00 Tripod35.00 24 exp. 100ASA 35mm col neg0.85

47 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.

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

49 Chapter 7 Ternary relationships and subtyping

50 Degree of relationship: unary vs. binary vs. ternary

51 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?

52 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)

53 The building blocks Entity Attribute Relationship Identifier

54 Entity types Independent Dependent Associative Aggregate Subordinate

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

56 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

57 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

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

59 Subordinate An entity with data that can vary among instances

60 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

61 Solutions 1. Entity Attribute Relationship Identifier 2. D


Download ppt "Database Management Fall 2003 Midterm Review Chapters 1 & 2."

Similar presentations


Ads by Google