© 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 6: Introduction to SQL Modern...

46
© 2011 Pearson Education, Inc. Publishing as © 2011 Pearson Education, Inc. Publishing as Prentice Hall Prentice Hall 1 Chapter 6: Chapter 6: Introduction to SQL Introduction to SQL Modern Database Management Modern Database Management 10 10 th th Edition Edition Jeffrey A. Hoffer, V. Ramesh, Jeffrey A. Hoffer, V. Ramesh, Heikki Topi Heikki Topi

Transcript of © 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 6: Introduction to SQL Modern...

© 2011 Pearson Education, Inc.  Publishing as © 2011 Pearson Education, Inc.  Publishing as Prentice HallPrentice Hall 11

Chapter 6:Chapter 6:Introduction to SQLIntroduction to SQL

Modern Database Modern Database ManagementManagement

1010thth Edition EditionJeffrey A. Hoffer, V. Ramesh, Jeffrey A. Hoffer, V. Ramesh,

Heikki Topi Heikki Topi

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 22

ObjectivesObjectives Define termsDefine 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:200n Discuss SQL:1999 and SQL:200n

standardsstandards

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 33

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 44

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 55

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

definition and manipulationdefinition and manipulation Define data structures and basic Define data structures and basic

operationsoperations Enable portability of database definition Enable portability of database definition

and application modulesand application modules 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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 66

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 77

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 88

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 99

SQL Data TypesSQL Data Types

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1010

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1111

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 new table and its CREATE TABLE–defines a new table and its columnscolumns

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

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1212

Table CreationTable CreationFigure 6-5 General syntax for CREATE TABLE statement used in data definition language

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1313

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

(from Chapter 1, Figure 1-3)

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1414

Figure 6-6 SQL database definition commands for Pine Valley Furniture Company (Oracle 11g)

Overall table definitions

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1515

Defining attributes and their data types

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1616

Non-nullable specification

Identifying primary key

Primary keys can never have NULL values

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1717

Non-nullable specifications

Primary key

Some primary keys are composite– composed of multiple attributes

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1818

Default value

Domain constraint

Controlling the values in attributes

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 1919

Primary key of parent table

Identifying foreign keys and establishing relationships

Foreign key of dependent table

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2020

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2121

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

Figure 6-7 Ensuring data integrity through updates

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2222

Changing TablesChanging Tables ALTER TABLE statement allows you to change column specifications:ALTER TABLE statement allows you to change column specifications:

Table Actions:Table Actions:

Example Example (adding a new column with a default value)(adding a new column with a default value)::

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2323

Removing TablesRemoving Tables

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2424

Insert StatementInsert Statement Adds one or more rows to a tableAdds one or more rows to a table Inserting into a tableInserting into a table

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

Inserting from another tableInserting from another table

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2525

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

Introduced with SQL:200n

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2626

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 CUSTOMERSTATE = ‘HI’;CUSTOMERSTATE = ‘HI’;

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2727

Update StatementUpdate Statement

Modifies data in existing rowsModifies data in existing rows

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2828

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 2929

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 Speed up random/sequential access to base table

datadata ExampleExample

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

CUSTOMER_T tableCUSTOMER_T table

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3030

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3131

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3232

SELECT ExampleSELECT Example

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

Table 6-3: Comparison Operators in SQL

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3333

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.CUSTOMERNAME AS .CUSTOMERNAME AS NAMENAME, , CUST.CUSTOMERADDRESS CUST.CUSTOMERADDRESS

FROM CUSTOMER_V FROM CUSTOMER_V CUSTCUST

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3434

SELECT Example SELECT Example Using a FunctionUsing a Function

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

SELECT SELECT COUNT(*)COUNT(*) FROM ORDERLINE_T FROM ORDERLINE_TWHERE ORDERID = 1004;WHERE ORDERID = 1004;

Note: with aggregate functions you can’t have Note: with aggregate functions you can’t have single-valued columns included in the SELECT single-valued columns included in the SELECT clause, unless they are included in the GROUP clause, unless they are included in the GROUP BY clauseBY clause

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3535

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

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 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3636

Figure 6-9 Boolean query without use of parentheses

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3737

SELECT Example–Boolean SELECT Example–Boolean OperatorsOperators

With parentheses…these override the normal With parentheses…these override the normal precedence of Boolean operatorsprecedence of Boolean operators

Note: by default, the AND operator takes precedence over the OR operator. With parentheses, you can make the OR take place before the AND.

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3838

Figure 6-9 Boolean query with use of parentheses

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 3939

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 the CUSTOMER NAMEwithin a state by the CUSTOMER NAME

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 4040

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)

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 4141

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

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 included groups with total numbers greater than 1 will be included in final result.in final result.

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 4242

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 “virtual table” created dynamically upon request by a user a user

No data actually stored; instead data from base table No data actually stored; instead data from base table made available to usermade available to user

Based on SQL SELECT statement on base tables or Based on SQL SELECT statement on base tables or other viewsother 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 Must be refreshed periodically to match the

corresponding base tablescorresponding base tables

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 4343

Sample CREATE VIEWSample CREATE VIEW

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 4444

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 4545

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

Chapter 6 © 2011 Pearson Education, Inc.  Publishing as Prentice Hall© 2011 Pearson Education, Inc.  Publishing as Prentice Hall 4646

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, electronic,

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

Copyright © 2011 Pearson Education, Inc.  Publishing as Prentice Copyright © 2011 Pearson Education, Inc.  Publishing as Prentice HallHall