chapter 7: introduction to sql - information systemsis.cba.edu.kw/433/handouts/ch07.pdf ·...

43
Chapter Chapter 7: Chapter Chapter 7: Introduction to SQL Introduction to SQL Modern Database Management Modern Database Management 9 th th Edition Edition 9 Edition Edition Jeffrey A. Jeffrey A. Hoffer Hoffer, Mary B. Prescott, , Mary B. Prescott, Heikki Heikki Topi Topi © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice Hall Publishing as Prentice Hall 1

Upload: others

Post on 12-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

ChapterChapter 77::Chapter Chapter 77::Introduction to SQLIntroduction to SQLQQ

Modern Database ManagementModern Database Management99thth EditionEdition99 EditionEdition

Jeffrey A. Jeffrey A. HofferHoffer, Mary B. Prescott, , Mary B. Prescott, HeikkiHeikki TopiTopi

© © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 11

Page 2: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

ObjectivesObjectivesObjectivesObjectives

Definition of termsDefinition of termsInterpret history and role of SQLInterpret history and role of SQLInterpret history and role of SQL Interpret history and role of SQL Define a database using SQL data Define a database using SQL data d fi iti ld fi iti ldefinition languagedefinition languageWrite single table queries using SQLWrite single table queries using SQLWrite single table queries using SQLWrite single table queries using SQLEstablish referential integrity using SQLEstablish referential integrity using SQLDiscuss SQL:Discuss SQL:1999 1999 and SQL:and SQL:200200n n standardsstandards

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 22

Page 3: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SQL OverviewSQL OverviewSQL OverviewSQL OverviewStructured Query LanguageStructured Query LanguageStructured Query LanguageStructured Query Language

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

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 33

Page 4: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

History of SQLHistory of SQLy Qy Q19701970––E. Codd develops relational database E. Codd develops relational database

ttconceptconcept19741974--19791979––System R with Sequel (later SQL) System R with Sequel (later SQL)

t d t IBM R h L bt d t IBM R h L bcreated at IBM Research Labcreated at IBM Research Lab19791979––Oracle markets first relational DB with Oracle markets first relational DB with SQLSQLSQLSQL19861986––ANSI SQL standard releasedANSI SQL standard released19891989, , 19921992, , 19991999, , 20032003––Major ANSI standard Major ANSI standard updatesupdatesCurrentCurrent––SQL is supported by most major SQL is supported by most major database vendorsdatabase vendors

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 44

Page 5: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Purpose of SQL StandardPurpose of SQL StandardPurpose of SQL StandardPurpose of SQL StandardSpecify syntax/semantics for data definitionSpecify syntax/semantics for data definitionSpecify syntax/semantics for data definition Specify syntax/semantics for data definition and manipulationand manipulationDefine data structuresDefine data structuresDefine data structuresDefine data structuresEnable portabilityEnable portabilitySpecify minimal (levelSpecify minimal (level 11) and complete (level) and complete (levelSpecify minimal (level Specify minimal (level 11) and complete (level ) and complete (level 22) standards) standardsAllow for later growth/enhancement toAllow for later growth/enhancement toAllow for later growth/enhancement to Allow for later growth/enhancement to standardstandard

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 55

Page 6: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Benefits of a StandardizedBenefits of a StandardizedBenefits of a Standardized Benefits of a Standardized Relational LanguageRelational Languageg gg g

Reduced training costsReduced training costsProductivityProductivityApplication portabilityApplication portabilityApplication portabilityApplication portabilityApplication longevityApplication longevityReduced dependence on a single vendorReduced dependence on a single vendorCrossCross system communicationsystem communicationCrossCross--system communicationsystem communication

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 66

Page 7: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SQL EnvironmentSQL EnvironmentCatalogCatalogCatalogCatalog

A set of schemas that constitute the description of a A set of schemas that constitute the description of a databasedatabasedatabasedatabase

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

Data Definition Language (DDL)Data Definition Language (DDL)g g ( )g g ( )Commands that define a database, including creating, Commands that define a database, including creating, altering, and dropping tables and establishing constraintsaltering, and dropping tables and establishing constraints

l ( )l ( )Data Manipulation Language (DML)Data Manipulation Language (DML)Commands that maintain and query a databaseCommands that maintain and query a database

l ( )l ( )Data Control Language (DCL)Data Control Language (DCL)Commands that control a database, including Commands that control a database, including administering privileges and committing dataadministering privileges and committing data

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 77

administering privileges and committing dataadministering privileges and committing data

Page 8: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 88

Page 9: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Some SQL Data typesSome SQL Data types(Table(Table 77 22))(Table (Table 77--22) )

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 99

Page 10: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1010

Page 11: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

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

CREATE SCHEMACREATE SCHEMA––defines a portion of thedefines a portion of theCREATE SCHEMACREATE SCHEMA defines a portion of the defines a portion of the database owned by a particular userdatabase owned by a particular userCREATE TABLECREATE TABLE––defines a table and its columnsdefines a table and its columnsCREATE TABLECREATE TABLE defines a table and its columnsdefines a table and its columnsCREATE VIEWCREATE VIEW––defines a logical table from one or defines a logical table from one or more viewsmore views

Other CREATE statements: CHARACTER SET, Other CREATE statements: CHARACTER SET, COLLATION TRANSLATION ASSERTIONCOLLATION TRANSLATION ASSERTIONCOLLATION, TRANSLATION, ASSERTION, COLLATION, TRANSLATION, ASSERTION, DOMAINDOMAIN

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1111

Page 12: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Table CreationTable Creation Steps in table creation:

Figure 7-5 General syntax for CREATE TABLE1. Identify data types for

attributes

2. Identify columns that can and cannot be null

3 Id tif l th t3. Identify columns that must be unique (candidate keys)

4. Identify primary key–foreign key mates

5. Determine default values

6. Identify constraints on l (d icolumns (domain

specifications)

7 Create the table and

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1212

7. Create the table and associated indexes

Page 13: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1313

Page 14: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

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

Overall table definitions

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1414

Page 15: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Defining attributes and their data types

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1515

Page 16: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

N ll bl ifi tiNon-nullable specification

Primary keys can never have

Identifying primary keyNULL values

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1616

Identifying primary key

Page 17: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Non-nullable specifications

Primary key

Some primary keys are composite–d f l i l ibcomposed of multiple attributes

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1717

Page 18: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Controlling the values in attributes

Default value

g

e u v ue

Domain constraint

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1818

Page 19: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Identifying foreign keys and establishing relationships

Primary key of parent tablep

Foreign key of dependent tabledepe de ab e

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1919

Page 20: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

D t I t it C t lD t I t it C t lData Integrity ControlsData Integrity ControlsReferential integrityReferential integrity constraint thatconstraint thatReferential integrityReferential integrity––constraint that constraint that ensures that foreign key values of a ensures that foreign key values of a t bl t t h i k l ft bl t t h i k l ftable must match primary key values of table must match primary key values of a related table in a related table in 11:M relationships:M relationshipsRestricting:Restricting:

Deletes of primary recordsDeletes of primary recordsp yp yUpdates of primary recordsUpdates of primary recordsInserts of dependent recordsInserts of dependent recordsInserts of dependent recordsInserts of dependent records

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2020

Page 21: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Figure 7-7 Ensuring data integrity through updates

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2121

Page 22: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Changing and Removing TablesChanging and Removing Tables

ALTER TABLE statement allows you to ALTER TABLE statement allows you to change column specifications:change column specifications:

ALTER TABLE CUSTOMER T ADD (TYPEALTER TABLE CUSTOMER T ADD (TYPEALTER TABLE CUSTOMER_T ADD (TYPE ALTER TABLE CUSTOMER_T ADD (TYPE VARCHAR(VARCHAR(22))))

DROP TABLE statement allows you toDROP TABLE statement allows you toDROP 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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2222

Page 23: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

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

Choice of indexesChoice of indexesChoice of indexesChoice of indexesFile organizations for base tablesFile organizations for base tablesFile organizations for indexesFile organizations for indexesggData clusteringData clusteringStatistics maintenanceStatistics maintenance

Creating indexesCreating indexesSpeed up random/sequential access to base table Speed up random/sequential access to base table p p / qp p / qdatadataExampleExample

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2323

the CUSTOMER_T tablethe CUSTOMER_T table

Page 24: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Insert StatementInsert StatementAdds data to a tableAdds data to a tableInserting into a tableInserting into a table

INSERT INTO CUSTOMER_T VALUES (INSERT INTO CUSTOMER_T VALUES (001001, ‘Contemporary , ‘Contemporary C l ’ ‘C l ’ ‘13551355 S Hi Bl d ’ ‘G i ill ’ ‘FL’S Hi Bl d ’ ‘G i ill ’ ‘FL’ 3260132601))Casuals’, ‘Casuals’, ‘1355 1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 3260132601););

Inserting a record that has some null attributes Inserting a record that has some null attributes i id tif i th fi ld th t t ll t d ti id tif i th fi ld th t t ll t d trequires identifying the fields that actually get datarequires identifying the fields that actually get data

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 (PRODUCT_ON_HAND) VALUES (11, ‘End Table’, ‘Cherry’, , ‘End Table’, ‘Cherry’, 175175, , 88););

Inserting from another tableInserting from another tableINSERT INTO CA_CUSTOMER_T SELECT * FROM CUSTOMER_T WHERE INSERT INTO CA_CUSTOMER_T SELECT * FROM CUSTOMER_T WHERE STATE = ‘CA’;STATE = ‘CA’;

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2424

Page 25: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Creating Tables with Identity ColumnsCreating Tables with Identity ColumnsNew with SQL:2003

Inserting into a table does not require explicit customer ID entry or Inserting into a table does not require explicit customer ID entry or field li tfield li tfield listfield list

INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary Casuals’, INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary Casuals’, ‘‘13551355 S Himes Blvd ’ ‘Gainesville’ ‘FL’S Himes Blvd ’ ‘Gainesville’ ‘FL’ 3260132601););

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2525

1355 1355 S. Himes Blvd., Gainesville , FL, S. Himes Blvd., Gainesville , FL, 3260132601););

Page 26: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Delete StatementDelete Statement

Removes rows from a tableRemoves rows from a tableDelete certain rowsDelete certain rows

DELETE FROM CUSTOMER T WHERE STATEDELETE FROM CUSTOMER T WHERE STATEDELETE FROM CUSTOMER_T WHERE STATE DELETE FROM CUSTOMER_T WHERE STATE = ‘HI’;= ‘HI’;

D l t llD l t llDelete all rowsDelete all rowsDELETE FROM CUSTOMER_T;DELETE FROM CUSTOMER_T;

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2626

Page 27: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

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 775 WHERE PRODUCT_ID = WHERE PRODUCT_ID = 77;;

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2727

Page 28: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Merge StatementMerge StatementMerge StatementMerge Statement

M k it i t d t t bl ll bi ti f I t dMakes it easier to update a table…allows combination of Insert and Update in one statement

Useful for updating master tables with new data

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2828

Useful for updating master tables with new data

Page 29: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SELECT StatementSELECT StatementUsed for queries on single or multiple tablesUsed for queries on single or multiple tablesClauses of the SELECT statement:Clauses of the SELECT statement:Clauses of the SELECT statement:Clauses of the SELECT statement:

SELECTSELECTList the columns (and expressions) that should be returned from the List the columns (and expressions) that should be returned from the ( p )( p )queryquery

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

WHEREWHEREIndicate 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 BYGROUP BYGROUP BYIndicate categorization of results Indicate categorization of results

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

ORDER BYORDER BYSorts the result according to specified criteriaSorts the result according to specified criteria

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2929

g pg p

Page 30: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3030

Page 31: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SELECT ExampleSELECT Examplepp

Find products with standard price less thanFind products with standard price less thanFind products with standard price less than Find products with standard price less than $$275275

SELECTSELECT PRODUCT_NAME, STANDARD_PRICE PRODUCT_NAME, STANDARD_PRICE FROMFROM PRODUCT_V PRODUCT_V WHEREWHERE STANDARD_PRICE < STANDARD_PRICE < 275275;;

Table 7-3: Comparison Operators in SQL

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3131

Page 32: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SELECT Example Using AliasSELECT Example Using Alias

Alias is an alternative column or table nameAlias is an alternative column or table name

SELECTSELECT CUSTCUST CUSTOMER ASCUSTOMER AS NAMENAMESELECT SELECT CUSTCUST.CUSTOMER AS .CUSTOMER AS NAMENAME, , CUST.CUSTOMER_ADDRESS CUST.CUSTOMER_ADDRESS

FROM CUSTOMER_V FROM CUSTOMER_V CUSTCUSTWHEREWHERE NAMENAME = ‘Home Furnishings’;= ‘Home Furnishings’;WHERE WHERE NAMENAME Home Furnishings ; Home Furnishings ;

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3232

Page 33: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SELECT ExampleSELECT ExampleSELECT Example SELECT Example Using a FunctionUsing a Functiongg

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

SELECT SELECT COUNT(*)COUNT(*) FROM ORDER_LINE_VFROM ORDER_LINE_VWHERE ORDER_ID = WHERE ORDER_ID = 10041004;;;;

Note: with aggregate functions you can’t haveNote: with aggregate functions you can’t haveNote: with aggregate functions you can t have Note: with aggregate functions you can t have singlesingle--valued columns included in the SELECT valued columns included in the SELECT clauseclause

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3333

Page 34: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SELECT ExampleSELECT Example––Boolean OperatorsBoolean Operatorspp ppANDAND, , OROR, and , and NOTNOT Operators for customizing Operators for customizing conditions in WHERE clauseconditions in WHERE clauseconditions in WHERE clauseconditions in WHERE clause

SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICESTANDARD_PRICE

FROM PRODUCT_VFROM PRODUCT_VWHERE (PRODUCT_DESCRIPTION WHERE (PRODUCT_DESCRIPTION LIKELIKE ‘‘%%Desk’Desk’OROR PRODUCT_DESCRIPTION PRODUCT_DESCRIPTION LIKELIKE ‘‘%%Table’) Table’) ANDAND STANDARD_PRICE > STANDARD_PRICE > 300300;;

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3434

have any number of characters preceding the word Desk will be allowed

Page 35: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Venn Diagram from Previous QueryVenn Diagram from Previous Query

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3535

Page 36: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SELECT Example SELECT Example ––S ti R lt ith th ORDER BY ClS ti R lt ith th ORDER BY ClSorting Results with the ORDER BY ClauseSorting Results with the ORDER BY Clause

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

SELECT CUSTOMER_NAME, CITY, STATESELECT CUSTOMER_NAME, CITY, STATEFROM CUSTOMER_VFROM CUSTOMER_VWHERE STATEWHERE STATE ININ (‘FL’, ‘TX’, ‘CA’, ‘HI’)(‘FL’, ‘TX’, ‘CA’, ‘HI’)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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3636

OR conditions

Page 37: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SELECT ExampleSELECT Example––Categorizing Results Using the GROUP BY ClauseCategorizing Results Using the GROUP BY ClauseCategorizing Results Using the GROUP BY ClauseCategorizing Results Using the GROUP BY Clause

For use with aggregate functionsFor use with aggregate functionsgg ggg gScalar aggregateScalar aggregate: single value returned from SQL query with : single value returned from SQL query with aggregate functionaggregate functionVV l i l l d f SQLl i l l d f SQLVector 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 VFROM CUSTOMER_VFROM CUSTOMER_VGROUP BYGROUP BY CUSTOMER_STATE;CUSTOMER_STATE;

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3737

yy

Page 38: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

SELECT ExampleSELECT Example––Q lif i R l b C iQ lif i R l b C iQualifying 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, COUNT(CUSTOMER_STATE) SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE) FROM CUSTOMER VFROM CUSTOMER VFROM CUSTOMER_VFROM CUSTOMER_VGROUP BY CUSTOMER_STATEGROUP BY CUSTOMER_STATEHAVINGHAVING COUNT(CUSTOMER STATE) >COUNT(CUSTOMER STATE) > 11HAVINGHAVING COUNT(CUSTOMER_STATE) > COUNT(CUSTOMER_STATE) > 11;;

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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3838

Page 39: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Using and Defining ViewsUsing and Defining Viewsg gg gViews provide users controlled access to tablesViews provide users controlled access to tablesBase TableBase Table––table containing the raw datatable containing the raw dataBase TableBase Table––table containing the raw datatable containing the raw dataDynamic ViewDynamic View

A “virtual table” created dynamically upon request by a userA “virtual table” created dynamically upon request by a userA 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 useravailable to useravailable to userBased on SQL SELECT statement on base tables or other Based on SQL SELECT statement on base tables or other viewsviews

Materialized ViewMaterialized ViewCopy or replication of dataCopy or replication of dataData actually storedData actually storedMust be refreshed periodically to match the corresponding Must be refreshed periodically to match the corresponding base tablesbase tables

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3939

base tablesbase tables

Page 40: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Sample CREATE VIEWSample CREATE VIEWppCREATE VIEW EXPENSIVE_STUFF_V ASCREATE VIEW EXPENSIVE_STUFF_V ASSELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICESELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICEFROM PRODUCT_TFROM PRODUCT_TWHERE UNIT_PRICE >WHERE UNIT_PRICE >300300WITH 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

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 4040

the view

Page 41: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Advantages of ViewsAdvantages of ViewsAdvantages of ViewsAdvantages of ViewsSimplify query commandsSimplify query commandsSimplify query commandsSimplify query commandsAssist with data security (but don't rely on views Assist with data security (but don't rely on views for security there are more important securityfor security there are more important securityfor security, there are more important security for security, there are more important security measures)measures)Enhance programming productivityEnhance programming productivityEnhance programming productivityEnhance programming productivityContain most current base table dataContain most current base table dataU littl tU littl tUse little storage spaceUse little storage spaceProvide customized view for userProvide customized view for userEstablish physical data independenceEstablish physical data independence

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 4141

Page 42: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

Disadvantages of ViewsDisadvantages of ViewsDisadvantages of ViewsDisadvantages of ViewsU i ti h ti i iU i ti h ti i iUse processing time each time view is Use processing time each time view is referencedreferencedMay or may not be directly updateableMay or may not be directly updateable

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 4242

Page 43: Chapter 7: Introduction to SQL - Information Systemsis.cba.edu.kw/433/Handouts/ch07.pdf · 2011-03-01 · HistoryyQ of SQL 19701970––E. Codd develops relational database E. Codd

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronicretrieval system, or transmitted, in any form or by any means, electronic,

mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America.

Copyright © Copyright © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall

Chapter 7 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 4343