Concepts of Database Management Seventh Edition

70
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL

description

Concepts of Database Management Seventh Edition. Chapter 3 The Relational Model 2: SQL. Objectives. Introduce Structured Query Language (SQL) Use simple and compound conditions in SQL Use computed fields in SQL Use built-in SQL functions Use subqueries in SQL. Objectives (continued). - PowerPoint PPT Presentation

Transcript of Concepts of Database Management Seventh Edition

Page 1: Concepts of Database Management Seventh Edition

Concepts of Database ManagementSeventh Edition

Chapter 3

The Relational Model 2: SQL

Page 2: Concepts of Database Management Seventh Edition

Objectives

• Introduce Structured Query Language (SQL)

• Use simple and compound conditions in SQL

• Use computed fields in SQL

• Use built-in SQL functions

• Use subqueries in SQL

2

Page 3: Concepts of Database Management Seventh Edition

Objectives (continued)

• Group records in SQL

• Join tables using SQL

• Perform union operations in SQL

• Use SQL to update database data

• Use an SQL query to create a table in a database

3

Page 4: Concepts of Database Management Seventh Edition

Introduction

• SQL (Structured Query Language)– Allows users to query a relational database– Must enter commands to obtain the desired results– Standard language for relational database

manipulation

4

Page 5: Concepts of Database Management Seventh Edition

Getting Started with SQL

• If you are completing the work in this chapter using Microsoft Office Access 2007, Microsoft Office Access 2010, or MySQL version 4.1 or higher, the following sections contain specific information about your DBMS

5

Page 6: Concepts of Database Management Seventh Edition

Getting Started with Microsoft Office Access 2007 and 2010

• If you are using the Access 2007 or 2010 version of the Premiere Products database provided with the Data Files for this text:– Tables in the database have already been created– You will not need to execute the CREATE TABLE

commands to create the tables or the INSERT commands to add records to the tables

6

Page 7: Concepts of Database Management Seventh Edition

Getting Started with Microsoft Office Access 2007 and 2010 (continued)

• To execute SQL commands shown in the figures in Access 2007 or Access 2010:– Open the Premiere Products database– Click the Create tab on the Ribbon– Click the Query Design button in the Other group– Click the Close button in the Show Table dialog box– Click the View button arrow in the Results group on

the Query Design Tools tab, then click SQL View– The Query1 tab displays the query in SQL view,

ready for you to type your SQL commands

7

Page 8: Concepts of Database Management Seventh Edition

Getting Started with MySQL

• MySQL-Premiere script provided with the Data Files for this text will:– Activate the database– Create the tables– Insert the records

• To run a script in MySQL:– Type the SOURCE command followed by the name

of the file– Press the Enter key

8

Page 9: Concepts of Database Management Seventh Edition

Getting Started with MySQL (continued)

• Before typing commands in MySQL, you must activate the database by typing the USE command followed by the name of the database

• The most recent command entered in MySQL is stored in a special area of memory called the statement history

9

Page 10: Concepts of Database Management Seventh Edition

Table Creation

• SQL CREATE TABLE command– Creates a table by describing its layout

• Typical restrictions placed on table and column names by DBMS– Names cannot exceed 18 characters– Names must start with a letter– Names can contain only letters, numbers, and

underscores (_)– Names cannot contain spaces

10

Page 11: Concepts of Database Management Seventh Edition

Table Creation (continued)

• INTEGER– Number without a decimal point

• SMALLINT– Uses less space than INTEGER

• DECIMAL(p,q)– P number of digits; q number of decimal places

• CHAR(n)– Character string n places long

• DATE– Dates in DD-MON-YYYY or MM/DD/YYYY form

11

Page 12: Concepts of Database Management Seventh Edition

Simple Retrieval

• SELECT-FROM-WHERE: SQL retrieval command – SELECT clause: lists fields to display– FROM clause: lists table or tables that contain data

to display in query results– WHERE clause (optional): lists any conditions to be

applied to the data to retrieve

• Simple condition: field name, a comparison operator, and either another field name or a value

12

Page 13: Concepts of Database Management Seventh Edition

Simple Retrieval (continued)

13

• Retrieving all fields and all records– Syntax: SELECT * FROM <table>– Example 1: SELECT * FROM Customer– Example 2: SELECT * FROM Rep

• Retrieving specific field(s)• Syntax: SELECT <field1>, <field2>,..<fieldn> FROM

<table>• Example 1: SELECT Customername, City, State FROM

Customer

• Example 2: SELECT Repnum, Lastname, Firstname, Commission, Rate FROM Rep

Page 14: Concepts of Database Management Seventh Edition

Non-Graded Exercise

14

1. Show all the fields and records from Rep table

2. Show all fields and records Item table

3. Show the Last name and First name of all Sales Rep from Rep table

4. Show the Item number, Description, On Hand Quantity and Price from Item table

Page 15: Concepts of Database Management Seventh Edition

Simple Retrieval – Filtering Records

15

• Filtering records to retrieve using WHERE clause– Syntax: SELECT * FROM <table>– Example 1: (Filtering records with a Text/String field)

SELECT * FROM Customer WHERE City=‘Grove’– Example 2: (Filtering records with a Numeric field)

SELECT * FROM Customer WHERE CreditLimit=7500– Example 3: (Filtering records using specific fields)

SELECT Customername, City WHERE City = ‘Grove’– Example 4: (Filtering records using not equal)

SELECT * FROM City WHERE City <> ‘Fullton’

– Note : If it is a string or a text the value should have a quote like in ‘Grove’ but if it is numeric do not put a quote.

Page 16: Concepts of Database Management Seventh Edition

Simple Retrieval (continued)

FIGURE 3-6: SQL query with WHERE condition

16

Page 17: Concepts of Database Management Seventh Edition

Simple Retrieval (continued)

FIGURE 3-7: Query results

17

Page 18: Concepts of Database Management Seventh Edition

Relational Operators

18

Operator Description Example

> Greater Than Age>20

< Less than Age<21

= Equal City=‘Grove’

>= Greater than or Equal CreditLimit >= 10000

<= Less than or Equal Balance<=5000

<> Not Equal City <> ‘Grove’

Database Example

MS Access OrderDate = #10/21/2013#

MySQL OrderDate = DATE(‘2013-10-21’)

Date Comparisons

Page 19: Concepts of Database Management Seventh Edition

Non-Graded Exercise

19

1. Show all Customers that comes from the City of Northfield from Customer table

2. Show all products from Item table whose Category is TOY

3. Show all Customers whose Balance is greater than 2,000 from Customer table

4. Show all Customers whose Credit Limit is above or equal to 7500 from Customer table

5. Show all Customers whose balance is less than 500 from Customer table

6. Show all orders from Orders table whose order is beyond 10/13/2015

Page 20: Concepts of Database Management Seventh Edition

Graded Exercise No. 1

20

Check-up Time

Page 21: Concepts of Database Management Seventh Edition

Compound Conditions

• Compound condition– Connecting two or more simple conditions using one

or both of the following operators: AND and OR– Preceding a single condition with the NOT operator

• Connecting simple conditions using AND operator– All of the simple conditions must be true for the

compound condition to be true

• Connecting simple conditions using OR operator– Any of the simple conditions must be true for the

compound condition to be true

21

Page 22: Concepts of Database Management Seventh Edition

AND – Truth Table

• In order for AND to be true all conditions/expressions should be true

22

Condition 1 Condition 2 Result

False False False

False True False

True False False

True True True

Page 23: Concepts of Database Management Seventh Edition

AND – Truth Table (Example)

• Example : Age>20 AND State=‘Pohnpei’

23

Age State Result/Answer

20 Chuuk False

21 Yap False

19 Pohnpei False

21 Pohnpei True

Page 24: Concepts of Database Management Seventh Edition

OR – Truth Table

• In order for OR to be True at least one conditions/expressions should be true

24

Condition 1 Condition 2 Result

False False False

False True True

True False True

True True True

Page 25: Concepts of Database Management Seventh Edition

OR – Truth Table (Example)

• Example : Age>20 OR State=‘Pohnpei’

25

Age State Result/Answer

20 Chuuk False

21 Yap True

19 Pohnpei True

21 Pohnpei True

Page 26: Concepts of Database Management Seventh Edition

Compound Conditions (continued)

FIGURE 3-15: Query results

FIGURE 3-14: Compound condition that uses the AND operator

26©2015 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

Page 27: Concepts of Database Management Seventh Edition

Compound Conditions (continued)

FIGURE 3-17: Query results

FIGURE 3-16: Compound condition that uses the OR operator

27©2015 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

Page 28: Concepts of Database Management Seventh Edition

Non-Graded Exercise

28

1. Show all products from Item table whose Category is GME and its price is above $20

2. Show all Customers that comes from either the City of Mesa or Grove from Customer table

3. Show all Customers whose Credit Limit is $7,500 but its Balance is above $1,000 from Customer table

4. Show all products from Item table whose Storehouse is from either 1 or 2

5. Show all products from Item table whose On hand quantity is above 20 and coming from Storehouse no. 3

Page 29: Concepts of Database Management Seventh Edition

Compound Conditions (continued)

• Preceding a condition by NOT operator– Reverses the truth or falsity of the original condition

• BETWEEN operator– Value must be between the listed numbers

29

Page 30: Concepts of Database Management Seventh Edition

Compound Conditions (continued)

30

• Using NOT operator– Example 1: SELECT * FROM Customer WHERE

NOT City=‘Grove’– Example 2: SELECT * FROM Customer WHERE

NOT CreditLimit=10000

• Using BETWEEN operator– Example 1: SELECT * FROM Customer WHERE

Balance BETWEEN 2000 AND 5000– Example 2: SELECT * FROM Orders WHERE

Orderdate BETWEEN #10/12/2015# AND #10/13/2015

Page 31: Concepts of Database Management Seventh Edition

Non-Graded Exercise

31

1. Show all products from Item whose Category is not from GME

2. Show all products from Item whose Storehouse is not from Storehouse number 3

3. Show all customers from Customer whose sales representative is not Repnum no. 45

4. Show all products from Item whose Price is from $20 to $100.

5. Show all products from Item whose On hand quantity is from 20 to 100

Page 32: Concepts of Database Management Seventh Edition

Computed Fields

• Computed field or calculated field– Field whose values you derive from existing fields– Can involve:

• Addition (+)

• Subtraction (-)

• Multiplication (*)

• Division (/)

32

Page 33: Concepts of Database Management Seventh Edition

Computed Fields (continued)

33

• Numeric Computed Fields– Example 1: Computing the Net by deducting Credit Limit from Balance

SELECT Customername, (Balance-CreditLimit) as Net FROM Customer

– Example 2: Computing the Running Total by Multiplying On hand quantity with Price

SELECT Partnum, Description, OnHand * Price as RunningTotal FROM Item

• Non-numeric Computed Field– Example 1: Concatenating or Joining Last name and First name of the Sales as

Full Name

SELECT Repnum, Lastname + “, “ + Firstname as Fullname FROM Rep

Page 34: Concepts of Database Management Seventh Edition

Computed Fields (continued)

FIGURE 3-26: Query results

FIGURE 3-25: SQL query with a computed field and condition

34

Page 35: Concepts of Database Management Seventh Edition

Non-Graded Exercise

35

1. Show customer name and a computed field name Net using the formula CreditLimit – Balance from Customer table.

2. Get the Running Total from each order by multiplying Number Ordered and Quoted Price of the Orderline table. Aside from the Running Total show also the Order Number.

3. Get the Running Total per product from Item table by multiplying Quantity on Hand by price. Show also the Description of the product.

4. Make a concatenated field for Street, City, State and Zip fields and named it Address, from Customer table. Show also the Customer name before the address.

Page 36: Concepts of Database Management Seventh Edition

Using Special Operators (LIKE and IN)

• Wildcards in Access SQL– Asterisk (*): collection of characters– Question mark (?): any individual character

• Wildcards in MySQL– Percent sign (%): any collection of characters– Underscore (_): any individual character

• To use a wildcard, include the LIKE operator in the WHERE clause

• IN operator provides a concise way of phrasing certain conditions

36

Page 37: Concepts of Database Management Seventh Edition

Using LIKE operator and wildcards

37

• Using asterisk for collection of characters pattern– Example 1: Displays customer whose name starts with letter B

SELECT * FROM Customer WHERE customername LIKE ‘B*’– Example 2: Displays customer whose name starts with the word Brook

SELECT * FROM Customer WHERE customername LIKE ‘Brook*’

• Using question mark for individual/single character– Example 1: Display orders whose partnum starts with letter K followed by any 3

characters.

SELECT * FROM Orderline WHERE Itemnum LIKE ‘K???’

Page 38: Concepts of Database Management Seventh Edition

Using the IN operator

38

– Example 1: Displays customer whose credit limit is either $5,000 or $10,000 or $15,000

SELECT * FROM Customer WHERE creditlimit IN(5000,10000,15000)

– Example 2: Displays customer who comes from the City of Grove, Crystal, Fillmore or Northfield

SELECT * FROM Customer WHERE city IN(‘Grove’,’Fullton’,’Northfield’)

Page 39: Concepts of Database Management Seventh Edition

Non-Graded Exercise

39

1. Show all products from Item table whose Description starts with letter ‘P’

2. Show all customers from Customer table whose Street starts with 3

3. Using IN show products whose Category is either TOY or PZL from Item table

4. Using IN show customers from Customer table whose Credit Limit is either 5000, 7500 or 15000.

Page 40: Concepts of Database Management Seventh Edition

Sorting

• Sort data using the ORDER BY clause

• Sort key: field on which to sort data

• When sorting data on two fields:– Major sort key (or primary sort key): more important

sort key– Minor sort key (or secondary sort key): less

important sort key

40

Page 41: Concepts of Database Management Seventh Edition

Using the ORDER BY statement

41

– Example 1: Displays customer sorted by customer name

SELECT * FROM Customer ORDER BY customername– Example 2: Displays sales rep sorted by Lastname then Firstname

SELECT * FROM Rep ORDER BY Lastname, Firstname– Example 3: Displays sales rep sorted by Lastname in descending order

SELECT * FROM Rep ORDER BY Lastname DESC– Example 4: Displays customer sorted by City whose Credit Limit is $10,000

SELECT * FROM Customer WHERE CreditLimit = 10000 ORDER BY city

Page 42: Concepts of Database Management Seventh Edition

Non-Graded Exercise

42

1. Show all products from Item table and sort it according to Description

2. Show all products from Item table and sort it according to Storehouse and then Description

3. Show all products ordered from Orderline table and sort it according to Number of product ordered and in Descending order

Page 43: Concepts of Database Management Seventh Edition

Graded Exercise No. 2

43

Check-up Time

Page 44: Concepts of Database Management Seventh Edition

Built-in Functions

• Built-in functions (aggregate functions) in SQL– COUNT: calculates number of entries– SUM or AVG: calculates sum or average of all

entries in a given column– MAX or MIN: calculates largest or smallest values

respectively

44

Page 45: Concepts of Database Management Seventh Edition

Using Aggregate Functions (COUNT, SUM, AVG, MAX, MIN)

45

– Example 1: Count all how many customers in Customer table

SELECT COUNT(*) as CustomerCount FROM Customer– Example 2: Count how many customers from the City of Grove

SELECT COUNT(*) as CountGrove FROM Customer WHERE city = ‘Grove’

– Example 3: Sum all Balance from all Customers

SELECT SUM(Balance) as TotalBalance FROM Customer– Example 4: Sum all Balance from all Customers for those who a CreditLimit of $5,000

SELECT SUM(Balance) as TotalBalance FROM Customer

WHERE CreditLimit=5000

Page 46: Concepts of Database Management Seventh Edition

Non-Graded Exercise

46

1. Count all the products from Item table

2. Count all the products from Item table whose Category is either ‘TOY’ or ‘GME’

3. Give the Total for the Quantity On Hand from Item table

4. Give the Sum or Total for the Quoted Price from Orderline table

5. Give the Sum or Total for the Quoted Price from Orderline table whose Quoted Price is above $400

Page 47: Concepts of Database Management Seventh Edition

Subqueries

• Subquery: inner query

• Subquery is evaluated first

• Outer query is evaluated after the subquery

47

Page 48: Concepts of Database Management Seventh Edition

Using Subquery

48

– Example 1: Select orders where whose parts/products are from Warehouse No. 3

SELECT Ordernum FROM Orderline WHERE Partnum IN (SELECT Partnum FROM Part WHERE Warehouse = ‘3’)

Page 49: Concepts of Database Management Seventh Edition

Graded Exercise No. 3

49

Check-up Time

Page 50: Concepts of Database Management Seventh Edition

Grouping

• Create groups of records that share a common characteristic

• GROUP BY clause indicates grouping in SQL

• HAVING clause is to groups what the WHERE clause is to rows

50

Page 51: Concepts of Database Management Seventh Edition

Using GROUP BY

51

– Example 1: Count how many customers per Sales Representative

SELECT Repnum, COUNT(*) as TotalCustomersPerRep FROM Customer GROUP BY Repnum

– Example 2: Get the Total of how much Quantity on Hand per Class of all the products

SELECT Category, SUM(OnHand) as TotalPerCategory

FROM Item GROUP BY Category

Page 52: Concepts of Database Management Seventh Edition

Using HAVING

52

– Example 2: Get the Total of how much Quantity on Hand per Class of all products that have Quantity on hand above 70

SELECT Category, SUM(OnHand) as TotalPerCategory

FROM Item GROUP BY Class HAVING SUM(OnHand) > 120

Page 53: Concepts of Database Management Seventh Edition

Non-Graded Exercise

53

1. Using subquery show orders from Orderline table that has a Category of ‘GME’ in Item table

2. Count all customers from Customer table per City.

3. Sum all Quantity on Hand from Item table per Storehouse.

4. Display the Sum of Quantity on Hand from Item table per Storehouse that has Total Quantity on hand above 200.

Page 54: Concepts of Database Management Seventh Edition

Joining Tables

• Queries can locate data from more than one table

• Enter appropriate conditions in the WHERE clause

• To join tables, construct the SQL command as:1. SELECT clause: list all fields you want to display

2. FROM clause: list all tables involved in the query

3. WHERE clause: give the condition that will restrict the data to be retrieved to only those rows from the two tables that match

4. Or you could use INNER JOIN in same manner as no. 3

54

Page 55: Concepts of Database Management Seventh Edition

Joining tables example

55

– Example 1: Joining tables using WHERE clause

SELECT CustomerNum, CustomerName, Rep.Repnum, Lastname, Firstname FROM Customer, Rep

WHERE Customer.Repnum = Rep.Repnum– Example 2: Joining tables using INNER JOIN

SELECT A.CustomerNum, A.CustomerName, B.Repnum, B.Lastname, B.Firstname FROM Customer A INNER JOIN Rep B ON A.Repnum = B.Repnum

Page 56: Concepts of Database Management Seventh Edition

Non-Graded Exercise

56

1. Using WHERE clause join Orderline and Item tables showing Ordernum from Orderline table then Itemnum and Description from Item table

2. Using INNER JOIN, join Orderline and Item tables showing Ordernum from Orderline table then Itemnum and Description from Item table

Page 57: Concepts of Database Management Seventh Edition

Graded Exercise No. 4

57

Check-up Time

Page 58: Concepts of Database Management Seventh Edition

Updating Tables

• UPDATE command makes changes to existing data

• INSERT command adds new data to a table

• DELETE command deletes data from the database

58

Page 59: Concepts of Database Management Seventh Edition

Updating Table using UPDATE command

59

– Example 1: Updating one field

UPDATE Customer SET City=‘Manila’ WHERE Customernum=‘386’

– Example 2: Updating more than one field

UPDATE Rep SET Lastname=‘Doe’, Firstname=‘John’ WHERE Repnum=‘30’

– Example 3: Updating involving computation

UPDATE Item SET OnHand=OnHand-1 WHERE Storehouse=‘2’

Page 60: Concepts of Database Management Seventh Edition

Non-Graded Exercise

60

1. Using update command from Customer table restore back the City of Customernum = ‘386’ from Manila to Northfield

2. Using update command from Rep table restore back the Firstname and Lastname of Sales Rep John Doe to Gradey Megan whose Repnum = ‘30’

3. Using update command restore back from Item table to OnHand quantity plus 1 this time whose Storehouse = ‘2’

Page 61: Concepts of Database Management Seventh Edition

Updating Table using INSERT command

61

– Example 1: Inserting a record involving all fields

INSERT INTO Item VALUES (‘TH01',‘Thomas and Friends Train',50,‘TOY',‘2',35.50)

– Example 2: Inserting a record involving specific fields

INSERT INTO Item (Itemnum, Description,Category,Price) VALUES (‘BL10',‘Bible Puzzle',‘PZL',25.00)

Page 62: Concepts of Database Management Seventh Edition

Non-Graded Exercise

62

1. Insert a record into Rep table but put your own data.

2. Insert a record into Rep table but using only Repnum, Lastname, Firstname, Commission and Rate fields.

Page 63: Concepts of Database Management Seventh Edition

Creating a Table from a Query

• INTO clause– Saves the results of a query as a table– Specified before FROM and WHERE clauses

• MySQL – Create the new table using a CREATE TABLE

command– Use an INSERT command to insert the appropriate

data into the new table

63

Page 64: Concepts of Database Management Seventh Edition

64

Creating a Table from a Query (continued)

FIGURE 3-60a: Query to create a new table (Access)

64

Page 65: Concepts of Database Management Seventh Edition

65

Creating a Table from a Query (continued)

FIGURE 3-60b: Query to create a new table (for Oracle and MySQL)

65

Page 66: Concepts of Database Management Seventh Edition

Summary of SQL Commands

• Generic versions of SQL commands for every example presented in this chapter

• In most cases, commands in Access are identical to the generic versions

• For those commands that differ, both the generic version and the Access version are included

66

Page 67: Concepts of Database Management Seventh Edition

Summary

• Structured Query Language (SQL) is a language that is used to manipulate relational databases

• Basic form of an SQL query: SELECT-FROM-WHERE

• Use CREATE TABLE command to describe table layout to the DBMS, which creates the table

• In SQL retrieval commands, fields are listed after SELECT, tables are listed after FROM, and conditions are listed after WHERE

• In conditions, character values must be enclosed in single quotation marks

67

Page 68: Concepts of Database Management Seventh Edition

Summary (continued)

• Compound conditions are formed by combining simple conditions using either or both of the following operators: AND and OR

• Sorting is accomplished using ORDER BY clause

• When the data is sorted in more than one field, can have a major and minor sort key

• Grouping: use the GROUP BY clause

• HAVING clause: restricts the rows to be displayed

68

Page 69: Concepts of Database Management Seventh Edition

Summary (continued)

• Joining tables: use a condition that relates matching rows in the tables to be joined

• Built-in (aggregate) functions: COUNT, SUM, AVG, MAX, and MIN

• One SQL query can be placed inside another; the subquery is evaluated first

• UNION operator: unifies the results of two queries

69

Page 70: Concepts of Database Management Seventh Edition

Summary (continued)

• Calculated fields: include the calculation, the word AS, the name of the calculated field

• INSERT command adds a new row to a table

• UPDATE command changes existing data

• DELETE command deletes records

• INTO clause is used in a SELECT command to create a table containing the results of the query

70