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

39
© 2005 by Prentice Hall © 2005 by Prentice Hall 1 Chapter 7: Chapter 7: Introduction to SQL Introduction to SQL Modern Database Management Modern Database Management 7 7 th th Edition Edition Jeffrey A. Hoffer, Mary B. Prescott, Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden Fred R. McFadden

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

Page 1: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

© 2005 by Prentice Hall© 2005 by Prentice Hall 11

Chapter 7:Chapter 7:Introduction to SQLIntroduction to SQL

Modern Database Modern Database ManagementManagement

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

Fred R. McFaddenFred R. McFadden

Page 2: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

22Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

ObjectivesObjectives Definition of termsDefinition of terms Discuss advantages of standardized Discuss advantages of standardized

SQL 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 Work with ViewsWork with Views

Page 3: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

33Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

The Physical Design Stage of SDLC The Physical Design Stage of SDLC (Figures 2-4, 2-5 revisited)(Figures 2-4, 2-5 revisited)

Purpose –programming, testing, training, installation, documentingDeliverable – operational programs, documentation, training materials, program/data structures

Database activity – physical database design anddatabase implementation

Project Identification and Selection

Project Initiation and Planning

Analysis

Physical Design

Implementation

Maintenance

Logical Design

Implementation

Physical Design

Page 4: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

44Chapter 7 © 2005 by Prentice Hall© 2005 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) SQL-92 and SQL-99 Standards – Purpose:SQL-92 and SQL-99 Standards – Purpose:

Specify syntax/semantics for data definition and Specify syntax/semantics for data definition and manipulationmanipulation

Define data structuresDefine data structures Enable portabilityEnable portability Specify minimal (level 1) and complete (level 2) Specify minimal (level 1) and complete (level 2)

standardsstandards Allow for later growth/enhancement to standardAllow for later growth/enhancement to standard

Page 5: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

55Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 6: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

66Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 7: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

77Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

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

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

88Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

Some SQL Data types Some SQL Data types (from Oracle 9i)(from Oracle 9i)

String typesString types CHAR(n) – fixed-length character data, n characters long CHAR(n) – fixed-length character data, n characters long

Maximum length = 2000 bytesMaximum length = 2000 bytes VARCHAR2(n) – variable length character data, maximum 4000 VARCHAR2(n) – variable length character data, maximum 4000

bytesbytes LONG – variable-length character data, up to 4GB. Maximum 1 LONG – variable-length character data, up to 4GB. Maximum 1

per tableper table Numeric typesNumeric types

NUMBER(p,q) – general purpose numeric data typeNUMBER(p,q) – general purpose numeric data type INTEGER(p) – signed integer, p digits wideINTEGER(p) – signed integer, p digits wide FLOAT(p) – floating point in scientific notation with p binary FLOAT(p) – floating point in scientific notation with p binary

digits precisiondigits precision Date/time typeDate/time type

DATE – fixed-length date/time in dd-mm-yy formDATE – fixed-length date/time in dd-mm-yy form

Page 9: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

99Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

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

Page 10: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1010Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 11: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1111Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 12: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1212Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

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

Page 13: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1313Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

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

Overall table definitions

Page 14: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1414Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

Defining attributes and their data types

Page 15: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1515Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

Non-nullable specification

Identifying primary key

Primary keys can never have NULL values

Page 16: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1616Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

Non-nullable specifications

Primary key

Some primary keys are composite – composed of multiple attributes

Page 17: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1717Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

Default value

Domain constraint

Controlling the values in attributes

Page 18: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1818Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

Primary key of parent table

Identifying foreign keys and establishing relationships

Foreign key of dependent table

Page 19: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

1919Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 20: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2020Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

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

Page 21: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2121Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 22: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2222Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 23: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2323Chapter 7 © 2005 by Prentice Hall© 2005 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’;

Page 24: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2424Chapter 7 © 2005 by Prentice Hall© 2005 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;

Page 25: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2525Chapter 7 © 2005 by Prentice Hall© 2005 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;

Page 26: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2626Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 27: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2727Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

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

Page 28: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2828Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 29: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

2929Chapter 7 © 2005 by Prentice Hall© 2005 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 Furnishings’; = ‘Home Furnishings’;

Page 30: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3030Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 31: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3131Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 32: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3232Chapter 7 © 2005 by Prentice Hall© 2005 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 BY STATE, CUSTOMER_NAME;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

Page 33: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3333Chapter 7 © 2005 by Prentice Hall© 2005 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 : single value returned from SQL query with aggregate functionwith aggregate function

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

SELECT STATE, COUNT(STATE) SELECT STATE, COUNT(STATE)

FROM CUSTOMER_VFROM CUSTOMER_V

GROUP BYGROUP BY STATE; 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 functions if they are included in the GROUP BY clauseclause

Page 34: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3434Chapter 7 © 2005 by Prentice Hall© 2005 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 STATE, COUNT(STATE) SELECT STATE, COUNT(STATE)

FROM CUSTOMER_VFROM CUSTOMER_V

GROUP BY STATEGROUP BY STATE

HAVINGHAVING COUNT(STATE) > 1; COUNT(STATE) > 1;

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

Page 35: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3535Chapter 7 © 2005 by Prentice Hall© 2005 by Prentice Hall

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

Page 36: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3636Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 37: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3737Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 38: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3838Chapter 7 © 2005 by Prentice Hall© 2005 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

Page 39: © 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.

3939Chapter 7 © 2005 by Prentice Hall© 2005 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