Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapters 6 & 7 1. 2 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions."— Presentation transcript:

1 Chapters 6 & 7 1

2 2

3 Retrieving Data Sorting Data Filtering Retrieved Data Combining filters Wildcard filters Creating Calculated Fields Using Functions Grouping Data Filtering groups Accessing Data from Multiple Tables Subqueries Joins Creating Data Views 3

4 4

5 5 Basic Format: SELECT column(s) FROM table [WHERE condition(s)]; Rules: SELECT must be first clause FROM must be second clause Case does not matter (in SQL Server) Table/column names must be spelled as in the database Use double quotes for object names, single quotes for literal strings

6 SELECT column1[, column2, column3,…,columnX] FROM table; List all customer IDs on orders SELECT customer_ID FROM order_t; 6

7 SELECT * FROM table; Display information about all orders SELECT * FROM order_t; 7

8 SELECT DISTINCT column(s) FROM table; List all customers who've placed orders. SELECT DISTINCT Customer_ID FROM Order_t; 8

9 9

10 ORDER 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_address FROM Customer_t ORDER 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_hand FROM Product_t ORDER BY qty_on_hand DESC, product_description ASC; 10

11 11

12 For retrieving specific rows: Comparison Operators Boolean Operators Special Operators Calculated Fields (Expressions) SELECT column(s) FROM table WHERE ; 12

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

14 Show order IDs and dates of all orders placed by customer 1. SELECT Order_ID, Order_Date FROM Order_t WHERE 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_t WHERE Order_id = 1002; 14

15 Boolean Operators ANDall search conditions must be met ORany search condition must be met NOTa search condition must not be met Show orders placed by customer 1 with order ID(s) higher than SELECT * FROM Order_t WHERE Customer_ID = 1 AND Order_ID > 1005; 15

16 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 24 TH of the month 16

17 Shortcuts IN BETWEEN Wildcard matching LIKE NULL TOP 17

18 IN Find dates that customers 1, 3, & 5 placed orders. SELECT Customer_ID, Order_Date FROM Order_t WHERE Customer_ID IN (1,3,5); BETWEEN Find dates of orders placed by customers 1 thru 5. SELECT Customer_ID, Order_Date FROM Order_t WHERE Customer_ID BETWEEN 1 AND 5; 18

19 LIKE Show customers with 'furn' in their names. SELECT Customer_Name FROM Customer_t WHERE Customer_Name LIKE '%furn%'; Show customers with 'furn' + 5 characters in their names. SELECT Customer_Name FROM Customer_t WHERE Customer_Name LIKE '%furn_____'; 19

20 Null unknown not applicable List customers who do not have an address listed. SELECT Customer_ID, Customer_Name FROM Customer_t WHERE Customer_address IS NULL; Beware… SELECT Customer_Name FROM Customer_t WHERE Customer_address = NULL; 20

21 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_t ORDER BY order_date; 21 In the table??? That we ever received???

22 TOP n WITH TIES Displays query result rows that have tie/duplicate values Therefore may return more than N rows ORDER BY is required Which 2 products have the highest inventory? SELECT TOP 2 product_id, product_description, qty_on_hand FROM product_t ORDER BY qty_on_hand DESC; Which products have the 2 highest inventory levels? SELECT TOP 2 WITH TIES product_id, product_description, qty_on_hand FROM product_t ORDER BY qty_on_hand DESC; 22

23 23

24 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_id FROM Order_t WHERE customer_id IN (1, 3, 4) ORDER BY customer_id; 24

25 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_description FROM Product_t P WHERE P.product_finish LIKE 'Natural%'; 25

26 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_t WHERE Standard_Price < 300; 26

27 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_placed FROM customer_t WHERE state = 'fl'; 27

28 Converts data from one datatype to another Use 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: ' + AS varchar)…; 28

29 29

30 Scalar Text Date/Time Year, Month, Day … Mathematical Floor, Ceiling, Round …. System System_User GetDate() … Aggregate COUNT MIN MAX SUM AVG 30 Display, convert, manipulate values

31 31

32 Work with dates in ways other than mm/dd/yy Can also use CONVERT function to do this General Information on SQL Server Date functions: Examples of using Date functions 32 FunctionDescription GETDATE()Returns the current date and time DATEPART()Returns a single part of a date/time DATEADD()Adds or subtracts a specified time interval from a date DATEDIFF()Returns the time between two dates or times CONVERT()Displays date/time data in different formats DAY(), MONTH(), YEAR()Returns the day, month, or year portion of a date

33 Show the year customer 1 last placed an order. SELECT TOP 1 YEAR(order_date) AS "Year Last Ordered" FROM order_t WHERE customer_id = 1 ORDER 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

34 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 for examples of how to subtract other date parts such as timeshttp://www.w3schools.com/sql/func_datediff.asp 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_t ORDER BY "Order Age in Years" DESC; 34

35 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

36 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_t WHERE MONTH(order_date) = MONTH(GETDATE()); 36

37 37

38 Produce aggregated data COUNT MIN MAX SUM AVG 38

39 Counts 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 1 st SELECT COUNT(*) FROM Order_t WHERE 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

40 Finds 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_t WHERE Customer_ID = 1; 40

41 SUM (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

42 42

43 GROUP BY groups output according to an attribute can 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_t GROUP BY Product_finish; 43

44 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_t GROUP BY state; SELECT COUNT(customer_id), state, postal_code FROM customer_t GROUP BY state, postal_code; 44

45 HAVING Like 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_t GROUP BY Product_finish HAVING MIN (Qty_On_hand) >= 2 AND COUNT (Product_id) >=3; 45

46 46

47 Nested Queries (aka Subqueries) Joins (Inner) Join Self Join (Outer) Left Join Checking Non-Existence Conditions NOT IN NOT EXISTS Creating Views of data 47

48 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_ID FROM Order_t WHERE Customer_ID IN (SELECT Customer_ID FROM Customer_t WHERE State NOT LIKE '_A') ORDER BY Order_ID DESC; 48

49 Which customers have not placed orders? Show customer IDs and names, sorted by name. SELECT customer_id, customer_name FROM customer_t WHEREcustomer_id NOT IN (SELECT_____________ FROMorder_t) ORDER BYcustomer_name; 49

50 Revisit: Which 2 products have the highest inventory? SELECT TOP 2 WITH TIES product_id, product_description, qty_on_hand FROM product_t ORDER 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

51 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 51

52 52 Retrieve Customer Names, Customer IDs, and Order Dates of orders placed after Nov 1, SELECTCustomer_t.Customer_ID, Customer_Name, Order_date FROM Customer_t, Order_t WHERE Order_date > '01-NOV-00' AND Customer_t.Customer_ID = Order_t.Customer_ID;

53 List descriptions of all products ordered by customer 1. SELECT Product_description FROM Order_Line_t, Order_t, Product_t WHERE Order_t.Customer_ID = 1 AND Order_t.Order_ID = Order_Line_t.Order_ID AND Order_Line_t.Product_ID = Product_t.Product_ID; 53

54 List descriptions of all products ordered by customer 1. SELECT Product_description FROM (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

55 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.

56 Join a table to itself Rows from the same table are related i.e., recursive relationships Primary and Foreign keys in same table, different rows 56

57 For each customer who has an owner, show the customer's name and their owner's name. CUSTOMER_T 57

58 (fk) 58

59 For each customer who has an owner, show the customer's name and their owner's name. c. id c.namec.addrc.cityc.sta te c.postal_ cd c.ow nid o.i d o.nameo.addro.cityo.sta te o.postal_ cd o.ow nid 1contemporary casuals 1355 s. hines blvd gainesvil le fl seminole interiors 2400 rocky point dr. semin ole fl seminole interiors 2400 rocky point dr. seminolefl value furniture x.w.17th st. planotx furniture gallary325 flatiron dr.boulderco seminole interiors 2400 rocky point dr. semin ole fl impressions5585 westcott ct. sacreme nto ca value furniture x.w.17th st. planotx kaneohe homes112 kiowai st.kaneohehi seminole interiors 2400 rocky point dr. semin ole fl california classics 816 peach rd.santa clara ca mountain scenes 59

60 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 O WHERE C.Owner_ID = O.Customer_ID; 60

61 Left (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_Description FROM Product_t p LEFT JOIN Order_line_t ol ON p.Product_ID = ol.Product_ID WHERE ol.Product_ID IS NULL; 61

62 Checking Non-Existence List customers who have NOT ordered computer desks (NOTE: include customers who have not placed ANY orders) SELECT Customer_ID, customer_name FROM Customer_t WHERE Customer_ID NOT IN (SELECT Customer_ID FROM Order_t, Order_line_t, Product_t WHERE Order_t.Order_ID = Order_line_t.Order_ID AND Order_line_t.Product_ID = Product_t.Product_ID AND Product_Description LIKE '%computer desk%'); 62

63 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_name FROM Customer_t c1 WHERE 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

64 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, SELECT xyz.customer_id, xyz.customer_name, xyz.order_date FROM (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!

65 Derived Tables, cont… What product finish has the highest average price? SELECT Product_finish, AVG(Standard_Price) FROM Product_t GROUP BY Product_finish HAVING AVG(Standard_Price) = (SELECT MAX(AVG(Standard_Price)) FROM Product_t GROUP BY Product_finish); 65

66 Derived Tables, cont… What product finish has the highest average price? SELECT Product_finish, AVG(Standard_Price) FROM Product_t GROUP BY Product_finish HAVING 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!

67 Dynamic vs. "Materialized" Why use views? Simplify queries Rename columns Security CREATE VIEW view_name AS SELECT …… ; 67

68 Retrieve all the data elements required to create a customer invoice SELECT 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

69 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: (syntax for different dbms's) 69

70 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

71 3/20*** Quiz 2 *** 4/3 Database Stored Code Chapter 7: Advanced SQL Pages 320 – 327 4/3 *** Assignment 4 Due *** 71


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

Similar presentations


Ads by Google