1 Chapter 6 More SQL uDatabase Modification uDefining a Database Schema uViews.

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: SQL92, SQL2, SQL3. Vendors support.
1 More SQL Database Modification Defining a Database Schema Views.
SQL Query Examples Database Management COP4540, SCS, FIU.
SQL This presentation will cover: A Brief History of DBMS View in database MySQL installation.
Database Modifications CIS 4301 Lecture Notes Lecture /30/2006.
SQL reviews. Stored Procedures Create Procedure Triggers.
Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
1 Introduction to SQL Multirelation Queries Subqueries Slides are reused by the approval of Jeffrey Ullman’s.
Database Modifications, Data Types, Views. Database Modifications A modification command does not return a result as a query does, but it changes the.
Database Modifications, Data Types, Views. Database Modifications A modification command does not return a result as a query does, but it changes the.
Subqueries Example Find the name of the producer of ‘Star Wars’.
Indexes. An index on an attribute A of a relation is a data structure that makes it efficient to find those tuples that have a fixed value for attribute.
1 More SQL Database Modification Defining a Database Schema Views Source: slides by Jeffrey Ullman.
Dec 4, 2003Murali Mani SQL B term 2004: lecture 14.
1 More SQL Defining a Database Schema Views. 2 Defining a Database Schema uA database schema comprises declarations for the relations (“tables”) of the.
SQL. 1.SQL is a high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details that would be necessary in.
1 Constraints Foreign Keys Local and Global Constraints Triggers.
SQL SQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details that would be necessary in.
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.
Joins Natural join is obtained by: R NATURAL JOIN S; Example SELECT * FROM MovieStar NATURAL JOIN MovieExec; Theta join is obtained by: R JOIN S ON Example.
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)
1 More SQL Extended Relational Algebra Outerjoins, Grouping/Aggregation Insert/Delete/Update.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #2.
1 Relational Data Model CS 157B Nidhi Patel. 2 What is a Data Model? A notation for describing data or information A notation for describing data or information.
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.
SQL Overview Defining a Schema CPSC 315 – Programming Studio Slides adapted from those used by Jeffrey Ullman, via Jennifer Welch Via Yoonsuck Choe.
1 Exercises of SQL uAnswer the following questions, based on the database below. wSupplier (SNO, SNAME, STATUS, CITY) wPart(PNO, PNAME, COLOR, WEIGHT)
SQL 2014, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman distributes via his course web.
Relational Algebra Spring 2012 Instructor: Hassan Khosravi.
Introduction to Indexes. Indexes An index on an attribute A of a relation is a data structure that makes it efficient to find those tuples that have a.
ICS 321 Fall 2011 Constraints, Triggers, Views & Indexes Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa.
SCUHolliday - coen 1788–1 Schedule Today u Modifications, Schemas, Views. u Read Sections (except and 6.6.6) Next u Constraints. u Read.
1 Database Systems Defining Database Schema Views.
1 Chapter 6 Constraints uForeign Keys uConstraints.
1 More SQL uDatabase Modification uDefining a Database Schema uViews.
1/46 More SQL uDatabase Modification uDefining a Database Schema uViews.
Referential Integrity checks, Triggers and Assertions Examples from Chapter 7 of Database Systems: the Complete Book Garcia-Molina, Ullman, & Widom.
Advanced SQL Concepts - Checking of Constraints CIS 4301 Lecture Notes Lecture /6/2006.
© D. Wong Normalization  Purpose: process to eliminate redundancy in relations due to functional or multi-valued dependencies.  Decompose relation.
1 CSCE Database Systems Anxiao (Andrew) Jiang The Database Language SQL.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
SQL Exercises – Part I April
Databases : SQL-Schema Definition and View 2007, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey.
The Relational Model of Data Prof. Yin-Fu Huang CSIE, NYUST Chapter 2.
603 Database Systems Senior Lecturer: Laurie Webster II, M.S.S.E.,M.S.E.E., M.S.BME, Ph.D., P.E. Lecture 18 A First Course in Database Systems.
The Database Language SQL Prof. Yin-Fu Huang CSIE, NYUST Chapter 6.
Aggregation SELECT Sum(price) FROM Product WHERE manufacturer=“Toyota” SQL supports several aggregation operations: SUM, MIN, MAX, AVG, COUNT Except COUNT,
Databases : SQL Multi-Relations 2007, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman.
1 SQL: Concept and Usage. 2 SQL: an Overview SQL (Structured Query Language) –Also be pronounced as “sequel” –A relational database language –Consists.
1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for.
Subqueries CIS 4301 Lecture Notes Lecture /23/2006.
1 Data Modification with SQL CREATE TABLE, INSERT, DELETE, UPDATE Slides from
More SQL: Complex Queries, Triggers, Views, and Schema Modification
CPSC-310 Database Systems
Lecture 05: SQL Wednesday, January 12, 2005.
Chap 5. The DB Language (SQL)
Introduction to Structured Query Language (SQL)
THE RELATIONAL MODEL OF DATA
CPSC-608 Database Systems
Introduction to Database Systems CSE 444 Lecture 04: SQL
SQL: Concept and Usage.
SQL This presentation will cover: View in database MySQL installation
SQL Introduction Standard language for querying and manipulating data
Lecture 12: SQL Friday, October 20, 2000.
SQL – Constraints & Triggers
CMSC-461 Database Management Systems
Lecture 14: SQL Wednesday, October 31, 2001.
Presentation transcript:

1 Chapter 6 More SQL uDatabase Modification uDefining a Database Schema uViews

2 More SQL uDatabase Modification uDefining a Database Schema uViews

3 Database Modifications uA modification command does not return a result (as a query does), but changes the database in some way. uThree kinds of modifications: 1.Insert a tuple or tuples. 2.Delete a tuple or tuples. 3.Update the value(s) of an existing tuple or tuples.

4 Insertion uTo insert a single tuple: INSERT INTO VALUES ( ); uExample: add Sydney Greenstreet to the list of stars of The Maltese Falcon. INSERT INTO StarsIn VALUES(‘The Maltese Falcon’, 1942, ’Sydney GreenStreet’ );

5 Specifying Attributes in INSERT uWe may add to the relation name a list of attributes. uTwo reasons to do so: 1.We forget the standard order of attributes for the relation. 2.We don’t have values for all attributes, and we want the system to fill in missing components with NULL or a default value.

6 Example: Specifying Attributes uAnother way to add Sydney Greenstreet to the list of stars of The Maltese Falcon. INSERT INTO StarsIn(movieTitle, movieYear, starName) VALUES(’The Maltese Falcon’, 1942, ’Sydney GreenStreet’);

7 Inserting Many Tuples uWe may insert the entire result of a query into a relation, using the form: INSERT INTO ( );

8 Example: Insert a Subquery uUsing Studio and Movie, add to the relation Studio all movie studios that are mentioned in the relation Movie, but don’t appear in Studio.

9 Solution INSERT INTO Studio(name) (SELECT DISTINCT studioName FROM Movie WHERE studioName NOT IN (SELECT name FROM Studio));

10 Deletion uTo delete tuples satisfying a condition from some relation: DELETE FROM WHERE ;

11 Example: Deletion uDelete from relation StarsIn the fact that Sydney GreenStreet was a star in The Maltese Falcon: DELETE FROM StarsIn WHERE movieTitle = ‘The Maltese Falcon’ AND movieYear = 1942 AND starName = ‘Sydney Greenstreet’;

12 Example: Delete all Tuples uMake the relation Likes empty: DELETE FROM Likes; uNote no WHERE clause needed.

13 Example: Delete Many Tuples uDelete from MovieExec all movie executives whose net worth is low-less than ten million dollars. DELETE FROM MovieExec WHERE netWorth < ;

14 Example: Delete With subqueries uDelete from relation Movie in which Sydney GreenStreet was a star : DELETE FROM Movie WHERE Exists ( SELECT * FROM StarsIN WHERE movieTitle title AND movieYear = year);

15 Updates uTo change certain attributes in certain tuples of a relation: UPDATE SET WHERE ;

16 Example: Update uModify the relation MovieExec by prepending the title Pres. In front of every movie executives who is the president of a studio: UPDATE MovieExec SET name = ‘Pres. ’ || name WHERE cert# IN ( SELECT presC# FROM Studio);

17 Defining a Database Schema uA database schema comprises declarations for the relations (“tables”) of the database. uSeveral other kinds of elements also may appear in the database schema, including views, indexes, and triggers, which we’ll introduce later.

18 Creating (Declaring) a Relation uSimplest form is: CREATE TABLE ( ); uTo delete a relation: DROP TABLE ;

19 Elements of Table Declarations uMost basic element: an attribute and its type. uThe most common types are: wINT or INTEGER wREAL or FLOAT wCHAR(n ) fixed-length string of n characters. wVARCHAR(n ) variable-length string of up to n characters.

20 Example: Create Table CREATE TABLE MovieStar ( nameCHAR(30), addressVARCHAR(255), genderCHAR(1), birthdateDATE );

21 Modifying relation schemas uWe can use ALTER to modify a relation schema. We have several options, the most important of which are: wADD followed by a column name and its data type; wDROP followed by a column name;

22 Adding Attributes uWe may add a new attribute (“column”) to a relation schema by: ALTER TABLE ADD ; uExample: ALTER TABLE MovieStar ADD phone CHAR(16);

23 Deleting Attributes uRemove an attribute from a relation schema by: ALTER TABLE DROP ; uExample: we don’t really need the license attribute for bars: ALTER TABLE MovieStar DROP birthdate;

24 Default values uWhen we create or modify tuples, we sometimes don’t have values for all components. uTo address this problem, SQL provides the NULL value. uHowever, there are times when we would prefer to use default value, the value that is placed in a component if no other value is known.

25 Example uWe might wish to use the character ‘?’ as the default for an unknown gender, and we might also wish to use the earliest possible date, DATE ‘ ’ for an unknown birthdate. CREATE TABLE MovieStar ( name CHAR(30), address VARCHAR(255), gender CHAR(1) DEFAULT ‘?’, birthdate SHORTDATETIME DEFAULT ‘ ’ );

26 Indexes uAn index on an attribute A of a relation is a data structure that makes it efficient to find those tuples that have a fixed value for attribute A.

27 Example of Sparse Index Files

28 Example of a B + -tree B + -tree for account file (n = 3)

29 To create a index uCreate an index on attribute year for the relation Movie CREATE INDEX YearIndex ON Movie(year); uFrom Movie, create an index on title and year CREATE INDEX KeyIndex ON Movie(title, year);

30 To delete a index uIf we wish to delete the index, we simply use its name in a statement like: DROP INDEX YearIndex; uSelection of indexes requires a trade-off by the database designer wThe existence of an index on an attribute greatly speeds up queries in which a value for that attribute is specified. wOn the other hand, ervery index built for an attribute of some relation makes insertions, deletion, and updates to that relation more complex and time- consuming.

31 Views uA view is a “virtual table” = a relation defined in terms of the contents of other tables and views. uDeclare by: CREATE VIEW AS ; uAntonym: a relation whose value is really stored in the database is called a base table.

32 Example: View Definition uTo define a view that is a part of the Movie relation, specifically, the titles and years of the movies made by Paramount Studio: CREATE VIEW ParamountMovie AS SELECT title, year FROM Movie WHERE studioName = ‘Paramount’;

33 Example: Accessing a View uQuery a view as if it were a base table. wAlso: a limited ability to modify views if it makes sense as a modification of one underlying base table. uExample query: SELECT title FROM ParamountMovie WHERE year = 1979;

34 What Happens When a View Is Used? uThe SQL system will translate the query on the view ParamountMovie into a query about the base table Movie that has the same effect as our original query. SELECT title FROM Movie WHERE studioName = ‘Paramount’ AND year = 1979;

35 Define a query based on views and base tables uExample: SELECT DISTINCT starName FROM ParamountMovie, StarsIn WHERE title = movieTitle AND year = movieYear;

36 Renaming attributes uWe can give a view’s attributes names of our own choosing. For example: CREATE VIEW MovieProd(movieTitle, prodName) AS SELECT title, name FROM Movie, MovieExec WHERE producerC# = cert#;

37 Delete a view uIf a view becomes unuseful, we can delete it. For instance: DROP VIEW ParamountMovie;

38 NULL Values uTuples in SQL relations can have NULL as a value for one or more components. uMeaning depends on context. Two common cases: wMissing value : e.g., we know Joe’s Bar has some address, but we don’t know what it is. wInapplicable : e.g., the value of attribute spouse for an unmarried person.

39 Two important rules uWhen we operate on a NULL and any other value, including another NULL, using an arithmetic operator like × or +, the result is NULL. uWhen we compare a NULL value and any value, including another NULL, using a comparison operator like = or >, the result is UNKNOWN. The value UNKNOWN is another truth-value, like TRUE and FALSE.

40 To ask if x has the value NULL ux IS NULL, this expression have the value TRUE if x has the value NULL and it has FALSE otherwise. ux IS NOT NULL, this expression have the value FALSE if x has the value NULL and it has TRUE otherwise

41 Comparing NULL’s to Values uThe logic of conditions in SQL is really 3-valued logic: TRUE, FALSE, UNKNOWN. uBut a query only produces a tuple in the answer if its truth value for the WHERE clause is TRUE (not FALSE or UNKNOWN).

42 Exercises of SQL uAnswer the following questions, based on the database below. wSupplier (SNO, SNAME, STATUS, CITY) wPart(PNO, PNAME, COLOR, WEIGHT) wProject(JNO, JNAME, CITY) wSPJ(SNO, PNO, JNO, QTY) uThe schema has four relations. The key attributes for each relation are shown in red.

43 u1.Give suitable declarations for each relation. u2.Write the following queries: w(1)Find the name and city of all the Supplier. w(2)Find the name, color and weight of all the parts. w(3)Find the number of all the projects using the parts that provided by S1. w(4)Find the name and quantity of all the parts used by J2. w(5)Find the number of all the parts made in ShangHai. w(6)Find the name of all the projects which have used the parts made in ShangHai.

44 w(7)Find the number of all the projects that didn’t used the parts made in TianJin. w(8)Update all the parts which color is red with blue. w(9)Update the Supplier S5 of the part P6 used by J4 with Supplier S3. w(10)Delete all the records about S2 from relation Supplier, and delete corresponding records from relation SPJ. w(11)Insert a new record(S2, J6, P4, 200) into relation Supplier. w(12)Grant the INSERT privilege on table Supplier to user John, and he includes the grant option with this privilege. w(13)Grant the SELECT privilege on table SPJ and UPDATE privilege on attribute QTY of SPJ to user Allice.

45 u3.Construct a view ThirdProj giving the Supplier number(Sno), part number(Pno), supporting quantity(QTY) of all Supplier who provide parts for “Third Project”. Write each of the queries using this view. w(1)Find the part number and supporting quantity of all parts used by “Third Project”. w(2)Find the supporting relation of S1.