62
SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL – Part II Yong Choi School of Business CSU, Bakersfield

  • View
    221

  • Download
    1

Embed Size (px)

Citation preview

Page 1: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL – Part II

Yong Choi

School of Business

CSU, Bakersfield

Page 2: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Aggregate Functions

• Example 18: Save as example 18– How many parts (count number of records) are

in item class HW? – Use of “count” command– Count all records: count(*)– Count all of HW Class– Review the Part table first

Page 3: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 18SQL Query to Count Records

Page 4: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 18

SELECT count(*)FROM PartWHERE Class="HW";

Page 5: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Aggregate Functions

• Example 19: Save as example 19– Find the number of customers and the total of

their balances.– Calculate total: sum(field name)

Page 6: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 19SQL Query to Count Records and

Calculate a Total

Page 7: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 19

SELECT count(*), Sum(Balance)FROM Customer;

Page 8: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Aggregate Functions

• Example 20: Save as example 20– Find the total number of customers and the total

of their balances. Change the column names for the number of customers and the total of their balances to CustomerCount and BalancesTotal.

– Change column name using “AS” command

Page 9: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 20SQL Query to Perform Calculations and

Rename Fields

Page 10: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 20

SELECT count(*) AS CustomerCount, Sum(Balance) AS BalanceTotal

FROM Customer;

Page 11: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Nested Query

• A query inside another query– A inside query (sub-query) is evaluated first. – It is common to enclose sub-query in parentheses for

readability!!

• Example 21: Save as example 21– List the order number for each order from the order

line table for a part located in warehouse 3.– Use “IN” command for combining two queries– Let ‘s see the answer first and then analyze

Page 12: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 21SQL Query with Subquery

Page 13: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 21SELECT OrderNumFROM OrderLineWHERE PartNum IN

(SELECT PartNum FROM PartWHERE Warehouse='3');

Page 14: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples - Grouping

• Use GROUP BY clause– ONLY grouping, NOT sorting (usually associated

with ORDER BY clause)

• Example 22: Save as example 22– For each sales rep, list the rep number, the

number of customers assigned to each rep, and the average balance of the rep’s customers.

– Rename the count of the number of customers and the average of the balances to NumOfCustomers and AverageBalance

Page 15: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 22SQL Query to Group Records

Page 16: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 22SELECT RepNum,

Count(*) AS NumOfCustomer, Avg(Balance) AS AvgBalance

FROM CustomerGROUP BY RepNum

Page 17: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Grouping (con’t)

• Example 23: Save as example 23– For each sales rep with fewer than four customers, list

the rep number, the number of customers assigned to the rep, and the average balance of the rep’s customers. Rename the count of the number of customers and the average of the balances to NumOfCustomers and AverageBalance.

– Use of “Having” command.

Page 18: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 23 SQL Query to Restrict Groups

Page 19: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 23

SELECT RepNum, count(*) AS NumCustomer, Avg(Balance) AS AverageBalance

FROM CustomerGROUP BY RepNumHAVING Count(*)<4;

Page 20: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Grouping (con’t)

• Use of Where and Having clauses together– “Where” command must be stated first

• Example 23-1: Save as example 23-1– Exactly same as example 23. Except, only groups

with fewer than three records and customers with credit limit of less than $10,000 must be included.

Page 21: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 23-1SQL Query with ‘WHERE’

and ‘HAVING’ Clauses

Page 22: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 23-1

SELECT RepNum, count(*) AS NumCustomer, Avg(Balance) AS AverageBalance

FROM CustomerWHERE CreditLimit<10000GROUP BY RepNumHAVING Count(*)<3;

Page 23: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Pine Valley Furniture Company data data modelmodel

23

(from Chapter 1, Figure 1-3)

Page 24: SQL – Part II Yong Choi School of Business CSU, Bakersfield

24

These tables are used in queries that follow

Figure 7-1 Pine Valley Furniture Company Customer_T and Order_T tables with pointers from customers to their orders

24Chapter 7 Copyright © 2014 Pearson Education, Inc.Copyright © 2014 Pearson Education, Inc.

Page 25: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Equi-Join ExampleEqui-Join Example• For each customer who placed an order, what

is the customer’s name and order number?

25

The best way to find out match customers with their orders is including CustumerID from both tables B/C it is a common field between two as PK and FK.

Page 26: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Processing Multiple TablesProcessing Multiple Tables

• Type of Joins (driven from Set Theory)– Equi-join– Natural join– Outer join: Left or Right – Union join– Self join

• Each example in the textbook chapter 7

26

Page 27: SQL – Part II Yong Choi School of Business CSU, Bakersfield

27

Example visualization of different join types with Example visualization of different join types with results returned in shaded arearesults returned in shaded area

Page 28: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Joining Tables

• Use of multiple tables• Example 24: Save as example 24

– List the number and name of each customer together with the number, last name, and first name of the sales rep who represents the customer.

• CustomerNum, CustomerName, RepNum, LastName, FirstName

Page 29: SQL – Part II Yong Choi School of Business CSU, Bakersfield

29

CustomerNum CustomerName Street City State Zip Balance CreditLimit RepNum

148 Al's Appliance and Sport 2837 Greenway Fillmore FL 33336 $6,550 $7,500 20

Customer

Rep

RepNum LastName FirstName Street City State Zip Commission Rate

20 Kaiser Valerie 624 Randall Grove FL 33321 $20,542.50 0.05

Page 30: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 24SQL Query to Join Tables

Page 31: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 24

SELECT CustomerNum, CustomerName, Rep.RepNum, LastName, FirstName

FROM Customer, RepWHERE Rep.RepNum=Customer.RepNum;

Page 32: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Select both: Customer.RepNum and Rep.RepNum

With: WHERE Rep.RepNum=Customer.RepNum

Page 33: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Include Rep.RepNum but no where statement:WHERE Rep.RepNum = Customer.RepNum

Page 34: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Joining Tables (con’t)

• Use of multiple tables with a compound condition

• Example 25: Save as example 25– List the number and name of each customer

whose credit limit is $10,000 together with number, last name, and first name of the sales rep who represents the customer.

Page 35: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 25Query to Restrict Records in Join

Page 36: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 25 (up to here for the exam)

SELECT CustomerNum, CustomerName, Rep.RepNum, LastName, FirstName

FROM Customer, RepWHERE Rep.RepNum=Customer.RepNumAND CreditLimit=10000;

Page 37: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Joining Tables (con’t)

• Example 26: Save as example– For every order, list the order number, order date,

customer number, and customer name. In addition, for each order line within the order, list the part number, description, number ordered, and quoted price.

– How many tables?– How many conditions?

Page 38: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 26Query to Join Multiple Tables

Page 39: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 26

SELECT Orders.OrderNum, Orderdate, Customer.CustomerNum, CustomerName, Part.PartNum, Description, NumOrdered, QuotedPrice

FROM Orders, Customer, OrderLine, PartWHERE

Customer.CustomerNum=Orders.CustomerNum AND Orders.OrderNum=OrderLine.OrderNum AND OrderLine.PartNum=Part.PartNum;

Page 40: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Union

• The union of two tables is a table containing all rows that are in either the first table, the second table, or both tables. – Two tables involved in union must have same structure.

• Example 27: Save as example 27– List the number and name of all customers that

are either represented by sales rep 35 or that currently have orders on file, or both.

Page 41: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 27 SQL Query to Perform UnionRed: Currently have orders on fileBlue: Represented by sales rep 35

Green: Both

Page 42: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 27

SELECT CustomerNum, CustomerNameFROM CustomerWHERE RepNum='35'

UNION SELECT Customer.CustomerNum, CustomerNameFROM Customer, OrdersWHERE Customer.CustomerNum=Orders.CustomerNum;

Page 43: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Three Basic Functions by SQLAnd Their Basic SQL Commands

1.Data definition (last topic) through the use of CREATE

2.Data manipulation (next topic) through INSERT, UPDATE, and DELETE

3.Data querying (we are done with this) through the use of SELECT AND MANY OTHERS, which is the basis for all SQL queries.

Page 44: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL - Data Manipulation

• Possible with Access– UPDATE– INSERT– DELETE

• Possible with enterprise level DBMS– COMMIT– ROLLBACK

Page 45: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL - Data Manipulation (con’t)

• UPDATE command makes data entry corrections

UPDATE Project

SET PrjtLocat = 'Bellaire', DeptNum = 5

WHERE PrjtNum = 10;

 

UPDATE Employee

SET Salary = Salary * 1.1

WHERE Branch = 'Lincoln';

Page 46: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL - Data Manipulation (con’t)

• INSERT command add new data to a table

INSERT INTO Employee (SSN, LastName, FirstName)

VALUES ('Richard', 'Marini', '43433');

• DELETE command removes table row

– DELETE FROM Employee– WHERE LastName = 'Brown';

Page 47: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL - Data Manipulation (con’t)

• COMMIT command store data on the secondary memory permanently

• ROLLBACK command restores database back to previous condition if COMMIT hasn’t been used

Page 48: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples - Data Manipulation

• Example 28: Save as example 28– Change the street address of customer 524 to

1445 Rivard– First, review the current street address of

customer 524 (838 Ridgeland)

Page 49: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 28

UPDATE Customer SET Street = '1445 Rivard'WHERE CustomerNum='524';

Page 50: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples - Data Manipulation

• Example 29: Save as example 29– Add a new sales rep to the Rep table. Her number

is 16, her name is Sharon Rands, and her address is 826 Raymond, Altonville, FL 32543. She has not yet earned any commission, but her commission rate is 5%(0.05).

Page 51: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 29

INSERT INTO RepVALUES ('16', 'Rands', 'Shron', '826

Raymond', 'Altonville', 'FL', '32543', 0, 0.05);

Page 52: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples - Data Manipulation

• Example 30: Save as example 30– Delete any row in the Orderline table in which the

part number is BV06– First, review the part number BV06

(OrderNum21617)

Page 53: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 30

DELETE *FROM OrderLineWHERE PartNum='BV06';

Page 54: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Creating a New Table Using a Existing Table

• Example 31: save as example 31– Create a new table named SmallCust, consisting

of all fields from the Customer table and those rows in which the credit limit is less than or equal to $7,500.

SELECT INTO Name of table to createFROMWHERE

Page 55: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 31SQL Query to Create New Table

Page 56: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 31

SELECT * INTO SmallCust

FROM Customer

WHERE CreditLimit<=7500;

Page 57: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL - Data Definition I

• Create a database structure to hold all the database tables; MS Access ONLY can create tables

• Usually, only a DBA can create a new database structure

SQL syntax for creating a database structure:CREATE SCHEMA AUTHORIZATION <creator>;

Example:CREATE SCHEMA AUTHORIZATION JONES;

Page 58: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL - Data Definition II

• Specify a new relation by giving it a name and specifying each of its attributes.

• Each attribute is given a name, a data type to specify its values, and some constraints on the attribute.

• Syntax:

CREATE TABLE <table name>;

Page 59: SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Example – Data Definition

• Example 32: Save as example 32– Create a table call “CSUB” that contains following

fields:• EmpID Number (vs. Number(9) or Num(9))• LastName Char(20)• FirstName Char(20)• Street Char(30)• City Char(20)• State Char(2)• Phone Number

Page 60: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 32 (con’t)

Using AccessCreate table CSUB(EmpID Number, LastName Char(20), FirstName Char(20), Street

Char(30), City Char(20), State Char(2), Phone Number);

• Insert following values:– EmpID: 123456789– LastName: your lastname– FirstName: your firstname– Street: 9001 Stockdale Hgwy– City: Bakersfield– State: CA– Phone: 6616656691

Page 61: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Example 32

INSERT INTO Employee

VALUES ('987654321', 'Choi', 'Yong', '9001 Stockdale', 'Bakersfield', 'CA', '123456789');

Page 62: SQL – Part II Yong Choi School of Business CSU, Bakersfield

Using OracleCREATE TABLE EMPLOYEE

(FNAME VARCHAR(15) NOT NULL,

LNAME VARCHAR(15) NOT NULL,

SSN CHAR(9) NOT NULL, BDATE DATE,

SEX CHAR,

SALARY DECIMAL(10,2),

SUPERSSN CHAR(9),

DEPTNO INT NOT NULL, PRIMARY KEY (SSN),

FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(SSN), FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER) );