db modifications

42
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');

Upload: kendall

Post on 22-Feb-2016

29 views

Category:

Documents


0 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: DB Modifications

DB Modifications• Modification = insert + delete + update.

Insertion of a TupleINSERT 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.

ExampleLikes(drinker, beer)Insert the fact that Sally likes Bud.INSERT INTO Likes(drinker, beer)VALUES('Sally', 'Bud');

Page 2: DB Modifications

Insertion of the Result of a QueryINSERT INTO relation (subquery).

ExampleCreate 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

);

Page 3: DB Modifications

DeletionDELETE FROM relation WHERE condition.• Deletes all tuples satisfying the condition from the named

relation.

ExampleSally no longer likes Bud.Likes(drinker, beer)

DELETE FROM LikesWHERE drinker = 'Sally' AND

beer = 'Bud';

ExampleMake the Likes relation empty.DELETE FROM Likes;

Page 4: DB Modifications

Example• Delete all beers for which there is another beer by

the same manufacturer.Beers(name, manf)

DELETE FROM Beers bWHERE EXISTS

(SELECT name FROM Beers WHERE manf = b.manf AND

name <> b.name);

• Note alias for relation from which deletion occurs.

Page 5: DB Modifications

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

Page 6: DB Modifications

UpdatesUPDATE relation SET list of assignments WHERE condition.

ExampleDrinker Fred's phone number is 555-1212.Drinkers(name, addr, phone)UPDATE DrinkersSET phone = '555-1212'WHERE name = 'Fred';

ExampleMake $4 the maximum price for beer.• Updates many tuples at once.Sells(bar, beer, price)UPDATE SellsSET price = 4.00WHERE price > 4.00;

Page 7: DB Modifications

Defining a Database SchemaCREATE TABLE name (list of elements).• Principal elements are attributes and their types, but key

declarations and constraints also appear.• Similar CREATE X commands for other schema elements X:

views, indexes, assertions, triggers.• “DROP X 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;

Page 8: DB Modifications

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.

Page 9: DB Modifications

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

Page 10: DB Modifications

PostgreSQL DatesPostgreSQL 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.

Page 11: DB Modifications

Declaring KeysUse 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).

Page 12: DB Modifications

Declaring KeysTwo 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.

Page 13: DB Modifications

Example CREATE TABLE Sells (

bar CHAR(20),beer VARCHAR(20),price REAL,PRIMARY KEY(bar,beer)

);

Page 14: DB Modifications

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

);

Page 15: DB Modifications

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.

ExampleCREATE TABLE Drinkers ( name CHAR(30) PRIMARY KEY, addr CHAR(50)

DEFAULT '123 Sesame St', phone CHAR(16));

Page 16: DB Modifications

INSERT INTO Drinkers(name) VALUES('Sally')

results in the following tuple:name addr phoneSally 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 declaredphone CHAR(16) NOT NULL

then the insertion could not be made.

Page 17: DB Modifications

Interesting Defaults• DEFAULT CURRENT_TIMESTAMP• SEQUENCE

CREATE SEQUENCE customer_seq;CREATE TABLE Customer (

customerID INTEGER DEFAULT

nextval('customer_seq'),name VARCHAR(30)

);

Page 18: DB Modifications

Changing ColumnsAdd 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;

Page 19: DB Modifications

ViewsAn expression that describesa table without creating it.

• View definition form is:CREATE VIEW <name> AS <query>;

Page 20: DB Modifications

ExampleThe 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, beerFROM Frequents, SellsWHERE Frequents.bar = Sells.bar;

Querying ViewsTreat the view as if it were a materialized relation.

ExampleSELECT beerFROM CanDrinkWHERE drinker = ‘Sally’;

Page 21: DB Modifications

Semantics of View Use

Example

Page 22: DB Modifications

Compose

Page 23: DB Modifications

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

Page 24: DB Modifications

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

Outline1. Primary key declarations (already covered).2. Foreign-keys = referential integrity constraints.3. Attribute- and tuple-based checks = constraints within

relations.4. SQL Assertions = global constraints.

Not found in Oracle.5. Oracle Triggers.

A substitute for assertions.

Page 25: DB Modifications

Foreign KeysIn relation R a clause that “attribute A references S(B)”says that whatever values appear in the A column of Rmust also appear in the B column of relation S.• B must be declared the primary key for S.

ExampleCREATE TABLE Beers (name CHAR(20) PRIMARY KEY,manf CHAR(20)

);

CREATE TABLE Sells (bar CHAR(20),beer CHAR(20) REFERENCES Beers(name),price REAL

);

Page 26: DB Modifications

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.

Page 27: DB Modifications

What Happens Whena Foreign Key Constraint is Violated?1. Two ways:2. Insert or update a Sells tuple so it refers to a

nonexistent beer. Always rejected.

3. Delete or update a Beers tuple that has a beer value some Sells tuples refer to.

a) Default: reject.b) 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.”

Page 28: DB Modifications

c) 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.

Page 29: DB Modifications

Selecting a PolicyAdd ON [DELETE, UPDATE] [CASCADE, SET NULL] to

declaration of foreign key.

ExampleCREATE TABLE Sells (bar CHAR(20),beer CHAR(20),price REAL,FOREIGN KEY beer REFERENCES Beers(name)ON DELETE SET NULLON 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?

Page 30: DB Modifications

Attribute-Based ChecksFollow 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).

Page 31: DB Modifications

ExampleCREATE TABLE Sells (

bar CHAR(20),beer CHAR(20) CHECK(

beer IN (SELECT nameFROM 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.

Page 32: DB Modifications

Tuple-Based ChecksSeparate 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.

Page 33: DB Modifications

ExampleOnly 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));

Page 34: DB Modifications

SQL Assertions• Database-schema constraint.• Not present in Oracle.• Checked whenever a mentioned relation

changes.• Syntax:

CREATE ASSERTION < name>CHECK(<condition>);

Page 35: DB Modifications

ExampleNo bar may charge an average of more than $5 for beer.

Sells(bar, beer, price)

CREATE ASSERTION NoRipoffBarsCHECK(NOT EXISTS(

SELECT barFROM SellsGROUP BY barHAVING 5.0 < AVG(price))

);

• Checked whenever Sells changes.

Page 36: DB Modifications

ExampleThere cannot be more bars than drinkers.

Bars(name, addr, license)Drinkers(name, addr, phone)

CREATE ASSERTION FewBarCHECK(

(SELECT COUNT(*) FROM Bars) <= (SELECT COUNT(*) FROM Drinkers)

);

• Checked whenever Bars or Drinkers changes.

Page 37: DB Modifications

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:

1. Triggers invoked by the event; the system doesn’t have to figure out when a trigger could be violated.

2. Condition not available in checks.

Page 38: DB Modifications

ExampleWhenever 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 BeerTrigAFTER INSERT ON SellsFOR EACH ROWWHEN(new.beer NOT IN(SELECT name FROM Beers))BEGININSERT INTO Beers(name)VALUES(:new.beer);END;

.run

Page 39: DB Modifications

Options1. Can omit OR REPLACE. But if you do, it is an error

if a trigger of this name exists.2. AFTER can be BEFORE.3. If the relation is a view, AFTER can be INSTEAD OF.

Useful for allowing “modifications” to a view; you modify the underlying relations instead.

4. INSERT can be DELETE or UPDATE OF <attribute>. Also, several conditions like INSERT ON Sells can be

connected by OR.5. FOR EACH ROW can be omitted, with an important

effect: the action is done once for the relation(s) consisting of all changes.

Page 40: DB Modifications

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.

Page 41: DB Modifications

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

Page 42: DB Modifications

ExampleMaintain 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 PriceTrigAFTER UPDATE OF price ON SellsFOR EACH ROWWHEN(new.price > old.price + 1.00)BEGININSERT INTO RipoffBarsVALUES(:new.bar);END;

.run