440 likes | 527 Views
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.
E N D
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');
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 );
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;
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.
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.
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;
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;
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.
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.
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.
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).
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.
Example CREATE TABLE Sells ( bar CHAR(20), beer VARCHAR(20), price REAL, PRIMARY KEY(bar,beer) );
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 );
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) );
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.
Interesting Defaults • DEFAULT CURRENT_TIMESTAMP • SEQUENCE CREATE SEQUENCE customer_seq; CREATE TABLE Customer ( customerID INTEGER DEFAULT nextval('customer_seq'), name VARCHAR(30) );
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;
Views An expression that describes a table without creating it. • View definition form is: CREATE VIEW <name> AS <query>;
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’;
Semantics of View Use Example
Optimize Query • Push selections down tree. • Eliminate unnecessary projections.
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.
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 );
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.
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.”
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.
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?
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).
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.
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.
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) );
SQL Assertions • Database-schema constraint. • Not present in Oracle. • Checked whenever a mentioned relation changes. • Syntax: CREATE ASSERTION < name> CHECK(<condition>);
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.
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.
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.
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
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.
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.
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.
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