© 2007 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 8 th Edition...

42
© 2007 by Prentice Hall © 2007 by Prentice Hall 1 Chapter 7: Chapter 7: Introduction to SQL Introduction to SQL Modern Database Management Modern Database Management 8 8 th th Edition Edition Jeffrey A. Hoffer, Mary B. Prescott, Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden Fred R. McFadden
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    224
  • download

    1

Transcript of © 2007 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 8 th Edition...

© 2007 by Prentice Hall© 2007 by Prentice Hall 11

Chapter 7:Chapter 7:Introduction to SQLIntroduction to SQL

Modern Database Modern Database ManagementManagement

88thth Edition EditionJeffrey A. Hoffer, Mary B. Prescott, Jeffrey A. Hoffer, Mary B. Prescott,

Fred R. McFaddenFred R. McFadden

22Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

ObjectivesObjectives Definition of termsDefinition of terms Interpret history and role of SQL Interpret history and role of SQL Define a database using SQL data Define a database using SQL data

definition languagedefinition language Write single table queries using SQLWrite single table queries using SQL Establish referential integrity using SQLEstablish referential integrity using SQL Discuss SQL:1999 and SQL:2003 Discuss SQL:1999 and SQL:2003

standardsstandards

33Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SQL OverviewSQL Overview Structured Query LanguageStructured Query Language

The standard for relational database The standard for relational database management systems (RDBMS) management systems (RDBMS)

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

44Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

History of SQLHistory of SQL 1970–E. Codd develops relational database 1970–E. Codd develops relational database

conceptconcept 1974-1979–System R with Sequel (later SQL) 1974-1979–System R with Sequel (later SQL)

created at IBM Research Labcreated at IBM Research Lab 1979–Oracle markets first relational DB with SQL1979–Oracle markets first relational DB with SQL 1986–ANSI SQL standard released1986–ANSI SQL standard released 1989, 1992, 1999, 2003–Major ANSI standard 1989, 1992, 1999, 2003–Major ANSI standard

updatesupdates Current–SQL is supported by most major Current–SQL is supported by most major

database vendorsdatabase vendors

55Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Purpose of SQL StandardPurpose of SQL Standard Specify syntax/semantics for data Specify syntax/semantics for data

definition and manipulationdefinition and manipulation Define data structuresDefine data structures Enable portabilityEnable portability Specify minimal (level 1) and complete Specify minimal (level 1) and complete

(level 2) standards(level 2) standards Allow for later growth/enhancement to Allow for later growth/enhancement to

standardstandard

66Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Benefits of a Standardized Benefits of a Standardized Relational LanguageRelational Language

Reduced training costsReduced training costs ProductivityProductivity Application portabilityApplication portability Application longevityApplication longevity Reduced dependence on a single Reduced dependence on a single

vendorvendor Cross-system communicationCross-system communication

77Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SQL EnvironmentSQL Environment CatalogCatalog

A set of schemas that constitute the description of a databaseA set of schemas that constitute the description of a database SchemaSchema

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

Data Definition Language (DDL)Data Definition Language (DDL) Commands that define a database, including creating, altering, Commands that define a database, including creating, altering,

and dropping tables and establishing constraintsand dropping tables and establishing constraints Data Manipulation Language (DML)Data Manipulation Language (DML)

Commands that maintain and query a databaseCommands that maintain and query a database Data Control Language (DCL)Data Control Language (DCL)

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

88Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

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

99Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Some SQL Data types Some SQL Data types

1010Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Figure 7-4 DDL, DML, DCL, and the database development process

1111Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SQL Database DefinitionSQL Database Definition Data Definition Language (DDL)Data Definition Language (DDL) Major CREATE statements:Major CREATE statements:

CREATE SCHEMA–defines a portion of the CREATE SCHEMA–defines a portion of the database owned by a particular userdatabase owned by a particular user

CREATE TABLE–defines a table and its CREATE TABLE–defines a table and its columnscolumns

CREATE VIEW–defines a logical table from CREATE VIEW–defines a logical table from one or more viewsone or more views

Other CREATE statements: CHARACTER Other CREATE statements: CHARACTER SET, COLLATION, TRANSLATION, SET, COLLATION, TRANSLATION, ASSERTION, DOMAINASSERTION, DOMAIN

1212Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Table CreationTable CreationFigure 7-5 General syntax for CREATE TABLE

Steps in table creation:

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

1313Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

The following slides create tables The following slides create tables for this enterprise data modelfor this enterprise data model

1414Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Figure 7-6 SQL database definition commands for Pine Valley Furniture

Overall table definitions

1515Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Defining attributes and their data types

1616Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Non-nullable specification

Identifying primary key

Primary keys can never have NULL values

1717Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Non-nullable specifications

Primary key

Some primary keys are composite– composed of multiple attributes

1818Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Default value

Domain constraint

Controlling the values in attributes

1919Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Primary key of parent table

Identifying foreign keys and establishing relationships

Foreign key of dependent table

2020Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Data Integrity ControlsData Integrity Controls Referential integrity–constraint Referential integrity–constraint

that ensures that foreign key that ensures that foreign key values of a table must match values of a table must match primary key values of a related primary key values of a related table in 1:M relationshipstable in 1:M relationships

Restricting:Restricting: Deletes of primary recordsDeletes of primary records Updates of primary recordsUpdates of primary records Inserts of dependent recordsInserts of dependent records

2121Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Relational integrity is enforced via the primary-key to foreign-key match

Figure 7-7 Ensuring data integrity through updates

2222Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Changing and Removing Changing and Removing TablesTables

ALTER TABLE statement allows you ALTER TABLE statement allows you to change column specifications:to change column specifications: ALTER TABLE CUSTOMER_T ADD (TYPE ALTER TABLE CUSTOMER_T ADD (TYPE

VARCHAR(2))VARCHAR(2)) DROP TABLE statement allows you to DROP TABLE statement allows you to

remove tables from your schema:remove tables from your schema: DROP TABLE CUSTOMER_TDROP TABLE CUSTOMER_T

2323Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Schema DefinitionSchema Definition Control processing/storage efficiency:Control processing/storage efficiency:

Choice of indexesChoice of indexes File organizations for base tablesFile organizations for base tables File organizations for indexesFile organizations for indexes Data clusteringData clustering Statistics maintenanceStatistics maintenance

Creating indexesCreating indexes Speed up random/sequential access to base table dataSpeed up random/sequential access to base table data ExampleExample

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

CUSTOMER_T tableCUSTOMER_T table

2424Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Insert StatementInsert Statement Adds data to a tableAdds data to a table Inserting into a tableInserting into a table

INSERT INTO CUSTOMER_T VALUES (001, ‘Contemporary INSERT INTO CUSTOMER_T VALUES (001, ‘Contemporary Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);32601);

Inserting a record that has some null attributes Inserting a record that has some null attributes requires identifying the fields that actually get requires identifying the fields that actually get datadata INSERT INTO PRODUCT_T (PRODUCT_ID, INSERT INTO PRODUCT_T (PRODUCT_ID,

PRODUCT_DESCRIPTION,PRODUCT_FINISH, STANDARD_PRICE, PRODUCT_DESCRIPTION,PRODUCT_FINISH, STANDARD_PRICE, PRODUCT_ON_HAND) VALUES (1, ‘End Table’, ‘Cherry’, 175, 8);PRODUCT_ON_HAND) VALUES (1, ‘End Table’, ‘Cherry’, 175, 8);

Inserting from another tableInserting from another table INSERT INTO CA_CUSTOMER_T SELECT * FROM CUSTOMER_T INSERT INTO CA_CUSTOMER_T SELECT * FROM CUSTOMER_T

WHERE STATE = ‘CA’;WHERE STATE = ‘CA’;

2525Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Creating Tables with Identity Creating Tables with Identity ColumnsColumns

Inserting into a table does not require explicit customer ID Inserting into a table does not require explicit customer ID entry or field listentry or field list

INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);

New with SQL:2003

2626Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Delete StatementDelete Statement

Removes rows from a tableRemoves rows from a table Delete certain rowsDelete certain rows

DELETE FROM CUSTOMER_T WHERE DELETE FROM CUSTOMER_T WHERE STATE = ‘HI’;STATE = ‘HI’;

Delete all rowsDelete all rows DELETE FROM CUSTOMER_T;DELETE FROM CUSTOMER_T;

2727Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Update StatementUpdate Statement

Modifies data in existing rowsModifies data in existing rows

UPDATE PRODUCT_T SET UNIT_PRICE = UPDATE PRODUCT_T SET UNIT_PRICE = 775 WHERE PRODUCT_ID = 7;775 WHERE PRODUCT_ID = 7;

2828Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Merge StatementMerge Statement

Makes it easier to update a table…allows combination of Insert and Update in one statement

Useful for updating master tables with new data

2929Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT StatementSELECT Statement Used for queries on single or multiple tablesUsed for queries on single or multiple tables Clauses of the SELECT statement:Clauses of the SELECT statement:

SELECTSELECT List the columns (and expressions) that should be returned from the queryList the columns (and expressions) that should be returned from the query

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

WHEREWHERE Indicate the conditions under which a row will be included in the resultIndicate the conditions under which a row will be included in the result

GROUP BYGROUP BY Indicate categorization of results Indicate categorization of results

HAVINGHAVING Indicate the conditions under which a category (group) will be includedIndicate the conditions under which a category (group) will be included

ORDER BYORDER BY Sorts the result according to specified criteriaSorts the result according to specified criteria

3030Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

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

3131Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT ExampleSELECT Example

Find products with standard price less Find products with standard price less than $275than $275

SELECTSELECT PRODUCT_NAME, STANDARD_PRICE PRODUCT_NAME, STANDARD_PRICE

FROMFROM PRODUCT_V PRODUCT_V

WHEREWHERE STANDARD_PRICE < 275; STANDARD_PRICE < 275;

Table 7-3: Comparison Operators in SQL

3232Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT Example Using AliasSELECT Example Using Alias

Alias is an alternative column or table Alias is an alternative column or table namename

SELECT SELECT CUSTCUST.CUSTOMER AS .CUSTOMER AS NAMENAME, , CUST.CUSTOMER_ADDRESS CUST.CUSTOMER_ADDRESS

FROM CUSTOMER_V FROM CUSTOMER_V CUSTCUST

WHERE WHERE NAMENAME = ‘Home = ‘Home Furnishings’;Furnishings’;

3333Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT Example SELECT Example Using a FunctionUsing a Function

Using the COUNT Using the COUNT aggregate functionaggregate function to find totalsto find totals

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

Note: with aggregate functions you can’t Note: with aggregate functions you can’t have single-valued columns included in the have single-valued columns included in the SELECT clauseSELECT clause

3434Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT Example–Boolean SELECT Example–Boolean OperatorsOperators

ANDAND, , OROR, and , and NOTNOT Operators for customizing Operators for customizing conditions in WHERE clauseconditions in WHERE clause

SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICESTANDARD_PRICE

FROM PRODUCT_VFROM PRODUCT_V

WHERE (PRODUCT_DESCRIPTION WHERE (PRODUCT_DESCRIPTION LIKELIKE ‘ ‘%%Desk’Desk’

OROR PRODUCT_DESCRIPTION PRODUCT_DESCRIPTION LIKELIKE ‘ ‘%%Table’) Table’)

ANDAND UNIT_PRICE > 300; UNIT_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

3535Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Venn Diagram from Previous Venn Diagram from Previous QueryQuery

3636Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT Example – SELECT Example – Sorting Results with the ORDER BY Sorting Results with the ORDER BY

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

SELECT CUSTOMER_NAME, CITY, STATESELECT CUSTOMER_NAME, CITY, STATE

FROM CUSTOMER_VFROM CUSTOMER_V

WHERE STATE WHERE STATE ININ (‘FL’, ‘TX’, ‘CA’, ‘HI’) (‘FL’, ‘TX’, ‘CA’, ‘HI’)

ORDER BYORDER BY STATE, CUSTOMER_NAME; 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

3737Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT Example– SELECT Example– Categorizing Results Using the GROUP BY Categorizing Results Using the GROUP BY

ClauseClause For use with aggregate functionsFor use with aggregate functions

Scalar aggregateScalar aggregate: single value returned from SQL query with : single value returned from SQL query with aggregate functionaggregate function

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

SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE) SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE)

FROM CUSTOMER_VFROM CUSTOMER_V

GROUP BYGROUP BY CUSTOMER_STATE; CUSTOMER_STATE;

Note: you can use single-value fields with aggregate Note: you can use single-value fields with aggregate functions if they are included in the GROUP BY clausefunctions if they are included in the GROUP BY clause

3838Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT Example– SELECT Example– Qualifying Results by Categories Qualifying Results by Categories

Using the HAVING ClauseUsing the HAVING Clause For use with GROUP BYFor use with GROUP BY

SELECT CUSTOMER_STATE, SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE) COUNT(CUSTOMER_STATE)

FROM CUSTOMER_VFROM CUSTOMER_V

GROUP BY CUSTOMER_STATEGROUP BY CUSTOMER_STATE

HAVINGHAVING COUNT(CUSTOMER_STATE) > 1; COUNT(CUSTOMER_STATE) > 1;

Like a WHERE clause, but it operates on groups (categories), not Like a WHERE clause, but it operates on groups (categories), not on individual rows. Here, only those groups with total numbers on individual rows. Here, only those groups with total numbers greater than 1 will be included in final resultgreater than 1 will be included in final result

3939Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Using and Defining ViewsUsing and Defining Views Views provide users controlled access to tablesViews provide users controlled access to tables Base Table–table containing the raw dataBase Table–table containing the raw data Dynamic ViewDynamic View

A “virtual table” created dynamically upon request by a user A “virtual table” created dynamically upon request by a user No data actually stored; instead data from base table made No data actually stored; instead data from base table made

available to useravailable to user Based on SQL SELECT statement on base tables or other viewsBased on SQL SELECT statement on base tables or other views

Materialized ViewMaterialized View Copy or replication of dataCopy or replication of data Data actually storedData actually stored Must be refreshed periodically to match the corresponding Must be refreshed periodically to match the corresponding

base tablesbase tables

4040Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Sample CREATE VIEWSample CREATE VIEWCREATE VIEW EXPENSIVE_STUFF_V ASCREATE VIEW EXPENSIVE_STUFF_V AS

SELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICESELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICE

FROM PRODUCT_TFROM PRODUCT_T

WHERE UNIT_PRICE >300WHERE UNIT_PRICE >300

WITH CHECK_OPTION;WITH CHECK_OPTION;

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

4141Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Advantages of ViewsAdvantages of Views Simplify query commandsSimplify query commands Assist with data security (but don't rely on Assist with data security (but don't rely on

views for security, there are more views for security, there are more important security measures)important security measures)

Enhance programming productivityEnhance programming productivity Contain most current base table dataContain most current base table data Use little storage spaceUse little storage space Provide customized view for userProvide customized view for user Establish physical data independenceEstablish physical data independence

4242Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Disadvantages of ViewsDisadvantages of Views Use processing time each time view Use processing time each time view

is referencedis referenced May or may not be directly May or may not be directly

updateableupdateable