Sei sulla pagina 1di 77

Modern Database Management 10th Edition Jeffrey A. Hoffer, Mary B.

Prescott, Heikki Topi

Definition of terms Interpret history and role of SQL Define a database using SQL data definition language Write single table queries using SQL Establish referential integrity using SQL Discuss SQL:1999 and SQL:200n standards

Normalization theory is based on the observation that


relations with certain properties are more effective in inserting, updating and deleting data than other sets of relations containing the same data

Normalization is a multi-step process beginning with an unnormalized relation

No transitive dependenc y between nonkey attributes

BoyceCodd and Higher

Functional dependenc y of non key attributes on the primary key - Atomic values only Full Functional dependenc y of nonkey attributes on the primary key

All determinants are candidate keys - Single multivalued dependency

Relational Algebra is a collection of operators that take relations as their operands and return a relation as their results First defined by Codd
Include 8 operators
4 derived from traditional set operators 4 new relational operations

From: C.J. Date, Database Systems 8th ed.


5

Restrict Project Product Union Intersect Difference Join Divide

Extracts specified tuples (rows) from a specified relation (table)


Restrict is AKA Select

Extracts specified attributes(columns) from a specified relation.

Builds a relation from two specified relations consisting of all possible concatenated pairs of tuples, one from each of the two relations. (AKA Cartesian Product)
Product
a b c x y a a b b c c x y x y x y

Builds a relation consisting of all tuples appearing in either or both of two specified relations.

10

Builds a relation consisting of all tuples appearing in both of two specified relations

11

Builds a relation consisting of all tuples appearing in first relation but not the second.

12

Builds a relation from two specified relations consisting of all possible concatenated pairs, one from each of the two relations, such that in each pair the two tuples satisfy some condition. (E.g., equal values in a given col.)
(Natural or Inner) Join

A1 B1 A2 B1 A3 B2

B1 C1 B2 C2 B3 C3

A1 B1 C1 A2 B1 C1 A3 B2 C2

13

Outer Joins are similar to PRODUCT -- but will leave NULLs for any row in the first table with no corresponding rows in the second.

Outer Join A1 A2 A3 A4 B1 B1 B2 B7 B1 C1 B2 C2 B3 C3

A1 B1 C1 A2 B1 C1 A3 B2 C2 A4 * *

14

Takes two relations, one binary and one unary, and builds a relation consisting of all values of one attribute of the binary relation that match (in the other attribute) all values in the unary relation.
Divide a a a b c x y z x y a

x y

15

Structured Query Language The standard for relational database management systems (RDBMS)

RDBMS: A database management system that manages data as a collection of tables in which all relationships are represented by common values in related tables

16

1970E. Codd develops relational database concept 1974-1979System R with Sequel (later SQL) created at IBM Research Lab 1979Oracle markets first relational DB with SQL 1986ANSI SQL standard released 1989, 1992, 1999, 2003Major ANSI standard updates CurrentSQL is supported by most major database vendors

17

Structured Query Language Used for both Database Definition, Modification and Querying Basic language is standardized across relational DBMSs. Each system may have proprietary extensions to standard. Relational Calculus combines Restrict, Project and Join operations in a single command. SELECT.

18

Specify syntax/semantics for data definition and manipulation Define data structures Enable portability Specify minimal (level 1) and complete (level 2) standards Allow for later growth/enhancement to standard

19

Reduced training costs Productivity Application portability Application longevity Reduced dependence on a single vendor Cross-system communication

20

SQL Data Types

NEW IN SQL99

Predefined Types
Numeric

Ref Types

Arrays

User-Defined Types
DateTime Interval

ROW Data Struct


Boolean

String

Bit Exact Approximate

Character

Blob Fixed Varying

Date

Time

Fixed
Varying

Timestamp

CLOB
21

Catalog

A set of schemas that constitute the description of a database

Schema

The structure that contains descriptions of objects created by a user (base tables, views, constraints)

Data Definition Language (DDL)

Commands that define a database, including creating, altering, and dropping tables and establishing constraints

Data Manipulation Language (DML)


Data Control Language (DCL)

Commands that maintain and query a database

Commands that control a database, including administering privileges and committing data
22

Figure 7-1 A simplified schematic of a typical SQL environment, as described by the SQL: 200n standard

23

24

Figure 6-4 10th edition or Figure 7-4 9th edition DDL, DML, DCL, and the database development process

25

Data Definition Language (DDL) Major CREATE statements:


CREATE SCHEMAdefines a portion of the database owned by a particular user CREATE TABLEdefines a table and its columns CREATE VIEWdefines a logical table from one or more tables or views

26

CHARACTER SET(other than English), COLLATION(order that a character set will assume), TRANSLATION(rules that maps characters from a source character to destination), ASSERTION (check constraints), DOMAIN (set of valid values)

27

Steps in table creation:


Figure 7-5 General syntax for CREATE TABLE

1. Identify data types for attributes 2. Identify columns that can and cannot be null 3. Identify columns that must be unique (candidate keys) 4. Identify primary key foreign key mates 5. Determine default values 6. Identify constraints on columns (domain specifications) 7. Create the table and associated indexes
28

29

Figure 7-6 SQL database definition commands for Pine Valley Furniture
p,s precision and scale Length and decimal

Overall table definitions

30

Defining attributes and their data types

31

Non-nullable specification

Primary keys can never have NULL values

Identifying primary key


32

Non-nullable specifications

Primary key

Some primary keys are composite composed of multiple attributes

33

Controlling the values in attributes


Default value

Domain constraint

34

Identifying foreign keys and establishing relationships

Primary key of parent table

Foreign key of dependent table

35

Referential integrityconstraint that ensures that foreign key values of a table must match primary key values of a related table in 1:M relationships Restricting:
Deletes of primary records Updates of primary records Inserts of dependent records

36

Figure 7-7 Ensuring data integrity through updates

Relational integrity is enforced via the primarykey to foreignkey match

37

ALTER TABLE statement allows you to change column specifications:


ALTER TABLE CUSTOMER_T VARCHAR(2); ADD TYPE

DROP TABLE statement allows you to remove tables from your schema:
DROP TABLE CUSTOMER_T

38

Adds data to a table Inserting into a table

INSERT INTO CUSTOMER_T VALUES (001, Contemporary Casuals, 1355 S. Himes Blvd., Gainesville, FL, 32601); VALUE s Sequence!!!

39

Inserting

a record that has some null attributes requires identifying the fields that actually get data
INSERT INTO PRODUCT_T (PRODUCT_ID, PRODUCT_DESCRIPTION,PRODUCT_FINISH, STANDARD_PRICE, PRODUCT_ON_HAND) VALUES (1, End Table, Cherry, 175, 8);

40

Inserting

INSERT INTO CA_CUSTOMER_T SELECT * FROM CUSTOMER_T WHERE STATE = CA;


A SUBSET from another table

from another table

41

New with SQL:2003/SQL:200n

Inserting into a table does not require explicit customer ID entry or field list INSERT INTO CUSTOMER_T VALUES ( Contemporary Casuals, 1355 S. Himes Blvd., Gainesville, FL, 32601); INSERT INTO CUSTOMER_T VALUES (001, Contemporary Casuals, 1355 S. Himes Blvd., Gainesville, 42 FL, 32601);

Removes rows from a table Delete certain rows


DELETE FROM CUSTOMER_T WHERE STATE = HI;

Delete all rows


DELETE FROM CUSTOMER_T; Careful!!!

43

Modifies data in existing rows

UPDATE PRODUCT_T SET UNIT_PRICE = 775 WHERE PRODUCT_ID = 7; Note: the WHERE clause may be a subquery

44

Makes it easier to update a tableallows combination of Insert and Update in one statement Useful for updating master tables with new data
45

Control processing/storage efficiency:


Choice of indexes File organizations for base tables File organizations for indexes Data clustering Statistics maintenance

Creating indexes

Speed up random/sequential access to base table data Example


CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMER_NAME) This makes an index for the CUSTOMER_NAME field of the CUSTOMER_T table

46

Creating

Example

indexes

Remove index:

CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMER_NAME); This makes an index for the CUSTOMER_NAME field of the CUSTOMER_T table
DROP INDEX NAME_IDX;

47

Clauses of the SELECT statement: (Sequence!!)


SELECT FROM
List the columns (and expressions) that should be returned from the query

WHERE

Indicate the table(s) or view(s) from which data will be obtained


Indicate the conditions under which a row will be included in the result Indicate categorization of results Indicate the conditions under which a category (group) will be included Sorts the result according to specified criteria
48

GROUP BY
HAVING

ORDER BY

Figure 7-10 SQL statement processing order (adapted from van der Lans, p.100)

49

SELECT Conditions 1. = equal to a particular value 2. >= greater than or equal to a particular value 3. > greater than a particular value 4. <= less than or equal to a particular value 5. <> not equal to a particular value 6. LIKE *term* (may be other wild cards in other systems) 7. IN (opt1, opt2,,optn) 8. BETWEEN val1 AND val2 9. IS NULL

50

Find products with standard price less than $275


SELECT PRODUCT_NAME, STANDARD_PRICE FROM PRODUCT_V WHERE STANDARD_PRICE < 275;

Table 7-3: Comparison Operators in SQL


51

Alias is an alternative column or table name

SELECT CUST.CUSTOMER_NAME AS NAME, CUST.CUSTOMER_ADDRESS FROM CUSTOMER_V AS CUST WHERE NAME = Home Furnishings;

52

What is average standard price for each product in inventory?


SELECT AVG (STANDARD_PRICE) AS AVERAGE FROM PROCUCT_V;

AVG, COUNT, MAX, MIN, SUM; LN, EXP, POWER, SQRT

53

Using the COUNT aggregate function to find totals


SELECT COUNT (*) FROM ORDER_LINE_V WHERE ORDER_ID = 1004;

Note 1: with aggregate functions you cant have singlevalued columns included in the SELECT clause -SELECT PRODUCT_ID, COUNT(*) FROM ORDER_LINE_V WHERE ORDER_ID = 1004; Note 1: CPOUNT (*) and COUNT

54

AND, OR, and NOT Operators for customizing conditions in WHERE clause
SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICE FROM PRODUCT_V WHERE (PRODUCT_DESCRIPTION LIKE %Desk OR PRODUCT_DESCRIPTION LIKE %Table) AND STANDARD_PRICE > 300;

Note: the LIKE operator allows you to compare strings using wildcards. For example, the % wildcard in %Desk indicates that all strings that have any number of characters preceding the word Desk will be allowed

55

56

Compare:
SELECT ORDER_ID FROM ORDER_LINE_V; and SELECT DISTINCT ORDER_ID FROM ORDER_LINE_V; But: SELECT DISTINCT ORDER_ID, ORDER_QUANTITY FROM ORDER_LINE_V;

57

Sort the results first by STATE, and within a state by CUSTOMER_NAME


SELECT CUSTOMER_NAME, CITY, STATE FROM CUSTOMER_V WHERE STATE IN (FL, TX, CA, HI) ORDER BY STATE, CUSTOMER_NAME;

Note: the IN operator in this example allows you to include rows whose STATE value is either FL, TX, CA, or HI. It is more efficient than

separate OR conditions
58

For use with aggregate functions


Scalar aggregate: single value returned from SQL query with aggregate function Vector aggregate: multiple values returned from SQL query with aggregate function (via GROUP BY)

SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE) FROM CUSTOMER_V GROUP BY CUSTOMER_STATE; Note: you can use single-value fields with aggregate functions *if* they are included in the GROUP BY clause; OR: (in an aggregate function)
59

For use with GROUP BY


SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE) FROM CUSTOMER_V GROUP BY CUSTOMER_STATE HAVING COUNT(CUSTOMER_STATE) > 1;
Like a WHERE clause, but it operates on groups (categories), not on individual rows. Here, only those groups with total numbers greater than 1 will be included in final result
60

Views provide users controlled access to tables Base Tabletable containing the raw data Dynamic View

Materialized View

A virtual table created dynamically upon request by a user No data actually stored; instead data from base table made available to user Based on SQL SELECT statement on base tables or other views Copy or replication of data Data actually stored Must be refreshed periodically to match the corresponding base tables

61

CREATE VIEW EXPENSIVE_STUFF_V AS SELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICE FROM PRODUCT_T WHERE UNIT_PRICE >300 WITH CHECK_OPTION;

View has a name View is based on a SELECT statement CHECK_OPTION works only for
updateable views and prevents updates that would create rows not included in the view
62

Simplify query commands Assist with data security (but don't rely on views for security, there are more important security measures) Enhance programming productivity Contain most current base table data Use little storage space Provide customized view for user Establish physical data independence

63

Use processing time each time view is referenced May or may not be directly updateable

64

Relating to Slide 38/39


SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICE FROM PRODUCT_V WHERE (PRODUCT_DESCRIPTION LIKE %Desk OR PRODUCT_DESCRIPTION LIKE %Table) AND STANDARD_PRICE > 300; Compare no parentheses: SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICE FROM PRODUCT_V WHERE PRODUCT_DESCRIPTION LIKE %Desk OR PRODUCT_DESCRIPTION LIKE %Table AND STANDARD_PRICE > 300;
65

66

67

Addendum for 3/28 class(1) HAVING clause


P. 341: The HAVING clause acts like a WHERE clause, but it identifies groups that meet a criterion, rather than rows.
Therefore, you will usually see a HAVING clause

WHERE qualifies a set of rows, while HAVING

68

Addendum for 3/28 class(2) Views


P. 343: Syntax of CREATE VIEW: CREATE VIEW view-name AS SELECT (that provides the rows and columns of the view)
Example P. 344:
CREATE VIEW ORDER_TOTALS_V AS SELECT PRODUCT_ID PRODUCT, SUM(STANDARD_PRICE*QUANTITY) TOTAL FROM INVOICE_V GROUP BY PRODUCT_ID;

69

Every loan has at least one borrower who maintains an account with a minimum balance or $1000.00 create assertion balance_constraint check (not exists ( select * from loan where not exists ( select * from borrower, depositor, account where loan.loan_number = borrower.loan_number and borrower.customer_name =

depositor.customer_name and depositor.account_number = account.account_number and account.balance >= 1000)))

Reference: Korth

70

The sum of all loan amounts for each branch must be less than the sum of all account balances at the branch. create assertion sum_constraint check (not exists (select * from branch where (select sum(amount ) from loan where loan.branch_name =

branch.branch_name ) >= (select sum (amount ) from account where loan.branch_name = branch.branch_name )))

71

Forms of authorization on parts of the database:


Read - allows reading, but not modification of data. Insert - allows insertion of new data, but not modification of existing data. Update - allows modification, but not deletion of data. Delete - allows deletion of data.

Forms of authorization to modify the database schema (covered in Chapter 8): Index - allows creation and deletion of indices. Resources - allows creation of new relations. Alteration - allows addition or deletion of attributes in a relation. Drop - allows deletion of relations.
72

The grant statement is used to confer authorization grant <privilege list> on <relation name or view name> to <user list> <user list> is:
a user-id public, which allows all valid users the privilege granted A role (more on this in Chapter 8)

Granting a privilege on a view does not imply granting any privileges on the underlying relations. The grantor of the privilege must already hold the privilege on the specified item (or be the database administrator).
73

select: allows read access to relation,or the ability to query using the view grant select on branch to U1, U2, U3 insert: the ability to insert tuples update: the ability to update using the SQL update statement delete: the ability to delete tuples. all privileges: used as a short form for all the allowable privileges more in Chapter 8
74

Example: grant users U1, U2, and U3 select authorization on the branch relation:

The revoke statement is used to revoke authorization.


revoke <privilege list> on <relation name or view name> from <user list>

Example:

All privileges that depend on the privilege being revoked are also revoked. <privilege-list> may be all to revoke all privileges the revokee may hold. If the same privilege was granted twice to the same user by different grantees, the user may retain the privilege after the revocation.
75

revoke select on branch from U1, U2, U3

EXEC SQL statement is used to identify embedded SQL request to the preprocessor
EXEC SQL <embedded SQL statement > END_EXEC

Note: this varies by language (for example, the Java embedding uses # SQL { . }; ) From within a host language, find the names and cities of customers with more than the variable amount dollars in some account.
76

Specify the query in SQL and declare a cursor for it EXEC SQL declare c cursor for select depositor.customer_name, customer_city from depositor, customer, account where depositor.customer_name =

customer.customer_name and depositor account_number = account.account_number and account.balance > :amount


END_EXEC

77

Potrebbero piacerti anche