chapter 6: introduction to sql © 2013 pearson education 1 modern database management 11 th edition,...

55
CHAPTER 6: CHAPTER 6: INTRODUCTION TO SQL INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi

Upload: loreen-hensley

Post on 13-Jan-2016

228 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

CHAPTER 6:CHAPTER 6:INTRODUCTION TO SQLINTRODUCTION TO SQL

© 2013 Pearson Education1

Modern Database Management11th Edition, International Edition

Jeffrey A. Hoffer, V. Ramesh, Heikki Topi

Page 2: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

OBJECTIVESOBJECTIVES

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

definition language Write single table queries using SQL Establish referential integrity using SQL Discuss SQL:1999 and SQL:2008

standards

2

Page 3: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SQL OVERVIEWSQL OVERVIEW

SQL : Structured Query LanguageThe standard language for relational database management systems (RDBMS)

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

3

Relational DB

Page 4: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

Figure 6.3 Sample Data of a Relational Figure 6.3 Sample Data of a Relational DatabaseDatabase

4

Page 5: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

HISTORY OF SQLHISTORY OF SQL 1970 – E. F. Codd develops relational database concept 1974 - 1979–System R with Sequel (later SQL) created

at IBM Research Lab 1979 – Oracle markets first relational DB with SQL 1981 – SQL/DS (Structured Query Language/Data

System)first available RDBMS system on DOS/VSE

Others followed: INGRES (1981), IDM (1982), DG/SGL (1984), Sybase (1986)

1986 – ANSI SQL standard released 1989, 1992, 1999, 2003, 2006, 2008–Major ANSI SQL

standard updates Current – SQL is supported by most major database

vendors

5

Page 6: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

PURPOSE OF SQL STANDARDPURPOSE OF SQL STANDARD Specify syntax/semantics for data definition

and manipulation Define data structures and basic operations Enable portability (可攜性 ) of database

definition and application modules Specify minimal (level 1) and complete

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

standard (referential integrity, transaction management, user-defined functions, extended join operations, national character sets)

6

Page 7: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

BENEFITS OF A STANDARDIZED BENEFITS OF A STANDARDIZED RELATIONAL LANGUAGERELATIONAL LANGUAGE Reduced training costs Productivity Application portability Application longevity (長壽 ) Reduced dependence on a single

vendor Cross-system communication

7

Page 8: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

Terms in SQL ENVIRONMENTTerms in SQL ENVIRONMENT Catalog

A set of schemas that constitute the description of a database

Schema (架構概要 ) A structure that contains descriptions of objects (base

tables, views, constraints) created by a user Data Definition Language (DDL)

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

Data Manipulation Language (DML) Commands used to maintain and query a database

Data Control Language (DCL) Commands used to control a database, including those

for administering privileges and committing (saving) data (making tentative changes permanent)

8

Page 9: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

9

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

9Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

Database 1

Database 2

Page 10: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SQL DATA TYPESSQL DATA TYPES

10

Page 11: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

11

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

11Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

相反

Logical Design

used byprogrammer

used byDBA

Page 12: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SQL DATABASE DEFINITIONSQL DATABASE DEFINITION By Data Definition Language (DDL) Major CREATE statements:

CREATE SCHEMA – used to define the portion of the database owned by a particular user

Schema objects include base tables, views, constraints, …

Privilege of creating DBs may be reserved for the DBA CREATE TABLE – used to define a new table and its

columns CREATE VIEW – used to define a logical (virtual) table

from one or more tables or views Advanced CREATE statements: CHARACTER SET,

TRANSLATION, DOMAIN, COLLATE, ASSERTION(Not covered in this textbook)

12

重點

Page 13: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

STEPS IN TABLE STEPS IN TABLE CREATIONCREATION

13

1. Identify data type for each attribute

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 14: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education14

Figure 6-5 General syntax for CREATE TABLE statement used in data definition language

較不常用

較不常用

較不常用

Notation{ } : one or more[ ] : optional( ) : reserved symbol

statement example

Page 15: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education15

Example of column definitions and table constraint

columndefinitio

ns

tableconstrai

nt

Page 16: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

16

More on Defining attributes and their data types(Example of Column Definitions)

16Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

columndefinitio

ns

columndefinitio

ns

Page 17: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

17

Non-nullable specification(Example of Column Constraint Clause)

Identifying primary key

Primary keys can never have NULL values

17Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

column constraint

clause

tableconstrai

nt

Page 18: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

18

Non-nullable Specifications

The primary key is composite. It is composed of 2 attributes

18Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

2 column constraint

clauses

3 tableconstrai

ntsPrimary

key

Page 19: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

19

Controlling the Values in an Attribute

19Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

domain constrain

t

default value

Page 20: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

20

PK of parent table

Identifying foreign keys and establishing relationships

Foreign key of the dependent (child) table

20Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

Page 21: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

21

(From Figure 4-5 Relational Schema for Pine Valley Furniture)

21Chapter 4 © 2013 Pearson Education© 2013 Pearson Education

Referential integrity constraints are drawn via arrows from child table to parent table

CorrespondingSQL DDL

Data Examp

le

CUSTOMER > ORDER > ORDER LINE PRODUCT > ORDER LINE

Creation order of tables :

Page 22: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education22

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

Overall table definitions

Relational

SchemaData

Example

Page 23: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

CREATING DATA INTEGRITY CREATING DATA INTEGRITY CONTROLSCONTROLS

Referential integrityEstablishing referential integrity constraint between two tables (a child and a parent tables) with a 1:M relations.In an SQL statement, the constraint ensures that the foreign key values of a (child) table must

match primary key values of a related (parent), or Be NULL

The REFERENCES clause prevents making a non-matching change in FK value, but not PK value of parent table.Other situations of creating referential integrity control:

Delete primary records in the parent table Update primary records in the parent table

23

Clause

Parent

tables

Page 24: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

24

Relational integrity is enforced via PK-FK match

Figure 6-7 Example of ensuring data integrity in data updates

24Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

The other 3 options

is ensured

Parent table

Child table

Relational

Schema

1:M

Page 25: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

CHANGING TABLE DEFINITIONSCHANGING TABLE DEFINITIONS ALTER TABLE statement allows you to change column specifications:

alter_table_action:

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

25

Page 26: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

REMOVING TABLESREMOVING TABLES

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

Example : DROP TABLE CUSTOMER_T

26

Page 27: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

INSERT STATEMENTINSERT STATEMENT

Statement for adding one or more data rows to a table

Example of inserting into a table

Inserting a record that has some null attributes requires identifying the fields that actually get data

Inserting records from another table

27

table definition

Attribute productLineID is not specified.NULL is entered for attribute productLineID in this record.

table definition

Page 28: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

CREATING TABLES WITH IDENTITY (CREATING TABLES WITH IDENTITY ( 識別識別 ) ) COLUMNSCOLUMNS

((INTRODUCED IN SQL:2008INTRODUCED IN SQL:2008))

28

Remove the need to create a procedure to Remove the need to create a procedure to generate a sequence and then apply into it to generate a sequence and then apply into it to data insertion.data insertion.

Page 29: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

CREATING TABLES WITH IDENTITY CREATING TABLES WITH IDENTITY COLUMNSCOLUMNS

((INTRODUCED IN SQL:2008INTRODUCED IN SQL:2008))

29

Only one column can be an identity column in a table.

Insertion statement does not Insertion statement does not require value explicitly specified require value explicitly specified for customer ID. for customer ID. Example :Example :INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);32601);

Page 30: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

DELETE STATEMENTDELETE STATEMENT

Removes data rows from a table Example of deleting certain rows

DELETE DELETE

FROM Customer_T FROM Customer_T

WHERE CustomerState = ‘HI’;WHERE CustomerState = ‘HI’;

Example of Deleting all data rows :DELETE FROM Customer_T;DELETE FROM Customer_T;

30

Page 31: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

UPDATE STATEMENTUPDATE STATEMENT

Example of modifying data in existing rowsUPDATE Product_T UPDATE Product_T

SET ProductStandardPrice = 775 SET ProductStandardPrice = 775

WHERE ProductID = 7;WHERE ProductID = 7;

31

Data Exampl

e

Page 32: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

MERGE (MERGE ( 合併合併 ) STATEMENT) STATEMENT((INTRODUCED IN SQL:2008INTRODUCED IN SQL:2008))

32

Useful for updating a master table by using new data Allows combination of Insert and Update in one

statement Makes it easier to update a master table.

not matched, insert

matched, updateprice

updated attribute :ProductStandardprice

key for merge :ProductID

Product_T(PROD)

Purchase_T(PURCH)

master

table

newdata

mastertable

newdata

key

updated attribute

not matched, insert

Page 33: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

DEFINITION OF INTERNAL DEFINITION OF INTERNAL SCHEMASCHEMA

Control processing/storage efficiency: Choice of indexes File organizations for base tables File organizations for indexes Data clustering Statistics maintenance

Creating indexes Speed up random/sequential access to base table data Statement example : CREATE INDEX Name_IDX ON CUSTOMER_T(CustomerName)

This makes an index for the CustomerName field of the CUSTOMER_T table

33

CUSTOMER table

Page 34: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SELECT STATEMENTSELECT STATEMENT Used for queries on single or multiple tables Clauses of the SELECT statement:

SELECTSELECTList the columns (and expressions) to be returned from the query

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

WHEREWHEREIndicate the conditions under which a row will be included in the result

GROUP BYGROUP BYIndicate the attribute(s) used for the categorization of query results

HAVINGHAVINGIndicate the conditions under which a category (group) will be included in the query result

ORDER BYORDER BYSorts the query result according to the specified criteria

34

Page 35: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

35

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

35Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

Must have these 2 clauses in a SQL statement

Page 36: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SELECT EXAMPLESELECT EXAMPLE

Query : List product description and price for products with standard price less than $275.

36

Table 6-3: Comparison Operators in SQL

Product_T table

PRODUCTDESCRIPTIONPRODUCTSTANDARDPRIC

E

End Table 175

Computer Desk 250

Coffee Table 200

Result :

Page 37: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SELECT EXAMPLE USING ALIASSELECT EXAMPLE USING ALIAS

Alias is an alternative column or table name

(Often, it is a shorter name)

SELECT CUSTCUST.CustomerName AS NameName,

CUST.CustomerAddress

FROM CUSTOMER_T CUSTCUST

WHERE NameName = ‘Home Furnishings’;

37

alias

alias

NAMECUSTOMERADDRESS

Home Furnishings

1900 Allard Ave.

Result :

需一致

需一致

Page 38: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SELECT EXAMPLE USING AN AGGREGATE SELECT EXAMPLE USING AN AGGREGATE FUNCTIONFUNCTION

Using the COUNT aggregate function to find totals.

Example :SELECT COUNT(*)COUNT(*) FROM ORDERLINE_TWHERE ORDERID = 1004;

Note: With aggregate functions you can’t have column name(s) included in the SELECT clause, unless

they are included in the GROUP BY clause.

38

COUNT(*)

2

Result :Data

Page 39: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

ERRORERROR EXAMPLE USING AN AGGREGATE EXAMPLE USING AN AGGREGATE FUNCTIONFUNCTION

Using the COUNT aggregate function to find totals.

Error example : SELECT ProductID, COUNT(*)COUNT(*) FROM ORDERLINE_T WHERE ORDERID = 1004;

Result (in Microsoft SQL): Column ‘OrderLine_Y.ProductID’ is invalid in the select list because it is not contained in an Aggregate function and there is no GROUP BY clause.

Correct example:SELECT ProductID, COUNT(*)COUNT(*) FROM ORDERLINE_TWHERE ORDERID = 1004;GROUP BY ProductID;

39

PRODUCTID COUNT(*)

6 2

8 2

Result :

error

match

ORDERLINE

Page 40: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SELECT EXAMPLE–BOOLEAN SELECT EXAMPLE–BOOLEAN OPERATORSOPERATORS ANDAND, OROR, and NOTNOT boolean operators for combining

multiple conditions in the WHERE clause

40

Note: LIKELIKE operator allows we to compare the partial part of a string using wildcards ( 萬用字元 ). For example, the % wildcard in ‘%Desk’ indicates that all strings that have any number of characters preceding the suffix (字尾 ) “Desk” will be allowed.

Page 41: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education41

Figure 6-8 : A Boolean query without use of parentheses

By default, processing order of Boolean operators is NOT, then AND, then OR

() ;Product_

T

ProductDescription

LIKE ‘%Table’

ProductDescription

LIKE ‘%Desk’

Page 42: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education42

Result of a Boolean query without use of parentheses

Product_T

PRODUCTDESCRIPTION

PRODUCTFINISH

PRODUCTSTANDARDPRICE

Computer Desk Natural Ash 375

Writer’s Desk Cherry 325

8-Drawer Desk White Ash 750

Dining Table Natural Ash 800

Computer Desk Walnut 250

Page 43: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SELECT EXAMPLE–BOOLEAN SELECT EXAMPLE–BOOLEAN OPERATORSOPERATORS ParenthesesParentheses override the normal precedence

of Boolean operators

43

In this case parentheses make the OR take place before the AND.

Page 44: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education44

Figure 6-9 : A Boolean query with use of parentheses

ProductDescription

LIKE ‘%Table’

ProductDescription

LIKE ‘%Desk’

Product_T

Page 45: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education45

Result of a Boolean query with use of parentheses

PRODUCTDESCRIPTION

PRODUCTFINISH

PRODUCTSTANDARDPRICE

Computer Desk Natural Ash 375

Writer’s Desk Cherry 325

8-Drawer Desk White Ash 750

Dining Table Natural Ash 800

Product_T

Page 46: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SORTING RESULTS WITH ORDER BY SORTING RESULTS WITH ORDER BY CLAUSECLAUSE

Query : List customer name, city, and state for all customers in the CUSTOMER table whose address is in Florida, Texas, California, or Hawaii. List the customers alphabetically by state, and alphabetically by name within each state.

46

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.

Data

Page 47: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SORTING RESULTS WITH ORDER BY SORTING RESULTS WITH ORDER BY CLAUSECLAUSE

47

Customer_T

Page 48: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

CATEGORIZING RESULTS CATEGORIZING RESULTS USING USING GROUP BY GROUP BY CLAUSECLAUSE

Combined with an aggregate function to provide a summary information for each data subgroup categorized by certain attribute(s). The attributes used in GROUP BY clause have to

appear in SELECT clause. The SELECT clause has to contains at least one

aggregate function. Example

48

match

an aggregate function

Page 49: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

CATEGORIZING RESULTS USING GROUP BY CATEGORIZING RESULTS USING GROUP BY CLAUSECLAUSE

49

Customer_T

Query : List the number of customers in each state.

Page 50: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

QUALIFYING (QUALIFYING ( 限定限定 ) RESULTS BY ) RESULTS BY CATEGORIES : USING CATEGORIES : USING HAVING CLAUSEHAVING CLAUSE Having clause is used with GROUP BY

Functioning like a WHERE clause, but it operates on groups (categories), not on individual rows.

Here, only those groups with total numbers greater than 1 will be included in final result.

50

Page 51: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

QUALIFYING (QUALIFYING ( 限定限定 ) RESULTS BY ) RESULTS BY CATEGORIES : USING CATEGORIES : USING HAVING CLAUSEHAVING CLAUSE

51

No Having

Page 52: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

USING AND DEFINING VIEWSUSING AND DEFINING VIEWS Views provide users controlled access to tables Base Table : A table containing the raw data Dynamic View

A “virtual table” created dynamically upon request by a user

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

Based on SQL SELECT statement on base tables or other views

Materialized View Copy or replication of data Data actually stored Must be refreshed periodically to match corresponding base

tables52

Page 53: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

SAMPLE CREATE VIEWSAMPLE CREATE VIEW

53

View has a name. CHECK OPTION

works only for updateable views prevents updates that would make data rows

not obey the rule of the view.

Page 54: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

Chapter 6 © 2013 Pearson Education© 2013 Pearson Education

PROS and CONS OF USING DYNAMIC PROS and CONS OF USING DYNAMIC VIEWSVIEWSPositive Aspects Simplify query commands Help provide data security and confidentiality Improve programmer productivity Contain most current base table data Use little storage space Provide customized view for user Establish physical data independence

Negative Aspects Use processing time re-creating the view each

time a view is referenced May or may not be directly updateable

54

Page 55: CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education 1 Modern Database Management 11 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh,

5555

Copyright © 2013 Pearson EducationCopyright © 2013 Pearson Education