Presentation is loading. Please wait.

Presentation is loading. Please wait.

COP 2700 – Data Structures - SQL

Similar presentations


Presentation on theme: "COP 2700 – Data Structures - SQL"— Presentation transcript:

1 COP 2700 – Data Structures - SQL
Lecture 3 – May 27, 2015 Single Table Select Statements

2 Announcements Assignment 1 is due June 1 by 11:59 PM
Don't wait until June 1 at 11:58 to start the assignment!! Read chapter 2 for Next Monday's class Database Design Fundamentals Explain what is going to be on the first test

3 Tonight Single Table Select Statements
Install SQLServer on the hard-drives Review what we learned last week Apply our knowledge to the Premiere database Lab Time (If there is time!!)

4 Little SQLTool Web Page Upgrade
Premier Database Has Been Added to the Server

5 Basic SELECT Statement
Is one of the commands available in an RDMS Data Manipulation Language (DML) Answers a Question Who, What, How Many, Where Returns a Table that is called a Result Set. (All other DML statements return a success or failure and/or the number of records modified.)

6 Basic Select Statement Again
SELECT {List of Columns or Expressions or * or Literals} FROM {Tables or Views} JOIN {Links between Tables and Views} WHERE {Conditional Statements} GROUP BY {List of Columns} HAVING {More Conditional Statements} ORDER BY {Another List of Columns}

7 Definition of an Expression
An Expression is a series of constants, function calls, and/or columns that are evaluated and then displayed as a single column in a Select clause's Result Set. Different rules are applied based on the type of column/constants used in the expression.

8 Simple Arithmetic Expressions
Without any database columns Select SQRT(45)+36 Notice, no Table name in this case. Only constants. Notice the use of a function. Check out the other arithmetic functions available for SQLServer at With database columns SELECT Part_Num, Description, On_Hand * Price AS Inventory_Value FROM Part

9 Expressions The constants and columns used in an Expression must all have the same basic data type. SQLServer has many different data types, but they can be boiled down into four basic types Numeric Precise – Numeric/Decimal, Bit, Int and others Estimate – Float - Real Character/String (value surrounded by single quotes) Fixed Length – Char and nChar Variable Length – Varchar and nVarchar DateTime (value in a specific format for expressions) DateTime, Date, Time Binary (probably won't use in a expression. Used to store pictures, programs, anything that can be represented as a binary file.) For more information check out:

10 Expressions Converting From One Type to Another
SQLServer uses the Cast function to convert from one data type to another. Best example is converting date or numeric data to string for concatenation (remember the “+” with string data is used to concatenate or “add” strings together.) SELECT ORDER_DATE + '-' + Customer_Name AS Date_Customer FROM Premiere SELECT CAST(ORDER_DATE as varchar(11)) + '-' + Customer_Name AS Date_Customer FROM Premiere Same idea can be used for numeric data. You have to be careful with the size though. May truncate or round data, and sometimes can return an error. SELECT CAST(price AS varchar(2)) as Too_Short, Description FROM Part Notice the use of column aliases above!!

11 Expressions – Some String Functions
Substring(Expression,Start,Length) returns a string starting at character Start for Length positions. CharIndex(Compare, Expression) returns an integer of the first occurrence of Compare in the string Expression SELECT SUBSTRING(street,1,CHARINDEX(' ',street)) AS Street_Number, SUBSTRING(Street, CHARINDEX(' ',Street)+1,20) AS Street_Name FROM customer

12 Priority Database

13 Where Clause Series of conditional statements that evaluate to True or False Each conditional statement is of the form Expression Comparison-Operator Expression The Conditional Operators Include = < > <= >= != <> Notice the Conditional Statements compares Expressions, not necessarily just columns and constants. SELECT * FROM Part WHERE Class = 'HW' SELECT * FROM PART WHERE 'HW' = Class SELECT * FROM PART WHERE ON_HAND * PRICE > 2000

14 Where Clause Can be connected with AND/OR making a compound condition
Can be logically defined with parenthesis SELECT * FROM PART WHERE ON_HAND * PRICE > 3000 AND CLASS = 'SQ' OR CLASS = 'HW' (CLASS = 'SQ' OR CLASS = 'HW') Remember. The default in SQLServer is that capitalization of data does not matter, so unless you specifically install SQLServer requiring conditional statements to differentiate between capitalization, 'Miami', 'MIAMI' or 'miami' will all match.

15 WHERE Clause - NOT Reverses the logical value of a conditional statement. Applies to the next conditional statement (or parenthetical group of statement) SELECT * FROM Part WHERE On_Hand * Price > 3000 is the same as SELECT * FROM Part WHERE NOT On_Hand * Price <= 3000 WHERE Warehouse = 1 OR Warehouse = 3 is the same as ????? WHERE NOT (Warehouse != 1 AND Warehouse != 3) Why is that??

16 WHERE Clause - IN Creates a Special “shorthand” Conditional Statement
Allows a user to list a set of possible values in a WHERE clause. List of Parts in Warehouses 1 or 3 using OR SELECT * FROM Part WHERE Warehouse = 1 OR Warehouse = 3 Same Query using IN WHERE Warehouse IN (1, 3) Since it's just another Conditional Statement, we can connect them together with other conditional statements WHERE Warehouse IN (1, 3) AND SUBSTRING(Description,1,1) = 'D' The NOT is placed in front of the IN to negate the condition SELECT * FROM PART WHERE Warehouse NOT IN (1,3)

17 WHERE Clause - BETWEEN Allows one to specify a from and to boundary (inclusive) for a WHERE clause List all Parts with an on-hand inventory cost >= 2000 and <= 5000 SELECT * FROM Part WHERE On_Hand * Price BETWEEN 2000 and 5000

18 Dates GetDate() = Current system date and time
Cast(GetDate() as Date) = Just the current Date!! Date Arithmetic uses Functions to return a result DateAdd(interval, increment, date or column) Returns a Date type DateDiff (interval, starting, ending) return a Number type To use in a WHERE clause, always format the date as 'DD-MMM-YYYY' to ensure the correct date is selected SQLServer also has functions that can be used when specifying a date or time that use specific formats. We'll check out Cast and Convert later.

19 Nulls A Null is NOT a space and is NOT a blank.
With nulls, the column never had anything inserted into it. Blank, the column was used in an insert with a value of ''. Nulls many times make it difficult to find data if you are not aware that they exist. Select * from Transcript Where Grade != 'A' Will not return any transcript records where the Grade is null. If you want them as well, must specify Select * from Transcript Where Grade != 'A' OR Grade IS NULL If we wanted everything that has a grade Select * from Transcript Where Grade is NOT NULL Notice the special syntax for NULL conditionals (IS NOT NULL, IS NULL)

20 WHERE Clause Practice List the names of customers with credit limits of $10,000 or more. List the order number for each order placed by customer number 608 on 10/23/2010. List the number and name of each customer represented by sales rep 35 or sales rep 65. List the part number and part description of each part that is not in item class AP. List the part number, description, and number of units on hand for each part that has between 10 and 25 units on hand, including both 10 and 25. Do this two ways. List the part number, part description, and on-hand value (units on hand * unit price) of each part in item class SG. Assign the name ON_HAND_VALUE to the computed column. List the part number, part description, and on-hand value for each part whose on-hand value is at least $7,500. Assign the name ON_HAND_VALUE to the computed column. Use the IN operator to list the part number and part description of each part in item class AP or SG.

21 Distinct SELECT Warehouse FROM Part
Warehouse IDs will be repeated SELECT DISTINCT Warehouse FROM Part Warehouse IDs will NOT be repeated

22 Aggregates Sum, Max, Min, Count(*), Avg Functions
Others also available for statistics and analysis How many parts have a price greater than 500?: SELECT Count(*) FROM Part WHERE Price > 500' What is the average part price in the Premiere database SELECT AVG(Price) as Average_Price, Description FROM Part What is the total inventory price (the sum of the on_hand quantity times price)??

23 Count (Distinct Expression)
Used to count the aggregate of an expression without duplicates: How many parts have orders? SELECT Student_ID, Count(*) FROM Registration Group By Student_ID SELECT Student_ID, Count(Distinct Course_Id)

24 Group By Uses the Aggregates to get Subtotals of partitioned data
What is the total inventory price (the sum of the on_hand quantity times price) for each warehouse?? SELECT Warehouse, SUM(On_Hand*Price) as Total_Price FROM Part GROUP BY Warehouse The Group By must at least include ALL fields in the result set that are not aggregated.

25 More Group By Multiple Aggregates can be placed on the Select.
List the maximum item price, the mininum on hand quantity and the total inventory for each warehouse SELECT Warehouse, MAX(Price), MIN(On_Hand), SUM(Price*On_Hand) FROM Part Group By Warehouse

26 More Group By You can group by more stuff than is in the Select clause (which comes in handy for the Having we will get to in a second) SELECT Rep_Num FROM Part GROUP BY Rep_Num This looks stupid, but see what we do with it in the Having

27 Having Applies a second “WHERE” Clause to the result set of a Group By Select So Basically, it does the Aggregate, THEN it applies the Having clause as a secondary filter, so it is Filtering the Aggregate Result. Display all Reps and their customer's total credit limit where the total credit limit is greater than 2800. SELECT Rep_Num, SUM(Credit_Limit) as Total_Limit FROM CUSTOMER GROUP BY REP_NUM HAVING SUM(Credit_Limit) > 28000 Having CANNOT use Column Aliases!!

28 Having Back to that “Stupid” Group By
We don't want the Credit Limit in the Select, only the Rep_Num SELECT Rep_Num FROM CUSTOMER GROUP BY REP_NUM HAVING SUM(Credit_Limit) > 28000

29 Order By Is done AFTER the query is complete.
What does a Select statement return? That is what the Order By is applied against!! Either Column Aliases, Expressions or Column Names can be used The Expressions or Column Names do NOT have to be in the Select (but must be in the table) Orders the resulting table by the fields specified Each field can be sorted either Ascending (ASC) which is the Default) or Descending (DESC) List all Customers sorted by Rep Number and then by Balance Descending SELECT * FROM Customer ORDER BY REP_NUM, BALANCE DESC

30 Order By You can Order By ANYTHING from the Select statement, including aggregate fields List all parts sorted by total value SELECT *, On_Hand * Price As Total_Value FROM Part Order By On_Hand * Price or even Order By Total_Value

31 Sub Queries You can also use a query within a query
With a Sub Query a single column is returned, but with multiple rows that can be used with an “IN” statement With a Scalar a single row with a single column was returned that you can use as a value in a conditional statement

32 Sub Queries List the Order Number of each part in class AP.
Without a Sub Query we first get the list of parts in class AP SELECT Part_Num FROM Part WHERE Class = 'AP' Returns CD52, DR93, DW11, KL62, KT03 Then use that to get the Order Number SELECT Distinct Order_Num FROM Order_Line WHERE Part_Num IN ('CD52', 'DR93', 'DW11', 'KL62', 'KT03')

33 Sub Queries Just stick the two queries together, and Voila!!
SELECT Distinct Order_Num FROM Order_Line WHERE Part_Num IN (SELECT Part_Num FROM Part WHERE Class = 'AP')

34 Sub Queries - Scalar Selects
Selects that return a single value and can be used in a where clause with an equal or not equal List all orders with the highest number of credit hours offered: First, let's get the highest number of credit hours: SELECT MAX(Credit_Hours) FROM Course That's the Scalar (Returns One Column and One Row!!) Now use that as the right side of a condition in a WHERE clause SELECT Distinct Course_ID, Section, Semester FROM Registration WHERE Credit_Hours = (SELECT MAX(Credit_Hours) FROM Course) Any idea why the parenthesis?

35 Other Things You Might See
Brackets or Double Quotes Around Variable Names Allows for spaces in Variable Names SELECT Class, Sum(On_Hand) AS "On Hand Qty" FROM Part GROUP BY Class SELECT Class, Sum(On_Hand) AS [On Hand Qty]" TOP x Only show the Top x (x is a number) from the query. The select is done after everything within the query is completed, including the ORDER BY) Show the two parts that cost the most SELECT TOP 2 * FROM Part ORDER BY Price

36 More Exercises Find the number and name of each customer whose name begins with the letter “B.” List all details about all parts. Order the output by part number within warehouse. (That is, order the output by warehouse and then by part number.) How many customers have balances that are more than their credit limits? Find the total of the balances for all customers represented by sales rep 65 with balances that are less than their credit limits. List the part number, part description, and on-hand value of each part whose number of units on hand is more than the average number of units on hand for all parts. (Hint: Use a subquery.)


Download ppt "COP 2700 – Data Structures - SQL"

Similar presentations


Ads by Google