Lecture 4: Updates, Views, Constraints and Other Fun Features

Slides:



Advertisements
Similar presentations
1 Lecture 5: SQL Schema & Views. 2 Data Definition in SQL So far we have see the Data Manipulation Language, DML Next: Data Definition Language (DDL)
Advertisements

SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: SQL92, SQL2, SQL3. Vendors support.
Lecture 07: Relational Algebra
CSE 544 Constraints Lecture #3 Friday, January 13, 2011 Dan Suciu , Winter
1 Lecture 03: Advanced SQL. 2 Outline Unions, intersections, differences Subqueries, Aggregations, NULLs Modifying databases, Indexes, Views Reading:
1 Data Definition in SQL So far we have see the Data Manipulation Language, DML Next: Data Definition Language (DDL) Data types: Defines the types. Data.
SQL April 25 th, Agenda Grouping and aggregation Sub-queries Updating the database Views More on views.
1 Lecture 06: SQL Friday, January 14, Outline Indexes Defining Views (6.7) Constraints (Chapter 7) We begin E/R diagrams (Chapter 2)
End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.
1 Lecture 05: SQL Wednesday, October 8, Outline Outer joins (6.3.8) Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes.
1 INTERSECT and EXCEPT: (may no be in MySQL) (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A, S.B FROM S) (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A,
Lecture #4 October 19, 2000 SQL. Administration Exam date officially moved to December 7 th, 6:30pm, here. Homework #3 – will be on the web site tomorrow.
1 Lecture 07: Relational Algebra. 2 Outline Relational Algebra (Section 6.1)
Embedded SQL Direct SQL is rarely used: usually, SQL is embedded in some application code. We need some method to reference SQL statements. But: there.
Correlated Queries SELECT title FROM Movie AS Old WHERE year < ANY (SELECT year FROM Movie WHERE title = Old.title); Movie (title, year, director, length)
Remaining Topics in SQL to be covered… NULL values in SQL Outer joins in SQL Constraints and Triggers in SQL Embedded SQL.
SQL: Constraints and Triggers Chapter 6 Ullman and Widom Certain properties we’d like our database to hold Modification of the database may break these.
Exercises Product ( pname, price, category, maker) Purchase (buyer, seller, store, product) Company (cname, stock price, country) Person( per-name, phone.
1 Lecture 4: More SQL Monday, January 13th, 2003.
1 Lecture 7: End of Normal Forms Outerjoins, Schema Creation and Views Wednesday, January 28th, 2004.
SQL (almost end) April 26 th, Agenda HAVING clause Views Modifying views Reusing views.
SQL April 22 th, Agenda Union, intersections Sub-queries Modifying the database Views Modifying views Reusing views.
1 Lecture 04: SQL Wednesday, January 11, Outline Two Examples Nulls (6.1.6) Outer joins (6.3.8) Database Modifications (6.5)
1 Introduction to Database Systems CSE 444 Lecture 20: Query Execution: Relational Algebra May 21, 2008.
1 Lecture 6: Views Friday, January 17th, Updating Views How can I insert a tuple into a table that doesn’t exist? Employee(ssn, name, department,
1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.
Phase 2, Answering queries using views. February 2 nd, 2004.
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
Transactions, Relational Algebra, XML February 11 th, 2004.
1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.
CSE 544: Relational Operators, Sorting Wednesday, 5/12/2004.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Relational Algebra 2. Relational Algebra Formalism for creating new relations from existing ones Its place in the big picture: Declartive query language.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
Lecture 13: Relational Decomposition and Relational Algebra February 5 th, 2003.
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
1 Introduction to Database Systems CSE 444 Lecture 04: SQL April 7, 2008.
1 Lecture 5: Outerjoins, Schema Creation and Views Wednesday, January 15th, 2003.
Aggregation SELECT Sum(price) FROM Product WHERE manufacturer=“Toyota” SQL supports several aggregation operations: SUM, MIN, MAX, AVG, COUNT Except COUNT,
1 Lecture 06 Data Modeling: E/R Diagrams Wednesday, January 18, 2006.
1 Lecture 05: SQL Wednesday, October 8, Outline Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes Defining Views (6.7)
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
Relational Algebra.
SQL.
Lecture 05: SQL Wednesday, January 12, 2005.
Cours 7: Advanced SQL.
Lecture 8: Relational Algebra
Modifying the Database
Remaining Topics in SQL to be covered…
Introduction to Database Systems CSE 444 Lecture 04: SQL
Lecture 06: SQL Systems Aspects
SQL Introduction Standard language for querying and manipulating data
Lecture 05 Views, Constraints
RDBMS RELATIONAL DATABASE MANAGEMENT SYSTEM.
Lecture 12: SQL Friday, October 20, 2000.
Lecture 17: Systems Aspects of SQL
Lecture 33: The Relational Model 2
Lecture 4: SQL Thursday, January 11, 2001.
Integrity Constraints
Relational Algebra Friday, 11/14/2003.
CS639: Data Management for Data Science
Lecture 06: SQL Monday, October 11, 2004.
Lecture 4: SQL Wednesday, April 10, 2002.
CSE544 SQL Monday, April 5, 2004.
Lecture 04: SQL Monday, October 6, 2003.
Lecture 05: SQL Wednesday, October 9, 2002.
Lecture 05: SQL Systems Aspects
Lecture 11: Functional Dependencies
Lecture 14: SQL Wednesday, October 31, 2001.
Presentation transcript:

Lecture 4: Updates, Views, Constraints and Other Fun Features Monday, April 19th, 2004

Agenda Nulls and outerjoins Creating and updating schemas Views: updating and reusing them Constraints Programming with SQL Relational algebra

Null Values and Outerjoins Explicit joins in SQL: Product(name, category) Purchase(prodName, store) Same as: But Products that never sold will be lost ! SELECT Product.name, Purchase.store FROM Product JOIN Purchase ON Product.name = Purchase.prodName SELECT Product.name, Purchase.store FROM Product, Purchase WHERE Product.name = Purchase.prodName

Null Values and Outerjoins Left outer joins in SQL: Product(name, category) Purchase(prodName, store) SELECT Product.name, Purchase.store FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName

Product Purchase Name Category Gizmo gadget Camera Photo OneClick ProdName Store Gizmo Wiz Camera Ritz Name Store Gizmo Wiz Camera Ritz OneClick NULL

Outer Joins Left outer join: Right outer join: Full outer join: Include the left tuple even if there’s no match Right outer join: Include the right tuple even if there’s no match Full outer join: Include the both left and right tuples even if there’s no match

Modifying the Database Three kinds of modifications Insertions Deletions Updates Sometimes they are all called “updates”

Insertions General form: INSERT INTO R(A1,…., An) VALUES (v1,…., vn) Example: Insert a new purchase to the database: INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’) Missing attribute  NULL. May drop attribute names if give them in order.

Insertions INSERT INTO PRODUCT(name) SELECT DISTINCT Purchase.product FROM Purchase WHERE Purchase.date > “10/26/01” The query replaces the VALUES keyword. Here we insert many tuples into PRODUCT

Insertion: an Example Product(name, listPrice, category) Purchase(prodName, buyerName, price) prodName is foreign key in Product.name Suppose database got corrupted and we need to fix it: Purchase Product prodName buyerName price camera John 200 gizmo Smith 80 225 name listPrice category gizmo 100 gadgets Task: insert in Product all prodNames from Purchase

Insertion: an Example INSERT INTO Product(name) SELECT DISTINCT prodName FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera -

Insertion: an Example INSERT INTO Product(name, listPrice) SELECT DISTINCT prodName, price FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera 200 - camera ?? 225 ?? Depends on the implementation

Deletions Example: DELETE FROM PURCHASE WHERE seller = ‘Joe’ AND product = ‘Brooklyn Bridge’ Factoid about SQL: there is no way to delete only a single occurrence of a tuple that appears twice in a relation.

Updates Example: UPDATE PRODUCT SET price = price/2 WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’);

Data Definition in SQL So far we have see the Data Manipulation Language, DML Next: Data Definition Language (DDL) Data types: Defines the types. Data definition: defining the schema. Create tables Delete tables Modify table schema Indexes: to improve performance

Data Types in SQL Characters: Numbers: Times and dates: CHAR(20) -- fixed length VARCHAR(40) -- variable length Numbers: INT, REAL plus variations Times and dates: DATE, DATETIME (SQL Server only) To reuse domains: CREATE DOMAIN address AS VARCHAR(55)

Creating Tables Example: CREATE TABLE Person( name VARCHAR(30), social-security-number INT, age SHORTINT, city VARCHAR(30), gender BIT(1), Birthdate DATE );

Deleting or Modifying a Table Example: DROP Person; Exercise with care !! Altering: (adding or removing an attribute). ALTER TABLE Person ADD phone CHAR(16); ALTER TABLE Person DROP age; Example: What happens when you make changes to the schema?

Default Values Specifying default values: CREATE TABLE Person( name VARCHAR(30), social-security-number INT, age SHORTINT DEFAULT 100, city VARCHAR(30) DEFAULT ‘Seattle’, gender CHAR(1) DEFAULT ‘?’, Birthdate DATE The default of defaults: NULL

Indexes REALLY important to speed up query processing time. Suppose we have a relation Person (name, age, city) Sequential scan of the file Person may take long SELECT * FROM Person WHERE name = “Smith”

Indexes Create an index on name: B+ trees have fan-out of 100s: max 4 levels ! Adam Betty Charles …. Smith

Creating Indexes Syntax: CREATE INDEX nameIndex ON Person(name)

Creating Indexes Indexes can be created on more than one attribute: CREATE INDEX doubleindex ON Person (age, city) Example: SELECT * FROM Person WHERE age = 55 AND city = “Seattle” Helps in: SELECT * FROM Person WHERE city = “Seattle” But not in:

Creating Indexes Indexes can be useful in range queries too: B+ trees help in: Why not create indexes on everything? CREATE INDEX ageIndex ON Person (age) SELECT * FROM Person WHERE age > 25 AND age < 28

Agenda Nulls and outerjoins Creating and updating schemas Views: updating and reusing them Constraints Programming with SQL Relational algebra

Defining Views Views are relations, except that they are not physically stored. For presenting different information to different users Employee(ssn, name, department, project, salary) Payroll has access to Employee, others only to Developers CREATE VIEW Developers AS SELECT name, project FROM Employee WHERE department = “Development”

A Different View Person(name, city) Purchase(buyer, seller, product, store) Product(name, maker, category) We have a new virtual table: Seattle-view(buyer, seller, product, store) CREATE VIEW Seattle-view AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = “Seattle” AND Person.name = Purchase.buyer

Using a View We can later use the view: SELECT name, store FROM Seattle-view, Product WHERE Seattle-view.product = Product.name AND Product.category = “shoes”

What Happens When We Query a View ? SELECT name, Seattle-view.store FROM Seattle-view, Product WHERE Seattle-view.product = Product.name AND Product.category = “shoes” SELECT name, Purchase.store FROM Person, Purchase, Product WHERE Person.city = “Seattle” AND Person.name = Purchase.buyer AND Purchase.poduct = Product.name AND Product.category = “shoes”

Types of Views Virtual views: Materialized views Used in databases Computed only on-demand – slower at runtime Always up to date Materialized views Used in data warehouses Precomputed offline – faster at runtime May have stale data

Updating Views How can I insert a tuple into a table that doesn’t exist? Employee(ssn, name, department, project, salary) CREATE VIEW Developers AS SELECT name, project FROM Employee WHERE department = “Development” If we make the following insertion: INSERT INTO Developers VALUES(“Joe”, “Optimizer”) INSERT INTO Employee VALUES(NULL, “Joe”, “Development”, “Optimizer”, NULL) It becomes:

Non-Updatable Views CREATE VIEW Seattle-view AS SELECT seller, product, store FROM Person, Purchase WHERE Person.city = “Seattle” AND Person.name = Purchase.buyer How can we add the following tuple to the view? (“Joe”, “Shoe Model 12345”, “Nine West”) We need to add “Joe” to Person first, but we don’t have all its attributes

Answering Queries Using Views What if we want to use a set of views to answer a query. Why? The obvious reason… Answering queries over web data sources. Very cool stuff! (i.e., I did a lot of research on this).

Reusing a Materialized View Suppose I have only the result of SeattleView: SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘Seattle’ AND Person.per-name = Purchase.buyer and I want to answer the query SELECT buyer, seller Person.per-name = Purchase.buyer AND Purchase.product=‘gizmo’. Then, I can rewrite the query using the view.

Query Rewriting Using Views Rewritten query: SELECT buyer, seller FROM SeattleView WHERE product= ‘gizmo’ Original query: FROM Person, Purchase WHERE Person.city = ‘Seattle’ AND Person.per-name = Purchase.buyer AND Purchase.product=‘gizmo’.

Another Example I still have only the result of SeattleView: SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘Seattle’ AND Person.per-name = Purchase.buyer but I want to answer the query SELECT buyer, seller Person.per-name = Purchase.buyer AND Person.Phone LIKE ‘206 543 %’.

And Now? I still have only the result of SeattleView: SELECT buyer, seller, product, store FROM Person, Purchase, Product WHERE Person.city = ‘Seattle’ AND Person.per-name = Purchase.buyer AND Purchase.product = Product.name but I want to answer the query SELECT buyer, seller FROM Person, Purchase Person.per-name = Purchase.buyer.

And Now? I still have only the result of: SELECT seller, buyer, Sum(Price) FROM Purchase WHERE Purchase.store = ‘The Bon’ Group By seller, buyer but I want to answer the query SELECT seller, Sum(Price) WHERE Person.store = ‘The Bon’ Group By seller And what if it’s the other way around?

Finally… I still have only the result of: SELECT seller, buyer, Count(*) FROM Purchase WHERE Purchase.store = ‘The Bon’ Group By seller, buyer but I want to answer the query SELECT seller, Count(*) WHERE Person.store = ‘The Bon’ Group By seller

The General Problem Given a set of views V1,…,Vn, and a query Q, can we answer Q using only the answers to V1,…,Vn? Why do we care? We can answer queries more efficiently. We can query data sources on the WWW in a principled manner. Many, many papers on this problem. The best performing algorithm: The MiniCon Algorithm, (Pottinger & (Ha)Levy, 2000).

Querying the WWW Assume a virtual schema of the WWW, e.g., Course(number, university, title, prof, quarter) Every data source on the web contains the answer to a view over the virtual schema: UW database: SELECT number, title, prof FROM Course WHERE univ=‘UW’ AND quarter=‘2/02’ Stanford database: SELECT number, title, prof, quarter WHERE univ=‘Stanford’ User query: find all professors who teach “database systems”

Agenda Nulls and outer-joins Creating and updating schemas Views: updating and reusing them Constraints Programming with SQL Relational algebra

Constraints in SQL A constraint = a property that we’d like our database to hold The system will enforce the constraint by taking some actions: forbid an update or perform compensating updates

Constraints in SQL Constraints in SQL: Keys, foreign keys Attribute-level constraints Tuple-level constraints Global constraints: assertions The more complex the constraint, the harder it is to check and to enforce simplest Most complex

Keys OR: CREATE TABLE Product ( name CHAR(30) PRIMARY KEY, category VARCHAR(20)) OR: CREATE TABLE Product ( name CHAR(30), category VARCHAR(20) PRIMARY KEY (name))

Keys with Multiple Attributes CREATE TABLE Product ( name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (name, category))

Other Keys CREATE TABLE Product ( productID CHAR(10), name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (productID), UNIQUE (name, category)) There is at most one PRIMARY KEY; there can be many UNIQUE

Foreign Key Constraints Referential integrity constraints CREATE TABLE Purchase ( prodName CHAR(30) REFERENCES Product(name), date DATETIME) prodName is a foreign key to Product(name) name must be a key in Product

Product Purchase Name Category Gizmo gadget Camera Photo OneClick ProdName Store Gizmo Wiz Camera Ritz

Foreign Key Constraints (name, category) must be a PRIMARY KEY CREATE TABLE Purchase ( prodName CHAR(30), category VARCHAR(20), date DATETIME, FOREIGN KEY (prodName, category) REFERENCES Product(name, category)

What happens during updates ? Types of updates: In Purchase: insert/update In Product: delete/update Product Purchase Name Category Gizmo gadget Camera Photo OneClick ProdName Store Gizmo Wiz Camera Ritz

What happens during updates ? SQL has three policies for maintaining referential integrity: Reject violating modifications (default) Cascade: after a delete/update do a delete/update Set-null set foreign-key field to NULL READING ASSIGNEMNT: 7.1.5, 7.1.6

Constraints on Attributes and Tuples Constraints on attributes: NOT NULL -- obvious meaning... CHECK condition -- any condition ! Constraints on tuples CHECK condition

What is the difference from Foreign-Key ? CREATE TABLE Purchase ( prodName CHAR(30) CHECK (prodName IN SELECT Product.name FROM Product), date DATETIME NOT NULL)

General Assertions CREATE ASSERTION myAssert CHECK NOT EXISTS( SELECT Product.name FROM Product, Purchase WHERE Product.name = Purchase.prodName GROUP BY Product.name HAVING count(*) > 200)

Final Comments on Constraints Can give them names, and alter later Read in the book. We need to understand exactly when they are checked We need to understand exactly what actions are taken if they fail

Triggers Enable the database programmer to specify: when to check a constraint, what exactly to do. A trigger has 3 parts: An event (e.g., update to an attribute) A condition (e.g., a query to check) An action (deletion, update, insertion) When the event happens, the system will check the constraint, and if satisfied, will perform the action. NOTE: triggers may cause cascading effects. Database vendors did not wait for standards with triggers!

Elements of Triggers (in SQL3) Timing of action execution: before, after or instead of triggering event The action can refer to both the old and new state of the database. Update events may specify a particular column or set of columns. A condition is specified with a WHEN clause. The action can be performed either for once for every tuple, or once for all the tuples that are changed by the database operation.

Example: Row Level Trigger CREATE TRIGGER NoLowerPrices AFTER UPDATE OF price ON Product REFERENCING OLD AS OldTuple NEW AS NewTuple WHEN (OldTuple.price > NewTuple.price) UPDATE Product SET price = OldTuple.price WHERE name = NewTuple.name FOR EACH ROW

Statement Level Trigger CREATE TRIGGER average-price-preserve INSTEAD OF UPDATE OF price ON Product REFERENCING OLD_TABLE AS OldStuff NEW_TABLE AS NewStuff WHEN (1000 < (SELECT AVG (price) FROM ((Product EXCEPT OldStuff) UNION NewStuff)) DELETE FROM Product WHERE (name, price, company) IN OldStuff; INSERT INTO Product (SELECT * FROM NewStuff)

Bad Things Can Happen CREATE TRIGGER Bad-trigger AFTER UPDATE OF price IN Product REFERENCING OLD AS OldTuple NEW AS NewTuple WHEN (NewTuple.price > 50) UPDATE Product SET price = NewTuple.price * 2 WHERE name = NewTuple.name FOR EACH ROW

Agenda Nulls and outerjoins Creating and updating schemas Views: updating and reusing them Constraints Programming with SQL Relational algebra

Embedded SQL direct SQL (= ad-hoc SQL) is rarely used in practice: SQL is embedded in some application code SQL code is identified by special syntax

Impedance Mismatch Example: SQL in C: C uses int, char[..], pointers, etc SQL uses tables Impedance mismatch = incompatible types

The Impedance Mismatch Problem Why not use only one language? Forgetting SQL: “we can quickly dispense with this idea” [textbook, pg. 351]. SQL cannot do everything that the host language can do. Solution: use cursors

Programs with Embedded SQL Host language + Embedded SQL Preprocessor Preprocessor Call-level interface (CLI): ODBC,JDBC, ADO Host Language + function calls Host language compiler Host language compiler Host language program

Interface: SQL / Host Language Values get passed through shared variables. Colons precede shared variables when they occur within the SQL statements. EXEC SQL: precedes every SQL statement in the host language. The variable SQLSTATE provides error messages and status reports (e.g., “00000” says that the operation completed with no problem). EXEC SQL BEGIN DECLARE SECTION; char productName[30]; EXEC SQL END DECLARE SECTION;

Example Product (pname, price, quantity, maker) Purchase (buyer, seller, store, pname) Company (cname, city) Person(name, phone, city)

Using Shared Variables Void simpleInsert() { EXEC SQL BEGIN DECLARE SECTION; char n[20], c[30]; /* product-name, company-name */ int p, q; /* price, quantity */ char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; /* get values for name, price and company somehow */ EXEC SQL INSERT INTO Product(pname, price, quantity, maker) VALUES (:n, :p, :q, :c); }

Single-Row Select Statements int getPrice(char *name) { EXEC SQL BEGIN DECLARE SECTION; char n[20]; int p; char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; strcpy(n, name); /* copy name to local variable */ EXEC SQL SELECT price INTO :p FROM Product WHERE Product.name = :n; return p; }

Cursors Declare the cursor Open the cursor Fetch tuples one by one Close the cursor

Cursors void product2XML() { EXEC SQL BEGIN DECLARE SECTION; char n[20], c[30]; int p, q; char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; EXEC SQL DECLARE crs CURSOR FOR SELECT pname, price, quantity, maker FROM Product; EXEC SQL OPEN crs;

Cursors printf(“<allProducts>\n”); while (1) { EXEC SQL FETCH FROM crs INTO :n, :p, :q, :c; if (NO_MORE_TUPLES) break; printf(“ <product>\n”); printf(“ <name> %s </name>\n”, n); printf(“ <price> %d </price>\n”, p); printf(“ <quantity> %d </quantity>\n”, q); printf(“ <maker> %s </maker>\n”, c); printf(“ </product>\n”); } EXECT SQL CLOSE crs; printf(“</allProducts>\n”);

What is NO_MORE_TUPLES ? #define NO_MORE_TUPLES !(strcmp(SQLSTATE,”02000”))

More on Cursors cursors can modify a relation as well as read it. We can determine the order in which the cursor will get tuples by the ORDER BY keyword in the SQL query. Cursors can be protected against changes to the underlying relations. The cursor can be a scrolling one: can go forward, backward +n, -n, Abs(n), Abs(-n).

Agenda Nulls and outerjoins Creating and updating schemas Views: updating and reusing them Constraints Programming with SQL Relational algebra

Declartive query language Relational Algebra Formalism for creating new relations from existing ones Its place in the big picture: Declartive query language Algebra Implementation Relational algebra Relational bag algebra SQL, relational calculus

Relational Algebra Five operators: Derived or auxiliary operators: Union:  Difference: - Selection: s Projection: P Cartesian Product:  Derived or auxiliary operators: Intersection, complement Joins (natural,equi-join, theta join, semi-join) Renaming: r

1. Union and 2. Difference R1  R2 Example: R1 – R2 ActiveEmployees  RetiredEmployees R1 – R2 AllEmployees -- RetiredEmployees

What about Intersection ? It is a derived operator R1  R2 = R1 – (R1 – R2) Also expressed as a join (will see later) Example UnionizedEmployees  RetiredEmployees

3. Selection Returns all tuples which satisfy a condition Notation: sc(R) Examples sSalary > 40000 (Employee) sname = “Smithh” (Employee) The condition c can be =, <, , >, , <>

Find all employees with salary more than $40,000. s Salary > 40000 (Employee)

4. Projection Eliminates columns, then removes duplicates Notation: P A1,…,An (R) Example: project social-security number and names: P SSN, Name (Employee) Output schema: Answer(SSN, Name)

P SSN, Name (Employee)

5. Cartesian Product Each tuple in R1 with each tuple in R2 Notation: R1  R2 Example: Employee  Dependents Very rare in practice; mainly used to express joins

Relational Algebra Five operators: Derived or auxiliary operators: Union:  Difference: - Selection: s Projection: P Cartesian Product:  Derived or auxiliary operators: Intersection, complement Joins (natural,equi-join, theta join, semi-join) Renaming: r

Renaming Changes the schema, not the instance Notation: r B1,…,Bn (R) Example: rLastName, SocSocNo (Employee) Output schema: Answer(LastName, SocSocNo)

LastName, SocSocNo (Employee) Renaming Example Employee Name SSN John 999999999 Tony 777777777 LastName, SocSocNo (Employee) LastName SocSocNo John 999999999 Tony 777777777

Natural Join Notation: R1 ⋈ R2 Meaning: R1 ⋈ R2 = PA(sC(R1  R2)) Where: The selection sC checks equality of all common attributes The projection eliminates the duplicate common attributes

Natural Join Example Employee Name SSN John 999999999 Tony 777777777 Dependents SSN Dname 999999999 Emily 777777777 Joe Employee Dependents = PName, SSN, Dname(s SSN=SSN2(Employee x rSSN2, Dname(Dependents)) Name SSN Dname John 999999999 Emily Tony 777777777 Joe

Natural Join R= S= R ⋈ S= A B X Y Z V B C Z U V W A B C X Z U V Y W

Natural Join Given the schemas R(A, B, C, D), S(A, C, E), what is the schema of R ⋈ S ? Given R(A, B, C), S(D, E), what is R ⋈ S ? Given R(A, B), S(A, B), what is R ⋈ S ?

Theta Join A join that involves a predicate R1 ⋈ q R2 = s q (R1  R2) Here q can be any condition

Eq-join A theta join where q is an equality R1 ⋈A=B R2 = s A=B (R1  R2) Example: Employee ⋈SSN=SSN Dependents Most useful join in practice

Semijoin R ⋉ S = P A1,…,An (R ⋈ S) Where A1, …, An are the attributes in R Example: Employee ⋉ Dependents

Semijoins in Distributed Databases Semijoins are used in distributed databases Dependents Employee SSN Dname Age . . . SSN Name . . . network Employee ⋈ssn=ssn (s age>71 (Dependents)) T = P SSN s age>71 (Dependents) R = Employee ⋉ T Answer = R ⋈ Dependents

Complex RA Expressions P name buyer-ssn=ssn pid=pid seller-ssn=ssn P ssn P pid sname=fred sname=gizmo Person Purchase Person Product

Operations on Bags A bag = a set with repeated elements All operations need to be defined carefully on bags {a,b,b,c}{a,b,b,b,e,f,f}={a,a,b,b,b,b,b,c,e,f,f} {a,b,b,b,c,c} – {b,c,c,c,d} = {a,b,b,d} sC(R): preserve the number of occurrences PA(R): no duplicate elimination Cartesian product, join: no duplicate elimination Important ! Relational Engines work on bags, not sets ! Reading assignment: 5.3 – 5.4

Finally: RA has Limitations ! Cannot compute “transitive closure” Find all direct and indirect relatives of Fred Cannot express in RA !!! Need to write C program Name1 Name2 Relationship Fred Mary Father Joe Cousin Bill Spouse Nancy Lou Sister