Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 More SQL uDatabase Modification uDefining a Database Schema uViews.

Similar presentations


Presentation on theme: "1 More SQL uDatabase Modification uDefining a Database Schema uViews."— Presentation transcript:

1 1 More SQL uDatabase Modification uDefining a Database Schema uViews

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

3 3 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’);

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

5 5 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’);

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

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

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

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

10 10 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’;

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

12 12 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 < 10000000;

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

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

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

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

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

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

19 19 Dates and Times uDATE and TIME are types in SQL. uThe form of a date value is: DATE ’yyyy-mm-dd’ wExample: DATE ’2004-09-30’

20 20 Times as Values uThe form of a time value is: TIME ‘hh:mm:ss’ with an optional decimal point and fractions of a second following. wExample: TIME ‘15:30:02.5’

21 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 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 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 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 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 ‘0000-00-00’ for an unknown birthdate. CREATE TABLE MovieStar ( name CHAR(30), address VARCHAR(255), gender CHAR(1) DEFAULT ‘?’, birthdate DATE DEFAULT DATE ‘0000-00-00’ );

26 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 27 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);

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

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

30 30 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’;

31 31 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;

32 32 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;

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

34 34 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#;

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

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

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

38 38 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

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

40 40 Join Expressions uSQL provides several versions of joins. uThese expressions can be stand-alone queries or used in place of relations in a FROM clause.

41 41 Products and Natural Joins uNatural join: R NATURAL JOIN S; uProduct: R CROSS JOIN S; uExample: Likes NATURAL JOIN Serves; uRelations can be parenthesized subqueries, as well.

42 42 Theta Join uR JOIN S ON uExample: using Movie and StarIn: Movie JOIN StarIn ON title = movieTitle AND year = movieyear;

43 43 Outerjoins uR OUTER JOIN S is the core of an outerjoin expression. It is modified by: 1.Optional NATURAL in front of OUTER. 2.Optional ON after JOIN. 3.Optional LEFT, RIGHT, or FULL before OUTER. uLEFT = pad dangling tuples of R only. uRIGHT = pad dangling tuples of S only. uFULL = pad both; this choice is the default.

44 44 Example uMovieStar NATURAL FULL OUTER JOIN MovieExec; wWhere FULL can be replaced by LEFT or RIGHT uMovie FULL OUTER JOIN StarIn ON title = movieTitle AND year = movieYear; wWhere FULL can be replaced by LEFT or RIGHT

45 45 Exercises uP252, Exercise 5.1.2 uP262, Exercise 5.2.1 uP269, Exercise 5.3.1 uP277, Exercise 5.5.1 uP284, Exercise 5.6.1 uP292, Exercise 5.7.1 uP303, Exercise 5.8.1, 5.8.3


Download ppt "1 More SQL uDatabase Modification uDefining a Database Schema uViews."

Similar presentations


Ads by Google