1 / 42

DB Modifications

DB Modifications. Modification = insert + delete + update. Insertion of a Tuple INSERT INTO relation VALUES (list of values). Inserts the tuple = list of values, associating values with attributes in the order the attributes were declared.

kendall
Download Presentation

DB Modifications

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. DB Modifications • Modification = insert + delete + update. Insertion of a Tuple INSERT INTO relation VALUES (list of values). • Inserts the tuple = list of values, associating values with attributes in the order the attributes were declared. • Forget the order? List the attributes as arguments of the relation. Example Likes(drinker, beer) Insert the fact that Sally likes Bud. INSERT INTO Likes(drinker, beer) VALUES('Sally', 'Bud');

  2. Insertion of the Result of a Query INSERT INTO relation (subquery). Example Create a (unary) table of all Sally's potential buddies, i.e., the people who frequent bars that Sally also frequents. Frequents(drinker, bar) CREATE TABLE PotBuddies( name char(30) ); INSERT INTO PotBuddies (SELECT DISTINCT d2.drinker FROM Frequents d1, Frequents d2 WHERE d1.drinker = 'Sally' AND d2.drinker <> 'Sally' AND d1.bar = d2.bar );

  3. Deletion DELETE FROM relation WHERE condition. • Deletes all tuples satisfying the condition from the named relation. Example Sally no longer likes Bud. Likes(drinker, beer) DELETE FROM Likes WHERE drinker = 'Sally' AND beer = 'Bud'; Example Make the Likes relation empty. DELETE FROM Likes;

  4. Example • Delete all beers for which there is another beer by the same manufacturer. Beers(name, manf) DELETE FROM Beers b WHERE EXISTS (SELECT name FROM Beers WHERE manf = b.manf AND name <> b.name ); • Note alias for relation from which deletion occurs.

  5. Semantics is tricky. If A.B. makes Bud and BudLite (only), does deletion of Bud make BudLite not satisfy the condition? • SQL semantics: all conditions in modifications must be evaluated by the system before any mods due to that mod command occur. • In Bud/Budlite example, we would first identify both beers a targets, and then delete both.

  6. Updates UPDATE relation SET list of assignments WHERE condition. Example Drinker Fred's phone number is 555-1212. Drinkers(name, addr, phone) UPDATE Drinkers SET phone = '555-1212' WHERE name = 'Fred'; Example Make $4 the maximum price for beer. • Updates many tuples at once. Sells(bar, beer, price) UPDATE Sells SET price = 4.00 WHERE price > 4.00;

  7. Defining a Database Schema CREATE TABLE name (list of elements). • Principal elements are attributes and their types, but key declarations and constraints also appear. • Similar CREATEX commands for other schema elements X: views, indexes, assertions, triggers. • “DROPX name” deletes the created element of kind X with that name. Example CREATE TABLE Sells ( bar CHAR(20), beer VARCHAR(20), price REAL ); DROP TABLE Sells;

  8. Types • INT or INTEGER. • REAL or FLOAT. • CHAR(n) = fixed length character string, padded with “pad characters.” • VARCHAR(n) = variable-length strings up to n characters. • Oracle uses VARCHAR2(n) as well. PostgreSQL uses VARCHAR and does not support VARCHAR2.

  9. NUMERIC(precision, decimal) is a number with precision digits with the decimal point decimal digits from the right. NUMERIC(10,2) can store ±99,999,999.99 • DATE. SQL form is DATE 'yyyy-mm-dd' • PostgreSQL follows the standard. Oracle uses a different format. • TIME. Form is TIME 'hh:mm:ss[.ss…]' in SQL. • DATETIME or TIMESTAMP. Form is TIMESTAMP 'yyyy-mm-dd hh:mm:ss[.ss…]' in SQL. • INTERVAL. Form is INTERVAL 'n period' in PostgreSQL. Period is month, days, year, etc.

  10. PostgreSQL Dates PostgreSQL supports extensive date calculations. • Conversions to_date(text), to_char(date/time/etc.),interval(text) • Date ± Integer = Date;Date  Date = Integer (always = number of days);Date + Date is invalid! • Timestamp ± Interval = Timestamp;Timestamp  Timestamp = Interval;Interval ± Interval = Interval;Date + Date is invalid. • Interval: '1 month' could be 28, 29, 30, or 31 days;'31 days' is always just that. • SQL uses DATEADD and DATEDIFF;PostgreSQL uses the simpler + and . • Also CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP.

  11. Declaring Keys Use PRIMARY KEY or UNIQUE. • But only one primary key, many UNIQUEs allowed. • SQL permits implementations to create an index (data structure to speed access given a key value) in response to PRIMARY KEY only. • But PostgreSQL and Oracle create indexes for both. • SQL does not allow nulls in primary key, but allows them in “unique” columns (which may have two or more nulls, but not repeated non-null values).

  12. Declaring Keys Two places to declare: • After an attribute’s type, if the attribute is a key by itself. • As a separate element. • Essential if key is >1 attribute.

  13. Example CREATE TABLE Sells ( bar CHAR(20), beer VARCHAR(20), price REAL, PRIMARY KEY(bar,beer) );

  14. Example CREATE TABLE Sells ( bar CHAR(20), beer VARCHAR(20), price REAL, UNIQUE(bar,beer) ); is different than: CREATE TABLE Sells ( bar CHAR(20) UNIQUE, beer VARCHAR(20) UNIQUE, price REAL );

  15. Other Properties You Can Give to Attributes • NOT NULL = every tuple must have a real value for this attribute. • DEFAULT value = a value to use whenever no other value of this attribute is known. Example CREATE TABLE Drinkers ( name CHAR(30) PRIMARY KEY, addr CHAR(50) DEFAULT '123 Sesame St', phone CHAR(16) );

  16. INSERT INTO Drinkers(name) VALUES('Sally') results in the following tuple: name addr phone Sally 123 Sesame St. NULL • Primary key is by default not NULL. • This insert is legal. • OK to list a subset of the attributes and values for only this subset. • But if we had declared phone CHAR(16) NOT NULL then the insertion could not be made.

  17. Interesting Defaults • DEFAULT CURRENT_TIMESTAMP • SEQUENCE CREATE SEQUENCE customer_seq; CREATE TABLE Customer ( customerID INTEGER DEFAULT nextval('customer_seq'), name VARCHAR(30) );

  18. Changing Columns Add an attribute of relation R with ALTER TABLE R ADD <column declaration>; Example ALTER TABLE Bars ADD phone CHAR(16) DEFAULT 'unlisted'; • Columns may also be dropped. ALTER TABLE Bars DROP license;

  19. Views An expression that describes a table without creating it. • View definition form is: CREATE VIEW <name> AS <query>;

  20. Example The view CanDrink is the set of drinker-beer pairs such that the drinker frequents at least one bar that serves the beer. CREATE VIEW CanDrink AS SELECT drinker, beer FROM Frequents, Sells WHERE Frequents.bar = Sells.bar; Querying Views Treat the view as if it were a materialized relation. Example SELECT beer FROM CanDrink WHERE drinker = ‘Sally’;

  21. Semantics of View Use Example

  22. Compose

  23. Optimize Query • Push selections down tree. • Eliminate unnecessary projections.

  24. Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages we learned earlier. • In essence: SQL programming is used to describe constraints. Outline • Primary key declarations (already covered). • Foreign-keys = referential integrity constraints. • Attribute- and tuple-based checks = constraints within relations. • SQL Assertions = global constraints. • Not found in Oracle. • Oracle Triggers. • A substitute for assertions.

  25. Foreign Keys In relation R a clause that “attribute A references S(B)” says that whatever values appear in the A column of R must also appear in the B column of relation S. • B must be declared the primary key for S. Example CREATE TABLE Beers ( name CHAR(20) PRIMARY KEY, manf CHAR(20) ); CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20) REFERENCES Beers(name), price REAL );

  26. Alternative: add another element declaring the foreign key, as: CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20), price REAL, FOREIGN KEY beer REFERENCES Beers(name) ); • Extra element essential if the foreign key is more than one attribute.

  27. What Happens Whena Foreign Key Constraint is Violated? • Two ways: • Insert or update a Sells tuple so it refers to a nonexistent beer. • Always rejected. • Delete or update a Beers tuple that has a beer value some Sells tuples refer to. • Default: reject. • Cascade: Ripple changes to referring Sells tuple. Example • Delete “Bud.” Cascade deletes all Sells tuples that mention Bud. • Update “Bud” to “Budweiser.” Change all Sells tuples with “Bud” in beer column to be “Budweiser.”

  28. Set Null: Change referring tuples to have NULL in referring components. Example • Delete “Bud.” Set-null makes all Sells tuples with “Bud” in the beer component have NULL there. • Update “Bud” to “Budweiser.” Same change.

  29. Selecting a Policy Add ON [DELETE, UPDATE] [CASCADE, SET NULL] to declaration of foreign key. Example CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20), price REAL, FOREIGN KEY beer REFERENCES Beers(name) ON DELETE SET NULL ON UPDATE CASCADE ); • “Correct” policy is a design decision. • E.g., what does it mean if a beer goes away? What if a beer changes its name?

  30. Attribute-Based Checks Follow an attribute by a condition that must hold for that attribute in each tuple of its relation. • Form: CHECK (condition). • Condition may involve the checked attribute. • Other attributes and relations may be involved, but only in subqueries. • Oracle: No subqueries allowed in condition. • Condition is checked only when the associated attribute changes (i.e., an insert or update occurs).

  31. Example CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20) CHECK( beer IN (SELECT name FROM Beers) ), price REAL CHECK( price <= 5.00 ) ); • Check on beer is like a foreign-key constraint, except: • The check occurs only when we add a tuple or change the beer in an existing tuple, not when we delete a tuple from Beers.

  32. Tuple-Based Checks Separate element of table declaration. • Form: like attribute-based check. • But condition can refer to any attribute of the relation. • Or to other relations/attributes in subqueries. • Again: Oracle forbids the use of subqueries. • Checked whenever a tuple is inserted or updated.

  33. Example Only Joe's Bar can sell beer for more than $5. CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20), price REAL, CHECK(bar = 'Joe''s Bar' OR price <= 5.00) );

  34. SQL Assertions • Database-schema constraint. • Not present in Oracle. • Checked whenever a mentioned relation changes. • Syntax: CREATE ASSERTION < name> CHECK(<condition>);

  35. Example No bar may charge an average of more than $5 for beer. Sells(bar, beer, price) CREATE ASSERTION NoRipoffBars CHECK(NOT EXISTS( SELECT bar FROM Sells GROUP BY bar HAVING 5.0 < AVG(price) ) ); • Checked whenever Sells changes.

  36. Example There cannot be more bars than drinkers. Bars(name, addr, license) Drinkers(name, addr, phone) CREATE ASSERTION FewBar CHECK( (SELECT COUNT(*) FROM Bars) <= (SELECT COUNT(*) FROM Drinkers) ); • Checked whenever Bars or Drinkers changes.

  37. Triggers (Oracle Version) Often called event-condition-action rules. • Event = a class of changes in the DB, e.g., “insertions into Beers.” • Condition = a test as in a where-clause for whether or not the trigger applies. • Action = one or more SQL statements. • Differ from checks or SQL assertions in that: • Triggers invoked by the event; the system doesn’t have to figure out when a trigger could be violated. • Condition not available in checks.

  38. Example Whenever we insert a new tuple into Sells, make sure the beer mentioned is also mentioned in Beers, and insert it (with a null manufacturer) if not. Sells(bar, beer, price) CREATE OR REPLACE TRIGGER BeerTrig AFTER INSERT ON Sells FOR EACH ROW WHEN(new.beer NOT IN (SELECT name FROM Beers)) BEGIN INSERT INTO Beers(name) VALUES(:new.beer); END; . run

  39. Options • Can omit OR REPLACE. But if you do, it is an error if a trigger of this name exists. • AFTER can be BEFORE. • If the relation is a view, AFTER can be INSTEADOF. • Useful for allowing “modifications” to a view; you modify the underlying relations instead. • INSERT can be DELETE or UPDATEOF <attribute>. • Also, several conditions like INSERT ON Sells can be connected by OR. • FOR EACH ROW can be omitted, with an important effect: the action is done once for the relation(s) consisting of all changes.

  40. Notes • There are two special variables new and old, representing the new and old tuple in the change. • old makes no sense in an insert, and new makes no sense in a delete. • Notice: in WHEN we use new and old without a colon, but in actions, a preceding colon is needed. • The action is a PL/SQL statement. • Simplest form: surround one or more SQL statements with BEGIN and END. • However, select-from-where has a limited form.

  41. Dot and run cause the definition of the trigger to be stored in the database. • Oracle triggers are part of the database schema, like tables or views. • Important Oracle constraint: the action cannot change the relation that triggers the action. • Worse, the action cannot even change a relation connected to the triggering relation by a constraint, e.g., a foreign-key constraint.

  42. Example Maintain a list of all the bars that raise their price for some beer by more than $1. Sells(bar, beer, price) RipoffBars(bar) CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells FOR EACH ROW WHEN(new.price > old.price + 1.00) BEGIN INSERT INTO RipoffBars VALUES(:new.bar); END; . run

More Related