Relational Model: Advanced Topics Chapter 4 Views An individual user’s, or an application program’s picture of the database. You can think of it as a saved query. It provides a measure of security – omitting sensitive tables or fields. Example • This might be used for a salesperson’s view: CREATE VIEW Housewares AS SELECT PartNum, Description, OnHand, Price FROM Part WHERE Class = ‘HW’ ; The salesperson could write this query of the view: SELECT * FROM Housewares WHERE OnHand < 25 ; What really happens in the DBMS is: SELECT PartNum, Description, OnHand, Price FROM Part WHERE Class = ‘HW’ AND OnHand < 25 ; • To the salesperson, it seems like he’s using a table named Housewares. • Any update to the Part table is immediately visible in the Housewares view (because it’s not really a table). • In Access, to make a view, create & save query. – Forms & Reports can be driven by views. CREATE VIEW Housewares (PNum, PDesc, OnHd, Price) AS SELECT PartNum, Description, OnHand, Price FROM Part WHERE Class = ‘HW’ ; This gives the salesperson a customized view, with different field names he might prefer. Views can join tables CREATE VIEW SalesCust (SNum, SLast, SFirst, CNum, CName) AS SELECT Rep.RepNum, LastName, FirstName, CustomerNum, CustomerName FROM Rep, Customer WHERE Rep.RepNum = Customer.RepNum ; A query might be written: SELECT SNum, SLast, SFirst FROM SalesCust WHERE CNum = ‘282’; An example of a query in code… Indexes • Like finding something quickly in a book. • Indexing can speed up the database performance. • Happens behind the scenes – its used by the DBMS, not the user. • Most helpful where tables have thousands, tens of thousands, or hundreds of thousands of records.. CreditLimit Index CreditLimit RecordNum $5,000 4,8 $7,500 1,3,9,10 $10,000 2,5,7 $15,000 6 Security • Assigning privileges to different users GRANT SELECT on Customer TO Jones GRANT INSERT ON Part TO Smith, Park Integrity Rules • Entity Integrity – No field that is part of a primary key can be NULL. – NULLs are when a value is missing, unknown or inapplicable Referential Integrity • Relationships are not very obvious. • Picture a DB with 20 tables, where tables have 30 fields. • Foreign Key FOREIGN KEY (RepNum) REFERENCES Rep In the customer table If they don’t match (perhaps a rep has been deleted)- then referential integrity is compromised. Structure Changes ALTER TABLE Customer ADD CustType CHAR(1) ALTER TABLE Customer CHANGE COLUMN CustomerName TO CHAR(40) ALTER TABLE Part DELETE Warehouse DROP TABLE SmallCust Many to Many Relationships • Students to Teachers • Products to Categories • Musicians to Bands Need 3 Tables Musicians (musicianID, name, …) Bands (bandID, name, label…) Musicians_bands (musicianID, bandID)