Yong Choi School of Business CSU, Bakersfield

Slides:



Advertisements
Similar presentations
Multiple Table Queries
Advertisements

Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
Greg Riccardi Florida State University. Using SQL to Manipulate Database Content and Structure How to create queries in SQL –Simple select statements.
Concepts of Database Management Sixth Edition
Concepts of Database Management Seventh Edition
Example 18 SELECT count(*) FROM Part WHERE Class="HW";
Structure Query Language (SQL) COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
Chapter 8 Embedded SQL.
Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:
SQL – Part II Yong Choi School of Business CSU, Bakersfield.
Concepts of Database Management, 4th Edition, Pratt & Adamski
SQL – Part II Yong Choi School of Business CSU, Bakersfield.
A Guide to SQL, Seventh Edition. Objectives Understand the concepts and terminology associated with relational databases Create and run SQL commands in.
Concepts of Database Management Sixth Edition
SQL SQL stands for Structured Query Language SQL allows you to access a database SQL is an ANSI standard computer language SQL can execute queries against.
Introduction to Structured Query Language (SQL)
Concepts of Database Management Sixth Edition
SQL (Standard Query Language) Yong Choi School of Business CSU, Bakersfield.
Chapter 3: SQL – Part I Yong Choi School of Business CSU, Bakersfield.
Part ( PartNum, Description, OnHand, Class, Warehouse, Price,
SQL – Part I Yong Choi School of Business CSU, Bakersfield.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Introduction to SQL J.-S. Chou Assistant Professor.
Introduction to SQL Yong Choi School of Business CSU, Bakersfield.
A Guide to SQL, Eighth Edition Chapter Two Database Design Fundamentals.
Concepts of Database Management, Fifth Edition Chapter 4: The Relational Model 3: Advanced Topics.
Chapter 4 The Relational Model 3: Advanced Topics Concepts of Database Management Seventh Edition.
SQL – Part II Yong Choi School of Business CSU, Bakersfield.
Concepts of Database Management Seventh Edition Chapter 4 Keys and Relationship.
1 A Guide to MySQL 2 Database Design Fundamentals.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
SQL – Part I Yong Choi School of Business CSU, Bakersfield.
Chapter 6 SQL: Data Manipulation (Advanced Commands) Pearson Education © 2009.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Concepts of Database Management Seventh Edition
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
SQL – Part I Yong Choi School of Business CSU, Bakersfield.
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: 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.
DO NOT COPY --CONFIDENTIAL Homework 5 Partial Key Star Diagrams & Data Warehouse Design BCIS 4660 Dr. Nick Evangelopoulos Spring 2012.
Concepts of Database Management Seventh Edition Chapter 4 Keys and Relationship.
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.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Southern Methodist University CSE CSE 2337 Introduction to Data Management Chapter 5 Part II.
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Fundamentals of DBMS Notes-1.
A Guide to SQL, Eighth Edition
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
CS580 Advanced Database Topics
A Guide to SQL, Eighth Edition
Structured Query Language (SQL) William Klingelsmith
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Normalization – Part II
Example 2 SELECT Customernum, CustomerName, Balance FROM Customer;
Yong Choi School of Business CSU, Bakersfield
CMPT 354: Database System I
Yong Choi School of Business CSU, Bakersfield
Chapter 14 Normalization Pearson Education © 2009.
Presentation transcript:

Yong Choi School of Business CSU, Bakersfield SQL – Part II Yong Choi School of Business CSU, Bakersfield

SQL Examples – Aggregate Functions Example 18: Save as example 18 How many parts (count number of records) are in item class HW? Use of “count” command Count all records: count(*) No idea? Try to figure out manually!

SQL Query to Count Records Example 18 SQL Query to Count Records

Example 18 SELECT count(*) FROM Part WHERE Class=_____________;

SQL Examples – Aggregate Functions Example 19: Save as example 19 Find the number of customers and the total of their balances.

SQL Query to Count Records and Calculate a Total Example 19 SQL Query to Count Records and Calculate a Total

Example 19 SELECT count(*), Sum(____________) FROM Customer;

SQL Examples – Aggregate Functions Example 20: Save as example 20 Find the total number of customers and the total of their balances. Change the column names for the number of customers and the total of their balances to CustomerCount and BalanceTotal. Assign column name using “AS” command

SQL Query to Perform Calculations and Rename Fields Example 20 SQL Query to Perform Calculations and Rename Fields

Example 20 SELECT count(*) AS ___________, Sum(Balance) AS _____________ FROM Customer;

SQL Examples – Nested Query A query inside another query A inside query (sub-query) is evaluated first. It is common to enclose sub-query in parentheses for readability!! Example 21: Save as example 21 List the order number for each order from the order line table for a part located in warehouse 3. That is, we are looking for list of OrderNum that is associated with warehouse 3. No idea? Try to figure out manually!

SQL Query with Subquery Example 21 SQL Query with Subquery

Example 21 SELECT OrderNum FROM OrderLine WHERE PartNum IN

SQL Examples - Grouping Use GROUP BY clause ONLY grouping, NOT sorting (usually associated with ORDER BY clause) Example 22: Save as example 22 For each sales rep, list the rep number, the number of customers assigned to each rep, and the average balance of the rep’s customers. Rename the count of the number of customers and the average of the balances to NumOfCustomers and AverageBalance

# of customers are grouped by each sales rep # Example 22 SQL Query to Group Records # of customers are grouped by each sales rep #

Example 22 SELECT RepNum, Count(_____) AS NumOfCustomer, Avg(Balance) AS AvgBalance FROM Customer GROUP BY ____________;

SQL Examples – Grouping (con’t) Example 23: Save as example 23 For each sales rep with fewer than four customers, list the rep number, the number of customers assigned to the rep, and the average balance of the rep’s customers. Rename the count of the number of customers and the average of the balances to NumOfCustomers and AverageBalance. Use of “Having” command. Count, Rep. with < 4 customers (group)

SQL Query to Restrict Groups Example 23 SQL Query to Restrict Groups # of customers are grouped by each sales rep # Apply the condition to the group

Example 23 where to put “Having” command? SELECT RepNum, count(*) AS NumCustomer, Avg(Balance) AS AverageBalance FROM Customer GROUP BY RepNum;

SQL Examples – Grouping (con’t) Use of Where and Having clauses together “Where” command must be stated first Example 23-1: Save as example 23-1 Exactly same as example 23. Except, only groups with fewer than three records and customers with credit limit of less than $10,000 must be included.

Example 23-1 SQL Query with ‘WHERE’ and ‘HAVING’ Clauses

Example 23-1 Where to put “Where” command? SELECT RepNum, count(*) AS NumCustomer, Avg(Balance) AS AverageBalance FROM Customer GROUP BY RepNum HAVING Count(*)<3;

Exercise Question 8 from chapter 6 How many students are enrolled on Database and Networking? (Hint: use SectionNo for each class so you can determine the answer from the semester of 2008)? Which courses were taught in the first semester of 2008 (I-2008) but not in the second semester of 2008 (II-2008)? (Note: There is no indication of the second semester of 2008 (II-2008))?

Matching Field Try below SQLs using Matching_DB on the class website To identify missing “RepNum,” make sure to review each table first! SQL 1 SELECT Customer.RepNum, CustomerName, Rep.RepNum, LastName, FirstName FROM Customer, Rep; SQL 2 FROM Customer, Rep Where Customer.RepNum=Rep.RepNum;

Inner Join Example For each customer who placed an order, what is the customer’s name and order number? The best way to find out match customers with their orders is Including CustumerID from both tables

Different Type of SQL Joins (INNER) JOIN: Returns records that have matching values in both tables LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table FULL (OUTER) JOIN: Return all records when there is a match in either left or right table Also, review SQL Joins in the textbook chapter 7

SQL Examples – Joining Tables Example 24: Save as example 24 List the number and name of each customer together with the number, last name, and first name of the sales rep who represents the customer. If a customer does not have a Rep., then he/she must not be included. That is, look for matching RepNum from both tables

SQL Query to Join Tables Example 24 SQL Query to Join Tables

Example 24 SELECT CustomerNum, CustomerName, Rep.RepNum, LastName, FirstName FROM Customer, Rep Where _______.RepNum =_________.RepNum; FROM Customer INNER JOIN [Rep] ON ________.RepNum=________.RepNum;

SQL Examples – Joining Tables (con’t) Use of multiple tables with a compound condition Example 25: Save as example 25 List the number and name of each customer whose credit limit is $10,000 together with number, last name, and first name of the sales rep who represents the customer.

Query to Restrict Records in Join Example 25 Query to Restrict Records in Join

Example 25 SELECT CustomerNum, CustomerName, Rep.RepNum, LastName, FirstName FROM Customer, Rep WHERE Rep.RepNum=Customer.RepNum AND _______________________;

SQL Examples – Joining Tables (con’t) Example 26: Save as example For every order, list the order number, order date, customer number, and customer name. In addition, for each order line within the order, list the part number, description, number ordered, and quoted price. Make sure that everything is matched. In other words, any “unmatched” records must not be included.

Query to Join Multiple Tables Example 26 Query to Join Multiple Tables

Example 26 SELECT Orders.OrderNum, Orderdate, Customer.CustomerNum, CustomerName, Part.PartNum, Description, NumOrdered, QuotedPrice FROM Orders, Customer, OrderLine, Part WHERE Customer.CustomerNum=Orders.CustomerNum AND Orders.OrderNum=OrderLine.OrderNum AND OrderLine.PartNum=Part.PartNum;

SQL Examples – Union Example 27: Save as example 27 The union of two tables is a table containing all rows that are in either the first table, the second table, or both tables. Two tables involved in union must have same structure. Example 27: Save as example 27 List the number and name of all customers that are either represented by sales rep 35 OR that currently have orders on file, OR both. Any “unmatched” records must not be included.

Example 27 SQL Query to Perform Union Red: Currently have orders on file Blue: Represented by sales rep 35 Green: Both

Example 27 SELECT CustomerNum, CustomerName FROM Customer WHERE RepNum='35' UNION SELECT Customer.CustomerNum, CustomerName FROM Customer, Orders WHERE Customer.CustomerNum=Orders.CustomerNum;

Three Basic Functions by SQL And Their Basic SQL Commands Data definition (last topic) through the use of CREATE Data manipulation (next topic) through INSERT, UPDATE, and DELETE Data querying (we are done with this) through the use of SELECT AND MANY OTHERS, which is the basis for all SQL queries.

SQL - Data Manipulation Possible with Access UPDATE INSERT DELETE Only possible with enterprise level DBMS COMMIT ROLLBACK

SQL - Data Manipulation (con’t) UPDATE command makes data entry corrections UPDATE Project SET PrjtLocat = 'Bellaire', DeptNum = 5 WHERE PrjtNum = 10;   UPDATE Employee SET Salary = Salary * 1.1 WHERE Branch = 'Lincoln';

SQL - Data Manipulation (con’t) INSERT command add new data to a table INSERT INTO Employee (SSN, LastName, FirstName) VALUES ('Richard', 'Marini', '43433'); DELETE command removes table row DELETE FROM Employee WHERE LastName = 'Brown';

SQL - Data Manipulation (con’t) COMMIT command store data on the secondary memory permanently ROLLBACK command restores database back to previous condition if COMMIT hasn’t been used

SQL Examples - Data Manipulation Example 28: Save as example 28 Update the street address of customer 524 to 1445 Rivard First, review the current street address of customer 524 (838 Ridgeland)

Example 28 UPDATE Customer SET Street = '1445 Rivard' WHERE CustomerNum='524';

SQL Examples - Data Manipulation Example 29: Save as example 29 Add a new sales rep to the Rep table. Her number is 16, her name is Sharon Rands, and her address is 826 Raymond, Altonville, FL 32543. She has not yet earned any commission, but her commission rate is 5%(0.05). First, review the “Rep” table

Example 29 INSERT INTO Rep VALUES ('16', 'Rands', 'Shron', '826 Raymond', 'Altonville', 'FL', '32543', 0, 0.05);

SQL Examples - Data Manipulation Example 30: Save as example 30 Delete any row in the Orderline table in which the part number is BV06 First, review the part number BV06 (OrderNum21617)

Example 30 DELETE * FROM OrderLine WHERE PartNum='BV06';

SQL Examples – Creating a New Table Using a Existing Table Example 31: save as example 31 Create a new table named SmallCust, consisting of all fields from the Customer table and those rows in which the credit limit is less than or equal to $7,500. SELECT INTO Name of table to create FROM WHERE

SQL Query to Create New Table Example 31 SQL Query to Create New Table

Example 31 SELECT * INTO SmallCust FROM Customer WHERE CreditLimit<=7500;

SQL - Data Definition I Create a database structure to hold all the database tables; MS Access ONLY can create tables Usually, only a DBA can create a new database structure SQL syntax for creating a database structure: CREATE SCHEMA AUTHORIZATION <creator>; Example: CREATE SCHEMA AUTHORIZATION JONES;

SQL - Data Definition II Specify a new relation by giving it a name and specifying each of its attributes. Each attribute is given a name, a data type to specify its values, and some constraints on the attribute. Syntax: CREATE TABLE <table name>;

SQL Example – Data Definition Example 32: Save as example 32 Create a table call “CSUB” that contains following fields: EmpID Number (vs. Number(9) or Num(9)) LastName Char(20) FirstName Char(20) Street Char(30) City Char(20) State Char(2) Phone Number

Example 32 (con’t) Using Access Insert following values: Create table CSUB (EmpID Number, LastName Char(20), FirstName Char(20), Street Char(30), City Char(20), State Char(2), Phone Number); Insert following values: EmpID: 123456789 LastName: your lastname FirstName: your firstname Street: 9001 Stockdale Hgwy City: Bakersfield State: CA Phone: 6616656691

Example 32 INSERT INTO CSUB VALUES ('987654321', 'Choi', 'Yong', '9001 Stockdale', 'Bakersfield', 'CA', '123456789');

Using Oracle CREATE TABLE EMPLOYEE (FNAME VARCHAR(15) NOT NULL, LNAME VARCHAR(15) NOT NULL, SSN CHAR(9) NOT NULL, BDATE DATE, SEX CHAR, SALARY DECIMAL(10,2), SUPERSSN CHAR(9), DEPTNO INT NOT NULL, PRIMARY KEY (SSN), FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(SSN), FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER) );