Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard...

71
SQL Chapters 6 & 7 1

Transcript of Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard...

Page 1: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SQL

Chapters 6 & 7

1

Page 2: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SQL QUERIES

2

Page 3: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

QUERYING DATA Retrieving Data Sorting Data Filtering Retrieved Data

Combining filtersWildcard filters

Creating Calculated Fields Using Functions Grouping Data

Filtering groups Accessing Data from Multiple Tables

Subqueries Joins

Creating Data Views 3

Page 4: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

RETRIEVING DATA

4

Page 5: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

QUERYING TABLES

5

Basic Format:SELECT column(s)FROM table[WHERE condition(s)];

Rules:SELECT must be first clauseFROM must be second clauseCase does not matter (in SQL Server)Table/column names must be spelled as in

the databaseUse double quotes for object names, single

quotes for literal strings

Page 6: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SELECTING ALL ROWS, SPECIFIC COLUMNS SELECT column1[, column2, column3,

…,columnX]FROM table;

List all customer IDs on ordersSELECT customer_ID FROM order_t;

6

Page 7: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SELECTING ALL ROWS, ALL COLUMNS

SELECT *FROM table;

Display information about all ordersSELECT * FROM order_t;

7

Page 8: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SELECTING UNIQUE ROWS

SELECT DISTINCT column(s)FROM table;

List all customers who've placed orders.SELECT DISTINCT Customer_ID FROM Order_t;

8

Page 9: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SORTING DATA

9

Page 10: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SORTING RESULTSORDER BY

Orders results in ASC or DESC order of column(s)

List customer names and addresses in descending order of customer's name.SELECT Customer_name, Customer_addressFROM Customer_tORDER BY Customer_name DESC;

List product numbers, descriptions, and quantities on hand for all products. Show products with highest quantities first, and then in alphabetical order of product description.

SELECT Product_id, product_description, qty_on_handFROM Product_tORDER BY qty_on_hand DESC, product_description ASC; 10

Page 11: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

FILTERING DATA

11

Page 12: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SEARCH CONDITIONS For retrieving specific rows:

Comparison OperatorsBoolean OperatorsSpecial OperatorsCalculated Fields (Expressions)

SELECT column(s)FROM tableWHERE <search condition(s)>;

12

Page 13: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

COMPARISON OPERATORS, CON'T...

Comparison Operators:= equal to> greater than< less than>= greater than or equal to<= less than or equal to<> not equal to

13

Page 14: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

COMPARISON OPERATORS, CONT… Show order IDs and dates of all

orders placed by customer 1.SELECT Order_ID, Order_Date FROM Order_tWHERE Customer_ID = 1;

Show the time that order #1002 was placed.SELECT Order_id,

CONVERT(varchar(8), Order_Date, 8) AS "Order Time"FROM Order_tWHERE Order_id = 1002;

14

Page 15: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

BOOLEAN OPERATORSBoolean Operators

AND all search conditions must be metOR any search condition must be metNOT a search condition must not be met

Show orders placed by customer 1 with order ID(s) higher than 1005.

SELECT *FROM Order_tWHERE Customer_ID = 1AND Order_ID > 1005;

15

Page 16: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

ORDER OF EVALUATION NOT, AND, OR Use parentheses to ensure desired ordering

Show orders placed by CUSTOMERS EXCEPT customer 1, and with order ID(s) higher than 1007

Show orders placed by customers except customer 1, that have EITHER an order ID higher than 1007 OR an order date on the 24TH of the month

16

Page 17: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SPECIAL OPERATORS

Shortcuts INBETWEEN

Wildcard matchingLIKE

NULL TOP

17

Page 18: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SPECIAL OPERATORS, CONT… IN

Find dates that customers 1, 3, & 5 placed orders.

SELECT Customer_ID, Order_DateFROM Order_tWHERE Customer_ID IN (1,3,5);

BETWEENFind dates of orders placed by customers 1

thru 5.SELECT Customer_ID, Order_DateFROM Order_tWHERE Customer_ID BETWEEN

1 AND 5; 18

Page 19: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SPECIAL OPERATORS, CONT…

LIKE

Show customers with 'furn' in their names.SELECT Customer_NameFROM Customer_tWHERE Customer_Name LIKE '%furn%';

Show customers with 'furn' + 5 characters in their names.

SELECT Customer_NameFROM Customer_tWHERE Customer_Name LIKE '%furn_____';

19

Page 20: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SPECIAL OPERATORS, CONT…

Nullunknownnot applicable

List customers who do not have an address listed.SELECT Customer_ID, Customer_NameFROM Customer_tWHERE Customer_address IS NULL;

Beware…SELECT Customer_NameFROM Customer_tWHERE Customer_address = NULL;

20

Page 21: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SPECIAL OPERATORS, CONT…

TOP n Displays first N rows of query results

Display the first 3 orders…SELECT TOP 3 *FROM order_t;

SELECT TOP 3 *FROM order_tORDER BY order_date;

21

In the table???

That we ever received???

Page 22: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SPECIAL OPERATORS, CONT…

TOP n WITH TIESDisplays query result rows that have tie/duplicate

valuesTherefore may return more than N rowsORDER BY is required

Which 2 products have the highest inventory?SELECT TOP 2 product_id, product_description, qty_on_handFROM product_tORDER BY qty_on_hand DESC;

Which products have the 2 highest inventory levels?SELECT TOP 2 WITH TIES product_id, product_description, qty_on_handFROM product_tORDER BY qty_on_hand DESC;

22

Page 23: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

CALCULATED FIELDS,

EXPRESSIONS

23

Page 24: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

USING COLUMN ALIASING Assign friendly names to existing columns Assign names to derived columns Only exists for duration of query

SELECT column_name AS "alias_name" [, ….] FROM table;

Show order information for customers 1, 3, and 4. Label the order dates "Date of Order".

SELECT Order_ID, Order_Date AS "Date of Order", customer_idFROM Order_tWHERE customer_id IN (1, 3, 4)ORDER BY customer_id;

24

Page 25: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

USING TABLE ALIASING Assign friendly (shortened) names to

tables Allows same table to be referenced

multiple times in a query Only exists for duration of query

SELECT column_name(s)[, ….] FROM table table_alias;

List descriptions of all products with any kind of “natural” finish.

SELECT Product_descriptionFROM Product_t PWHERE P.product_finish LIKE 'Natural%';

25

Page 26: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

EXPRESSIONS

Manipulating column values in a query Effect is Temporary

Show the effect of increasing product prices by 10% for those products that are currently priced under $300.

SELECT Product_ID, Standard_Price AS "Old Price", Standard_Price*1.1 AS "New Price"

FROM Product_tWHERE Standard_Price < 300;

26

Page 27: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

CONCATENATING VALUES Connecting text values together

Show the name, full address (street, city, state, zip) and number of orders placed by each customer in Florida.

SELECT customer_name, customer_address + ', ' + city + ', ' +

state + ', ' + postal_code AS "address",

orders_placedFROM customer_tWHERE state = 'fl';

27

Page 28: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SQL SERVER CAST FUNCTION

Converts data from one datatype to anotherUse for all other datatype conversions

CAST ( value AS target_data_type [ ( length ) ] )

Examples: SELECT 'The list price is: ' + CAST(standard_price AS varchar) FROM product_t;

Print 'old zip: ' + CAST(@czip AS varchar)…;

28

Page 29: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

FUNCTIONS

29

Page 30: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

FUNCTIONS

ScalarTextDate/Time

Year, Month, Day …

Mathematical Floor, Ceiling, Round ….

System System_User GetDate() …

AggregateCOUNTMINMAXSUMAVG

30

Display, convert, manipulate values

Page 31: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SCALAR FUNCTIONS

31

Page 32: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

DATES Work with dates in ways other than

mm/dd/yyCan also use CONVERT function to do this

General Information on SQL Server Date functions: http://msdn.microsoft.com/en-us/library/aa258863(SQL.80).aspx http://www.w3schools.com/SQl/sql_dates.asp

Examples of using Date functions http://jahaines.blogspot.com/2009/06/date-functions.html http://sqlserverpedia.com/wiki/Built-in_Functions_-_Date_and_Time_Functions

32

Function DescriptionGETDATE() Returns the current date and timeDATEPART() Returns a single part of a date/timeDATEADD() Adds or subtracts a specified time interval from a

dateDATEDIFF() Returns the time between two dates or timesCONVERT() Displays date/time data in different formatsDAY(), MONTH(), YEAR()

Returns the day, month, or year portion of a date

Page 33: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

DATES, CONT…

Show the year customer 1 last placed an order.SELECT TOP 1 YEAR(order_date) AS "Year Last

Ordered"FROM order_tWHERE customer_id = 1ORDER BY order_date DESC;

Show the different months that orders were placed.SELECT DISTINCT MONTH(order_date)FROM order_t;

SELECT DISTINCT DATENAME(month, order_date) AS "Month"

FROM order_t;

33

Page 34: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

DATES, CONT… How many months have elapsed between

our order dates and today?

SELECT DATEDIFF(MONTH, order_date, GETDATE())

FROM order_t;

* syntax is DATEDIFF(datepart, start_date, end_date)

** see http://www.w3schools.com/sql/func_datediff.asp for examples of how to subtract other date parts such as times

Show how old, in years, our orders are. Show results in descending order of age.SELECT order_id, YEAR(getdate()) -

YEAR(order_date) AS "Order Age in Years"

FROM order_tORDER BY "Order Age in Years" DESC;

34

Page 35: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

NUMERIC

Performs mathematical functions

Show the effects of decreasing product prices by 3.5%.

SELECT product_id, standard_price, standard_price*.965

FROM product_t;

SELECT product_id, standard_price, ROUND(standard_price*.965, 2)

FROM product_t;

SELECT product_id, standard_price, FLOOR(standard_price*.965)

FROM product_t;35

Page 36: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SYSTEM Retrieves information maintained by SQL

Server

Who is the user currently logged on?

SELECT SYSTEM_USER;

What is today's date?

SELECT GETDATE();

What orders were placed in the current month of any year?

SELECT *FROM order_tWHERE MONTH(order_date) = MONTH(GETDATE());

36

Page 37: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

AGGREGATE FUNCTIONS

37

Page 38: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

AGGREGATE FUNCTIONS

Produce aggregated dataCOUNTMINMAXSUMAVG

38

Page 39: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

COUNTCounts number of rows/values retrieved from

query

How many orders are there?SELECT COUNT(*) FROM Order_t;

Show how many orders were placed after Nov 1st 2000.SELECT COUNT(*)FROM Order_tWHERE Order_Date > '01-NOV-00';

How many orders have customer IDs?SELECT COUNT (Customer_ID) FROM Order_t;

How many different customers have placed orders?SELECT COUNT (DISTINCT Customer_ID)FROM Order_t;

39

Page 40: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

MIN AND MAXFinds minimum/maximum value of

attribute

Find date of most recent order.SELECT MAX(Order_Date) FROM Order_t;

Show the earliest year that an order was ever placed.

SELECT MIN (YEAR(Order_Date))FROM Order_t;

Show the date that customer 1 first placed an order.

SELECT MIN(Order_Date)FROM Order_tWHERE Customer_ID = 1;

40

Page 41: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SUM AND AVGSUM (totals values for specific attribute)

How many products are in inventory?SELECT SUM(qty_on_hand) FROM Product_t;

AVG (finds average value of an attribute)

What's the average price of our products?SELECT AVG(Standard_Price) FROM Product_t;

List the average product price and lowest

product quantity on hand of our products. SELECT AVG(Standard_Price),MIN(qty_on_hand) FROM

Product_t;41

Page 42: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

GROUPING DATA

42

Page 43: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

CATEGORIZING RESULTS

GROUP BYgroups output according to an attributecan perform operations on groups of rows

List the average product price and lowest product quantity on hand for each product finish we offer.

SELECT Product_finish, AVG(Standard_Price), MIN(qty_on_hand)FROM Product_t;

SELECT Product_finish,AVG(Standard_Price),MIN(qty_on_hand)FROM Product_tGROUP BY Product_finish;

43

Page 44: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

MORE ON GROUP BY’S… How many customers are there in each

state?SELECT COUNT(customer_id) FROM customer_t GROUP BY state;

SELECT COUNT(customer_id), state FROM customer_t GROUP BY state;

How many customers are in each postal_code area of each state?SELECT COUNT(customer_id), state, postal_code FROM customer_tGROUP BY state;

SELECT COUNT(customer_id), state, postal_code FROM customer_tGROUP BY state, postal_code;

44

Page 45: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

CATEGORIZING RESULTS, CON'T...

HAVINGLike a WHERE clause for groups

List the average product price and lowest product quantity on hand for each product finish that has (a) at least one product with two or more units on hand, and (b) at least 3 products with that finish.

SELECT Product_finish, AVG(Standard_Price), MIN(Qty_on_hand)FROM Product_tGROUP BY Product_finishHAVING MIN (Qty_On_hand) >= 2AND COUNT (Product_id) >=3;

45

Page 46: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

ACCESSING DATA IN MULTIPLE TABLES

46

Page 47: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

Nested Queries (aka Subqueries) Joins

(Inner) JoinSelf Join (Outer) Left Join

Checking Non-Existence ConditionsNOT INNOT EXISTS

Creating Views of data

47

QUERYING MULTIPLE TABLES

Page 48: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SUBQUERIES Placing an "inner" query in WHERE clause Inner queries must SELECT only one column Column selected by "inner" query must match

column in WHERE clause of “outer" query

Show all orders placed by customers who live in states that do NOT end in 'A'. Show orders in descending order.

SELECT Order_IDFROM Order_tWHERE Customer_ID IN

(SELECT Customer_IDFROM Customer_tWHERE State NOT LIKE '_A')

ORDER BY Order_ID DESC; 48

Page 49: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SUBQUERIES, CONT…

Which customers have not placed orders? Show customer IDs and names, sorted by name.

SELECT customer_id, customer_nameFROM customer_tWHERE customer_id NOT IN

(SELECT _____________ FROM order_t)

ORDER BY customer_name;

49

Page 50: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SUBQUERIES, CONT…

Revisit: Which 2 products have the highest inventory?

SELECT TOP 2 WITH TIES product_id, product_description,

qty_on_handFROM product_tORDER BY qty_on_hand DESC;

SELECT product_id, product_description, qty_on_hand

FROM Product_t WHERE qty_on_hand IN

(SELECT DISTINCT TOP 2 qty_on_hand FROM product_t ORDER BY qty_on_hand DESC);

50

Page 51: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

51

JOINS Bring data together from multiple

rows/tables Use common column in both rows/tables Common columns can have same or different names Must use table_name.column_name to distinguish

columns with same names Can specify one or multiple tables to connect Use WHERE or FROM clause to connect tables

Several Types Cross Join (Inner) Join Self Join (Outer) Left Join (Outer) Right Join (Outer) Full Join

See http://www.quackit.com/sql/tutorial/sql_join.cfm

Page 52: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

(INNER) JOIN

52

Retrieve Customer Names, Customer IDs, and Order Dates of orders placed after Nov 1, 2000.

SELECT Customer_t.Customer_ID, Customer_Name, Order_date

FROM Customer_t, Order_tWHERE Order_date > '01-NOV-00'AND Customer_t.Customer_ID =

Order_t.Customer_ID;

Page 53: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

(INNER) JOINS, CON'T…

List descriptions of all products ordered by customer 1.

SELECT Product_descriptionFROM Order_Line_t, Order_t, Product_tWHERE Order_t.Customer_ID = 1AND Order_t.Order_ID = Order_Line_t.Order_IDAND Order_Line_t.Product_ID = Product_t.Product_ID;

53

Page 54: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

(INNER) JOINS, CON'T…

List descriptions of all products ordered by customer 1.

SELECT Product_descriptionFROM (Order_Line_t ol INNER JOIN Order_t o

ON ol.Order_ID = o.Order_ID) INNER JOIN Product_t p ON ol.Product_ID = p.Product_ID

WHERE o.Customer_ID = 1;

54

Page 55: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

(INNER) JOINS, CON'T…

55

Let's combine concepts!

Assuming all orders need to be filled, which products do not have enough quantity on hand to fill their orders?

Show the product ID, description, the quantity of the product on hand, and the total quantity of the product ordered.

Page 56: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SELF JOINS

Join a table to itself Rows from the same table are related

i.e., recursive relationshipsPrimary and Foreign keys in same table,

different rows

56

Page 57: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SELF JOINS, CON'T… For each customer who has an owner,

show the customer's name and their owner's name.

customer_id(pk) customer_name customer_address city state postal_code owner_id (fk)

1 contemporary casuals

1355 s. hines blvd. gainsville fl 32601 10

2 value furniture 15145 x.w.17th st. plano tx 75094 3 home furnishings 1900 allard ave. albany ny 12209 4 eastern furniture 1925 beltline rd. carteret nj 7008 5 impressions 5585 westcott ct. sacramento ca 94206 2 6 furniture gallary 325 flatiron dr. boulder co 80514 10 7 period

furnishings 394 rainbow dr. seattle wa 97954

8 california classics

816 peach rd. santa clara ca 96915 15

9 M and H casual furniture

3709 1st st. clearwater fl 34620

10 seminole interiors

2400 rocky point dr. seminole fl 34646 2

11 american euro lifestyles

2424 missouri ave. n.

propect park

nj 7508

12 battle creek furniture

345 capitol ave. sw battlecreek mi 49015

13 heritage furnishings

66789 college ave. carlisle pa 17013

14 kaneohe homes 112 kiowai st. kaneohe hi 96744 10 15 mountain scenes 4132 main st. ogden ut 84403

CUSTOMER_T

57

Page 58: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SELF JOINS, CON'T…

is_ow ned_by

customer

customer_id (pk)

addr

city

name

ow ner_id

postal_code

state

is_ow ned_by

customer

customer_id (pk)

address

city

name

ow ner_id (fk)

postal_code

state

owning_customer

customer_id (pk)

address

city

name

ow ner_id (fk)

postal_code

state

(fk)

58

Page 59: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SELF JOINS, CON'T… For each customer who has an owner,

show the customer's name and their owner's name.

  

 

  

c.id

c.name c.addr c.city c.state

c.postal_cd

c.ownid

o.id

o.name o.addr o.city o.state

o.postal_cd

o.ownid

1 contemporary casuals

1355 s. hines blvd

gainesville

fl 32601 10 10 seminole interiors

2400 rocky point dr.

seminole

fl 34646 2

10 seminole interiors

2400 rocky point dr.

seminole fl 34646 2 2 value furniture

15145 x.w.17th st.

plano tx 75094  

6 furniture gallary 325 flatiron dr. boulder co 80514 10 10 seminole interiors

2400 rocky point dr.

seminole

fl 34646 2

5 impressions 5585 westcott ct.

sacremento

ca 94206 2 2 value furniture

15145 x.w.17th st.

plano tx 75094  

14 kaneohe homes 112 kiowai st. kaneohe hi 96744 10 10 seminole interiors

2400 rocky point dr.

seminole

fl 34646 2

8 california classics

816 peach rd. santa clara

ca 96915 15 15 mountain scenes

         

 

59

Page 60: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SELF JOINS, CON'T… For each customer who has an

owner, show the customer's name and their owner's name.

SELECT C.Customer_name AS "Customer", O.Customer_name AS "Owner"FROM Customer_t C, Customer_t OWHERE C.Owner_ID = O.Customer_ID;

60

Page 61: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

OUTER JOINSLeft (Outer) Joins

Brings data together from multiple rows/tables Use common column in both rows/tables Retrieves all rows from first table, and only

matching rows from second table Use table_name.column_name to distinguish columns Can specify TWO tables at a time to connect Use FROM clause to connect tables

List products that have not been ordered(NOTE: include product IDs and descriptions)

SELECT p.Product_ID, p.Product_DescriptionFROM Product_t p LEFT JOIN Order_line_t ol

ON p.Product_ID = ol.Product_IDWHERE ol.Product_ID IS NULL;

61

Page 62: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

QUERYING MULTIPLE TABLES, CON'T...

Checking Non-ExistenceList customers who have NOT ordered

computer desks(NOTE: include customers who have not placed ANY orders)

SELECT Customer_ID, customer_name

FROM Customer_tWHERE Customer_ID NOT IN

(SELECT Customer_IDFROM Order_t, Order_line_t, Product_tWHERE Order_t.Order_ID = Order_line_t.Order_IDAND Order_line_t.Product_ID =

Product_t.Product_IDAND Product_Description LIKE '%computer desk

%');62

Page 63: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

QUERYING MULTIPLE TABLES, CON'T...

Checking Non-Existence, con't...List customers who have NOT ordered

computer desks(NOTE: include customers who have not placed ANY orders)

SELECT Customer_ID, customer_nameFROM Customer_t c1WHERE NOT EXISTS

(SELECT * FROM Order_t o, Order_line_t ol, Product_t p WHERE o.Order_ID = ol.Order_ID AND ol.Product_ID = p.Product_ID AND Product_Description LIKE '%computer desk

%'AND c1.customer_id = o.customer_id);

63

Page 64: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

QUERYING MULTIPLE TABLES, CON'T…

Derived Tables Placing an "inner" query in the FROM clause Must use table alias for derived table

SELECT col(s)FROM (SELECT col(s) FROM table(s)

WHERE…) tblalias[WHERE …];

Retrieve Customer Names, Customer IDs, and Order Dates of orders placed after Nov 1, 2000.SELECT xyz.customer_id, xyz.customer_name, xyz.order_dateFROM (SELECT c.Customer_ID, c.Customer_Name, Order_Date

FROM Customer_t c, Order_t o WHERE Order_date > '01-NOV-00' AND c.Customer_id = o.Customer_id) XYZ;64

Table Alias REQUIRED!

Page 65: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

QUERYING MULTIPLE TABLES, CON'T… Derived Tables, cont… What product finish has the highest

average price?

SELECT Product_finish, AVG(Standard_Price)

FROM Product_tGROUP BY Product_finishHAVING AVG(Standard_Price) =

(SELECT MAX(AVG(Standard_Price)) FROM Product_t GROUP BY Product_finish);

65

Page 66: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

QUERYING MULTIPLE TABLES, CON'T… Derived Tables, cont… What product finish has the highest

average price?

SELECT Product_finish, AVG(Standard_Price)

FROM Product_tGROUP BY Product_finishHAVING AVG(Standard_Price) =

(SELECT MAX(Price) FROM (SELECT AVG(Standard_Price) AS

Price FROM Product_t GROUP BY Product_finish)

TempTbl ); 66

Table Alias REQUIRED!

Page 67: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

VIEWS Dynamic vs. "Materialized" Why use views?

Simplify queriesRename columnsSecurity

CREATE VIEW view_name ASSELECT …… ;

67

Page 68: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

VIEWS, CONT…Retrieve all the data elements required to create a

customer invoiceSELECT c.customer_id, customer_address, o.order_id, p.product_id, product_description,

standard_price, ordered_quantity, standard_price*ordered_quantity AS "line item cost"

FROM customer_t c, order_t o, order_line_t ol, product_t p

WHERE c.customer_id = o.customer_id

AND o.order_id = ol.order_id

AND ol.product_id = p.product_id;

Create a view that retrieves all the data elements required to create a customer invoice

CREATE VIEW invoice_view AS

SELECT o.customer_id, customer_address, ol.order_id, ol.product_id, product_description, standard_price, ordered_quantity as quantity, standard_price*ordered_quantity AS "line item cost"

FROM customer_t c, order_t o, order_line_t ol, product_t p

WHERE c.customer_id = o.customer_id

AND o.order_id = ol.order_id

AND ol.product_id = p.product_id;

68

Page 69: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

CASE Analogous to IF-THEN-ELSE within SQL

Examples: SELECT product_id, CASE

WHEN product_id = 3 THEN order_id

WHEN product_id = 8 THEN product_id

ELSE ordered_quantity

END

AS "order#, product#, or QN"

FROM order_line_t;

SELECT CASE WHEN state = 'FL' THEN postal_code END

FROM customer_t

WHERE customer_id <> 9;

See: http://www.java2s.com/Code/Oracle/Select-Query/CombineCasewithgroupby.htm http://www.adp-gmbh.ch/ora/sql/case_when.html http://www.cryer.co.uk/brian/sql/sql_crib_sheet.htm (syntax for different dbms's)69

Page 70: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

SUMMARY SQL Server Architecture

Components Where user data and metadata are stored How applications fit in

Types of SQL Server Products Our focus is on the query services and the RDBMS

How to access SQL Server for class History of SQL SQL Environment SQL Language

DDL DML

Basic Query Search Conditions Categorizing and Sorting Results Querying Multiple Tables

Various flavors of Joins Various Flavors of Subqueries

Additional SQL commands 70

Page 71: Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions.

NEXT TIME…

3/20 *** Quiz 2 ***

4/3 Database Stored CodeChapter 7: Advanced SQL

Pages 320 – 327

4/3 *** Assignment 4 Due ***

71