COP 2700 – Data Structures - SQL

Slides:



Advertisements
Similar presentations
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)MySQL Recap.
Advertisements

Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
Introduction to Structured Query Language (SQL)
Databases Lab 5 Further Select Statements. Functions in SQL There are many types of functions provided. The ones that are used most are: –Date and Time.
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Structured Query Language Part I Chapter Three CIS 218.
Introduction to Structured Query Language (SQL)
Databases Tutorial 2 Further Select Statements. Objectives for Week Data types Sort retrieved data Formatting output.
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
INFORMATION TECHNOLOGY IN BUSINESS AND SOCIETY SESSION 16 – SQL SEAN J. TAYLOR.
Rationale Aspiring Database Developers should be able to efficiently query and maintain databases. This module will help students learn the Structured.
ASP.NET Programming with C# and SQL Server First Edition
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 3 Single-Table Queries
SQL – Part II Yong Choi School of Business CSU, Bakersfield.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Applications – Microsoft Access Lesson 4 Working with Queries 36 Slides in Presentation.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Structured Query Language SQL Unit 2 An Introduction to Organizing and Retrieving Data with SQL.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
N5 Databases Notes Information Systems Design & Development: Structures and links.
Fundamentals of DBMS Notes-1.
SQL Query Getting to the data ……..
Presented by: Teererai Marange
In this session, you will learn to:
Relational Database Design
Writing Basic SQL SELECT Statements
Aggregating Data Using Group Functions
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
SQL FUNDAMENTALS CDSE Days 2018.
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Exploring Microsoft Office Access 2007
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Yong Choi School of Business CSU, Bakersfield
Database systems Lecture 3 – SQL + CRUD
Yong Choi School of Business CSU, Bakersfield
COP 2700 – Data Structures - SQL
M1G Introduction to Database Development
Reporting Aggregated Data Using the Group Functions
Contents Preface I Introduction Lesson Objectives I-2
CSC 453 Database Systems Lecture
Section 4 - Sorting/Functions
Reporting Aggregated Data Using the Group Functions
Reporting Aggregated Data Using the Group Functions
分组函数 Schedule: Timing Topic 35 minutes Lecture 40 minutes Practice
Shelly Cashman: Microsoft Access 2016
Aggregating Data Using Group Functions
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

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

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

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!!)

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

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

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}

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.

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 https://msdn.microsoft.com/en-us/library/ms177516.aspx With database columns SELECT Part_Num, Description, On_Hand * Price AS Inventory_Value FROM Part

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: http://www.teratrax.com/sql-server-data-types-ranges/

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

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

Priority Database

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

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.

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

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)

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

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.

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)

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.

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

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)??

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)

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.

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

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

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

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

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

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

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

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')

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')

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?

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

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