Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL Chapters 6 & 7.

Similar presentations


Presentation on theme: "SQL Chapters 6 & 7."— Presentation transcript:

1 SQL Chapters 6 & 7

2 Sql queries

3 Querying Data 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

4 Retrieving data

5 Querying Tables Basic Format: Rules: 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 Selecting all rows, specific columns
SELECT column1[, column2, column3,…,columnX] FROM table; List all customer IDs on orders SELECT customer_ID FROM order_t;

7 Selecting All Rows, all columns
FROM table; Display information about all orders FROM order_t;

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

9 Sorting data

10 Sorting Results 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;

11 filtering data

12 Search Conditions For retrieving specific rows: SELECT column(s)
Comparison Operators Boolean Operators Special Operators Calculated Fields (Expressions) SELECT column(s) FROM table WHERE <search condition(s)>;

13 Comparison Operators, con't...
= equal to > greater than < less than >= greater than or equal to <= less than or equal to <> not equal to

14 Comparison Operators, cont…
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;

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

16 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

17 Special Operators Shortcuts IN BETWEEN Wildcard matching LIKE NULL TOP

18 Special Operators, cont…
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. WHERE Customer_ID BETWEEN 1 AND 5;

19 Special Operators, cont…
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. WHERE Customer_Name LIKE '%furn_____';

20 Special Operators, cont…
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;

21 Special operators, cont…
TOP n Displays first N rows of query results Display the first 3 orders… SELECT TOP 3 * FROM order_t; FROM order_t ORDER BY order_date;  In the table???  That we ever received???

22 Special operators, cont…
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

23 Calculated fields, expressions

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

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

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

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

28 Sql server cast function
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)…;

29 functions

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

31 scalar functions

32 DATES 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 Function Description 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 Dates, cont… 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"

34 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 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_t ORDER BY "Order Age in Years" DESC;

35 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) SELECT product_id, standard_price, FLOOR(standard_price*.965)

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

37 Aggregate functions

38 Aggregate Functions Produce aggregated data COUNT MIN MAX SUM AVG

39 Count 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 1st 2000. 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;

40 Min and Max 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;

41 Sum and Avg SELECT SUM(qty_on_hand) FROM Product_t;
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;

42 Grouping data

43 Categorizing Results 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;

44 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 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; GROUP BY state, postal_code;

45 Categorizing Results, con't...
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;

46 Accessing data in multiple tables

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

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

49 Subqueries, cont… Which customers have not placed orders? Show customer IDs and names, sorted by name. SELECT customer_id, customer_name FROM customer_t WHERE customer_id NOT IN (SELECT _____________ FROM order_t) ORDER BY customer_name;

50 Subqueries, cont… 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, FROM Product_t WHERE qty_on_hand IN (SELECT DISTINCT TOP 2 qty_on_hand FROM product_t ORDER BY qty_on_hand DESC);

51 joins Bring data together from multiple rows/tables Several Types
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

52 (Inner) join 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_t WHERE Order_date > '01-NOV-00' AND Customer_t.Customer_ID = Order_t.Customer_ID;

53 (Inner) joins, con't… 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;

54 (inner) joins, con't… 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;

55 (Inner) joins, con't… 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 Self joins 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

57 Self joins, con't… For each customer who has an owner, show the customer's name and their owner's name. CUSTOMER_T

58 Self joins, con't… (fk)

59 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 seminole interiors 2400 rocky point dr. seminole 34646 2 value furniture 15145 x.w.17th st. plano tx 75094 6 furniture gallary 325 flatiron dr. boulder co 80514 5 impressions 5585 westcott ct. sacremento ca 94206 14 kaneohe homes 112 kiowai st. kaneohe hi 96744 8 california classics 816 peach rd. santa clara 96915 15 mountain scenes

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

61 Outer joins 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;

62 Querying Multiple Tables, con't...
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%');

63 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_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);

64 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_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; Table Alias REQUIRED!

65 Querying Multiple Tables, con't…
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)) GROUP BY Product_finish);

66 Querying Multiple Tables, con't…
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 ); Table Alias REQUIRED!

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

68 VIEWs, cont… 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"

69 CASE Analogous to IF-THEN-ELSE within SQL Examples: See:
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)

70 Summary SQL Server Architecture Types of SQL Server Products
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

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


Download ppt "SQL Chapters 6 & 7."

Similar presentations


Ads by Google