Modifying the Database

Slides:



Advertisements
Similar presentations
1 Datalog: Logic Instead of Algebra. 2 Datalog: Logic instead of Algebra Each relational-algebra operator can be mimicked by one or several Database Logic.
Advertisements

1 Lecture 4: Advanced SQL. 2 INTERSECT and EXCEPT: (missing from MySQL) (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A, S.B FROM S) (SELECT R.A, R.B FROM.
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)
SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: SQL92, SQL2, SQL3. Vendors support.
1 Lecture 12: SQL Friday, October 26, Outline Simple Queries in SQL (5.1) Queries with more than one relation (5.2) Subqueries (5.3) Duplicates.
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)
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,
Database Modifications A modification command does not return a result as a query does, but it changes the database in some way. There are three kinds.
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.
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.
SQL Overview Defining a Schema CPSC 315 – Programming Studio Spring 2008 Project 1, Lecture 3 Slides adapted from those used by Jeffrey Ullman, via Jennifer.
Correlated Queries SELECT title FROM Movie AS Old WHERE year < ANY (SELECT year FROM Movie WHERE title = Old.title); Movie (title, year, director, length)
Relation Decomposition A, A, … A 12n Given a relation R with attributes Create two relations R1 and R2 with attributes B, B, … B 12m C, C, … C 12l Such.
Integrity Constraints An important functionality of a DBMS is to enable the specification of integrity constraints and to enforce them. Knowledge of integrity.
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.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
More SQL: Complex Queries, Triggers, Views, and Schema Modification UMM AL QURA UNIVERSITY College of Computer Dr. Ali Al Najjar 1.
Recursive query plans for Data Integration Oliver Michael By Rajesh Kanisetti.
1 Lecture 04: SQL Wednesday, January 11, Outline Two Examples Nulls (6.1.6) Outer joins (6.3.8) Database Modifications (6.5)
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,
Datalog Inspired by the impedance mismatch in relational databases. Main expressive advantage: recursive queries. More convenient for analysis: papers.
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.
Datalog –Another query language –cleaner – closer to a “logic” notation, prolog – more convenient for analysis – can express queries that are not expressible.
Datalog Another formalism for expressing queries: - cleaner - closer to a “logic” notation - more convenient for analysis - equivalent in power to relational.
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.
The Relational Model of Data Prof. Yin-Fu Huang CSIE, NYUST Chapter 2.
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.
Slide Chapter 8 Views تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة من الادوات في ذلك. حيث المرجع الاساسي للمادة هي الكتاب المعتمد في.
CPSC-310 Database Systems
SQL.
Lecture 05: SQL Wednesday, January 12, 2005.
Cours 7: Advanced SQL.
CS 480: Database Systems Lecture 13 February 13,2013.
Introduction to Database Systems CSE 444 Lecture 04: SQL
STRUCTURED QUERY LANGUAGE
Lecture 10: Relational Algebra (continued), Datalog
SQL OVERVIEW DEFINING A SCHEMA
Lecture 4: Updates, Views, Constraints and Other Fun Features
Building a Database Application
SQL Introduction Standard language for querying and manipulating data
Lecture 9: Relational Algebra (continued), Datalog
SQL.
Lecture 12: SQL Friday, October 20, 2000.
Where are we? Until now: Modeling databases (ODL, E/R): all about the schema Now: Manipulating the data: queries, updates, SQL Then: looking inside -
Lecture 4: SQL Thursday, January 11, 2001.
Integrity Constraints
Lecture 5: The Relational Data Model
Logic Based Query Languages
Lecture 06: SQL Monday, October 11, 2004.
Lecture 4: SQL Wednesday, April 10, 2002.
Datalog Inspired by the impedance mismatch in relational databases.
Syllabus Introduction Website Management Systems
CSE544 SQL Monday, April 5, 2004.
CMSC-461 Database Management Systems
Lecture 04: SQL Monday, October 6, 2003.
Lecture 05: SQL Wednesday, October 9, 2002.
Lecture 14: SQL Wednesday, October 31, 2001.
Presentation transcript:

Modifying the Database We have 3 kinds of modifications: insertion, deletion, update. Insertion: general form -- INSERT INTO R(A1,…., An) VALUES (v1,…., vn) Insert a new purchase to the database: INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’) If we don’t provide all the attributes of R, they will be filled with NULL. We can drop the attribute names if we’re providing all of them in order.

More Interesting Insertions INSERT INTO PRODUCT(name) SELECT DISTINCT product FROM Purchase WHERE product NOT IN (SELECT name FROM Product) The query replaces the VALUES keyword. Note the order of querying and inserting.

Deletions 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 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, SQL operations on the data. Data definition: defining the schema. Create tables Delete tables Modify table schema But first: Define data types. Finally: define indexes.

Data Types in SQL Character strings (fixed of varying length) Bit strings (fixed or varying length) Integer (SHORTINT) Floating point Dates and times Domains will be used in table declarations. To reuse domains: CREATE DOMAIN address AS VARCHAR(55) You wish you had richer types, no? (hang on…)

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

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

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

Indexes REALLY important to speed up query processing time. Suppose we have a relation Person (name, SSN, age, city) An index on SSN enables us to fetch a tuple for a given SSN very efficiently (not have to scan the whole relation). The problem of deciding which indexes to put on the relations is very hard! (it’s called: physical database design).

Creating Indexes CREATE INDEX ssnIndex ON Person(SSN) Indexes can be created on more than one attribute: CREATE INDEX doubleindex ON Person (age, city) Why not create indexes on all the attributes?

Defining Views (!!) Views are relations, except that they are not physically stored. They are used to: simplify complex queries, and define distinct conceptual interfaces for different classes of users. Example view: purchases of telephony products. CREATE VIEW telephony-purchases AS SELECT product, buyer, seller, store FROM Purchase, Product WHERE Purchase.product = Product.pname AND Product.category = ‘telephony’ The view is materialized when its results are stored in the DBMS.

A Different View CREATE VIEW Seattle-view AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘Seattle’ AND Person.per-name = Purchase.buyer We can later use the views: SELECT name, store FROM Seattle-view, Product WHERE Seattle-view.product = Product.name AND Product.category = ‘shoes’ What’s really happening when we query a view?? It’s unfolded.

Updating Views How can I insert a tuple into a table that doesn’t exist? CREATE VIEW bon-purchase AS SELECT store, seller, product (note: buyer is not selected) FROM Purchase WHERE store = ‘The Bon Marche’ If we make the following insertion: INSERT INTO bon-purchase VALUES (‘the Bon Marche’, ‘Joe’, ‘Denby Mug’) We can simply add a tuple (‘the Bon Marche’, ‘Joe’, NULL, ‘Denby Mug’) to relation Purchase.

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’) In principle, two tuples should be added to the database: Person: (foo, NullPhoneNumber, ‘Seattle’) Purchase: (foo, ‘Joe’, ‘Nine West’, ‘Shoe Model 12345’) But it’s very hard to manage the foo’s later, so this update is not legal.

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 %’.

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 & Levy, 1999).

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=‘4/99’ Stanford database: SELECT number, title, prof, quarter WHERE univ=‘Stanford’ User query: find all professors who teach “database systems”

Datalog Another language for expressing queries: cleaner closer to a “logic” notation, prolog more convenient for analysis can express queries that are not expressible in relational algebra or SQL (recursion).

Predicates and Atoms - relations are represented by predicates - tuples are represented by atoms. Purchase( “joe”, “bob”, “Nike Town”, “Nike Air”, 2/2/98) - arithmetic comparison atoms: X < 100, X+Y+5 > Z/2 - negated atoms: NOT Product(“Brooklyn Bridge”, $100, “Microsoft”)

Datalog Rules and Queries A datalog rule has the following form: head :- atom1, atom2, …., atom,… ExpensiveProduct(X) :- Product(X,Y,P), P > $100 BritishProduct(X) :- Product(X,Y,P), Company(P, “UK”, SP) P(X,Y) :- Between(X,Y,Z), NOT Direct(X,Z) A single rule can express exactly select-from-where queries.

The Meaning of Datalog Rules ExpensiveProduct(X) :- Product(X,Y,P) & P > $100 Consider every assignment from the variables in the body to the constants in the database. If each of the atoms in the body is made true by the assignment, then add the tuple for the head into the relation of the head.

Rule Safety Every variable that appears anywhere in the query must appear also in a relational, non-negated atom in the query. Q(X,Y,Z) :- R1(X,Y) & X < Z not safe Q(X,Y,Z) :- R1(X,Y) & NOT R2(X,Y,Z) not safe

Composing Datalog Rules Extensional predicates: represent relations appearing in the database. Intentional predicates: defined by rules. These can be thought of as being views. Datalog rules may be composed in order to express more complex queries. With composition: it becomes easier to express certain queries (define views) we can define queries including unions, we can define recursive queries.

From Relational Algebra to Datalog We can translate any relational algebra operation to datalog: - projection - selection - union - intersection - join