Chapter 3 Query Formulation with SQL. Outline Background Getting started Joining tables Summarizing tables Reasoning tools Advanced problems Data manipulation.

Slides:



Advertisements
Similar presentations
© Abdou Illia MIS Spring 2014
Advertisements

Chapter 4 Joining Multiple Tables
Basic SQL Introduction Presented by: Madhuri Bhogadi.
Query Formulation with SQL
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Chapter 8 Normalization. © 2001 The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill/Irwin Outline Modification anomalies Functional dependencies.
Introduction to Structured Query Language (SQL)
McGraw-Hill/Irwin Copyright © 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Chapter 9 Advanced Query Formulation with SQL.
McGraw-Hill/Irwin Copyright © 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Chapter 6 Developing Data Models for Business Databases.
McGraw-Hill/Irwin Copyright © 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Chapter 7 Normalization of Relational Tables.
Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data
7-1 Normalization - Outline  Modification anomalies  Functional dependencies  Major normal forms  Practical concerns.
Introduction to Structured Query Language (SQL)
Chapter 9 Advanced Query Formulation with SQL. Outline Outer join problems Type I nested queries Type II nested queries and difference problems Nested.
McGraw-Hill/Irwin Copyright © 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Chapter 9 Supplemental Slides Type II Nested Query Demonstration.
Chapter 6 Developing Data Models for Business Databases.
McGraw-Hill/Irwin Copyright © 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 The Relational Data Model.
SQL Within PL / SQL Chapter 4. 2 SQL Within PL / SQL SQL Statements DML in PL / SQL Pseudocolums Transaction Control.
SQL - Part 2 Much of the material presented in these slides was developed by Dr. Ramon Lawrence at the University of Iowa.
Relational Database Management Systems. A set of programs to manage one or more databases Provides means for: Accessing the data Inserting, updating and.
Chapter 9 Joining Data from Multiple Tables
ITBIS373 Database Development
Lecture6:Data Manipulation in SQL, Simple SQL queries Prepared by L. Nouf Almujally Ref. Chapter5 Lecture6 1.
Chapter 7 Normalization. Outline Modification anomalies Functional dependencies Major normal forms Relationship independence Practical concerns.
Chapter 7 Normalization. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Modification anomalies Functional dependencies.
Copyright © 2011 by Michael V. Mannino All rights reserved. Database Design, Application Development, and Administration, 5 th Edition Chapter 3 The Relational.
Chapter 2 The Relational Data Model. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Relational model basics Integrity.
Chapter 14 Data and Database Administration. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Organizational context.
Using Special Operators (LIKE and IN)
Chapter 10 Application Development with Views. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Background Creating.
Chapter 3 Query Formulation with SQL. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Background Getting started.
Oracle 11g DATABASE DEVELOPMENT LAB1. Introduction  Oracle 11g Database:-  Oracle 11g database is designed for some features, which helps to the organizations.
Advanced Query Formulation with SQL. 9-2 Outline  Outer join problems  Type I nested queries  Type II nested queries and difference problems  Nested.
Chapter 9 Advanced Query Formulation with SQL. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Outer join problems.
9 Advanced Query Formulation with SQL (Chapter 9).
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BACS 287 Structured Query Language 1. BACS 287 Visual Basic Table Access Visual Basic provides 2 mechanisms to access data in tables: – Record-at-a-time.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Lecture No 14 Functional Dependencies & Normalization ( III ) Mar 04 th 2011 Database Systems.
1 DBS201: Introduction to Structure Query Language (SQL) Lecture 1.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
McGraw-Hill/Irwin Copyright © 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Chapter 4 Query Formulation with SQL.
SQL – Simple Queries and JOIN MGMT 360 Database Management.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. What is a View? Derived table Behaves like a base table (virtual) Stored.
Database UpdatestMyn1 Database Updates SQL is a complete data manipulation language that can be used for modifying the data in the database as well as.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
Retrieving Data in PL/SQL. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Recognize the SQL statements that can.
1 Welcome to the World of Databases! Database technology: crucial to the operation and management of modern organisations Major transformation in computing.
McGraw-Hill/Irwin Copyright © 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Chapter 10 Application Development with Views.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
Slide 1Chapter 9: Advanced Query Formulation with SQL Database Design, Application Development, and Administration, 5 th Edition Copyright © 2011 by Michael.
 CONACT UC:  Magnific training   
Chapter 2 The Relational Data Model. Outline Relational model basics Integrity rules Rules about referenced rows Relational Algebra.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL Query Getting to the data ……..
Application Development with Views
The Relational Data Model
Introduction to Database Management
Using Subqueries to Solve Queries
Developing Data Models – Conversion Rules
Query Formulation with SQL
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
CSC 453 Database Systems Lecture
Manipulating Data Lesson 3.
Presentation transcript:

Chapter 3 Query Formulation with SQL

Outline Background Getting started Joining tables Summarizing tables Reasoning tools Advanced problems Data manipulation statements

What is SQL? Structured Query Language Language for database definition, manipulation, and control International standard Standalone and embedded usage Intergalactic database speak

SQL Statements StatementChapter CREATE TABLE2 ALTER TABLE2 SELECT3, 9, 10 INSERT3, 10 UPDATE3, 10 DELETE3, 9, 10 CREATE VIEW10 CREATE TRIGGER11 GRANT, REVOKE14 CREATE ASSERTION14 COMMIT, ROLLBACK15

SELECT Statement Overview SELECT FROM WHERE GROUP BY HAVING ORDER BY Expression: combination of columns, constants, operators, and functions

University Database

First SELECT Examples Example 1 SELECT * FROM Faculty Example 2 (Access) SELECT * FROM Faculty WHERE FacSSN = ' ' Example 3 SELECT FacFirstName, FacLastName, FacSalary FROM Faculty Example 4 SELECT FacFirstName, FacLastName, FacSalary FROM Faculty WHERE FacSalary > AND FacRank = 'PROF'

Using Expressions Example 5 (Access) SELECT FacFirstName, FacLastName, FacCity, FacSalary*1.1 AS IncreasedSalary, FacHireDate FROM Faculty WHERE year(FacHireDate) > 1991 Example 5 (Oracle) SELECT FacFirstName, FacLastName, FacCity, FacSalary*1.1 AS IncreasedSalary, FacHireDate FROM Faculty WHERE to_number(to_char(FacHireDate, 'YYYY')) > 1991

Inexact Matching Match against a pattern: LIKE operator Use meta characters to specify patterns – Wildcard (* or %) – Any single character (? or _) Example 6 (Access) SELECT * FROM Offering WHERE CourseNo LIKE 'IS*' Example 6 (Oracle) SELECT * FROM Offering WHERE CourseNo LIKE 'IS%'

Using Dates Dates are numbers Date constants and functions are not standard Example 7 (Access) SELECT FacFirstName, FacLastName, FacHireDate FROM Faculty WHERE FacHireDate BETWEEN #1/1/1994# AND #12/31/1995# Example 7 (Oracle) SELECT FacFirstName, FacLastName, FacHireDate FROM Faculty WHERE FacHireDate BETWEEN '1-Jan-1994' AND '31-Dec-1995'

Other Single Table Examples Example 8: Testing for null values SELECT OfferNo, CourseNo FROM Offering WHERE FacSSN IS NULL AND OffTerm = 'SUMMER' AND OffYear = 2003 Example 9: Mixing AND and OR SELECT OfferNo, CourseNo, FacSSN FROM Offering WHERE (OffTerm = 'FALL' AND OffYear = 2002) OR (OffTerm = 'WINTER' AND OffYear = 2003)

Join Operator Most databases have many tables Combine tables using the join operator Specify matching condition –Can be any comparison but usually = –PK = FK most common join condition –Relationship diagram useful when combining tables

Join Example

Cross Product Style List tables in the FROM clause List join conditions in the WHERE clause Example 10 (Access) SELECT OfferNo, CourseNo, FacFirstName, FacLastName FROM Offering, Faculty WHERE OffTerm = 'FALL' AND OffYear = 2002 AND FacRank = 'ASST' AND CourseNo LIKE 'IS*' AND Faculty.FacSSN = Offering.FacSSN

Join Operator Style Use INNER JOIN and ON keywords FROM clause contains join operations Example 11 (Access) SELECT OfferNo, CourseNo, FacFirstName, FacLastName FROM Offering INNER JOIN Faculty ON Faculty.FacSSN = Offering.FacSSN WHERE OffTerm = 'FALL' AND OffYear = 2002 AND FacRank = 'ASST' AND CourseNo LIKE 'IS*'

Name Qualification Ambiguous column reference –More than one table in the query contains a column referenced in the query –Ambiguity determined by the query not the database Use column name alone if query is not ambiguous Qualify with table name if query is ambiguous

Summarizing Tables Row summaries important for decision-making tasks Row summary –Result contains statistical (aggregate) functions –Conditions involve statistical functions SQL keywords –Aggregate functions in the output list –GROUP BY: summary columns –HAVING: summary conditions

GROUP BY Examples Example 12: Grouping on a single column SELECT FacRank, AVG(FacSalary) AS AvgSalary FROM Faculty GROUP BY FacRank Example 13: Row and group conditions SELECT StdMajor, AVG(StdGPA) AS AvgGpa FROM Student WHERE StdClass IN ('JR', 'SR') GROUP BY StdMajor HAVING AVG(StdGPA) > 3.1

SQL Summarization Rules Columns in SELECT and GROUP BY –SELECT: non aggregate and aggregate columns –GROUP BY: list all non aggregate columns WHERE versus HAVING –Row conditions in WHERE –Group conditions in HAVING

Summarization and Joins Powerful combination List join conditions in the WHERE clause Example 14: List the number of students enrolled in each fall 2003 offering. SELECT Offering.OfferNo, COUNT(*) AS NumStudents FROM Enrollment, Offering WHERE Offering.OfferNo = Enrollment.OfferNo AND OffYear = 2003 GROUP BY Offering.OfferNo

Conceptual Evaluation Process

Conceptual Evaluation Lessons Row operations before group operations –FROM and WHERE before GROUP BY and HAVING –Check row operations first Grouping occurs only one time Use small sample tables

Conceptual Evaluation Problem Important practice Use the university database tables in Chapter 3 Example 15: List the number of offerings taught in 2003 by faculty rank and department. Exclude combinations of faculty rank and department with less than two offerings taught. SELECT FacRank, FacDept, COUNT(*) AS NumOfferings FROM Faculty, Offering WHERE Offering.FacSSN = Faculty.FacSSN AND OffYear = 2003 GROUP BY FacRank, FacDept HAVING COUNT(*) > 1

Query Formulation Process Problem Statemen t Database Representation Database Language Statement

Critical Questions What tables? –Columns in output –Conditions to test (including join conditions) How to combine the tables? –Usually join PK to FK –More complex ways to combine Individual rows or groups of rows? –Aggregate functions in output –Conditions with aggregate functions

Efficiency Considerations Little concern for efficiency Intelligent SQL compilers Correct and non redundant solution –No extra tables –No unnecessary grouping –Use HAVING for group conditions only

Advanced Problems Joining multiple tables Self joins Grouping after joining multiple tables Traditional set operators

Joining Three Tables Example 16: List Leonard Vince’s teaching schedule in fall For each course, list the offering number, course number, number of units, days, location, and time. SELECT OfferNo, Offering.CourseNo, OffDays, CrsUnits, OffLocation, OffTime FROM Faculty, Course, Offering WHERE Faculty.FacSSN = Offering.FacSSN AND Offering.CourseNo = Course.CourseNo AND OffYear = 2002 AND OffTerm = 'FALL' AND FacFirstName = 'Leonard' AND FacLastName = 'Vince'

Joining Four Tables Example 17: List Bob Norbert’s course schedule in spring For each course, list the offering number, course number, days, location, time, and faculty name. SELECT Offering.OfferNo, Offering.CourseNo, OffDays, OffLocation, OffTime, FacFirstName, FacLastName FROM Faculty, Offering, Enrollment, Student WHERE Offering.OfferNo = Enrollment.OfferNo AND Student.StdSSN = Enrollment.StdSSN AND Faculty.FacSSN = Offering.FacSSN AND OffYear = 2003 AND OffTerm = 'SPRING' AND StdFirstName = 'BOB' AND StdLastName = 'NORBERT'

Self-Join Join a table to itself Usually involve a self-referencing relationship Useful to find relationships among rows of the same table –Find subordinates within a preset number of levels –Find subordinates within any number of levels requires embedded SQL

Self-Join Example Example 18: List faculty members who have a higher salary than their supervisor. List the social security number, name, and salary of the faculty and supervisor. SELECT Subr.FacSSN, Subr.FacLastName, Subr.FacSalary, Supr.FacSSN, Supr.FacLastName, Supr.FacSalary FROM Faculty Subr, Faculty Supr WHERE Subr.FacSupervisor = Supr.FacSSN AND Subr.FacSalary > Supr.FacSalary

Multiple Joins Between Tables Example 19: List the names of faculty members and the course number for which the faculty member teaches the same course number as his or her supervisor in SELECT FacFirstName, FacLastName, O1.CourseNo FROM Faculty, Offering O1, Offering O2 WHERE Faculty.FacSSN = O1.FacSSN AND Faculty.FacSupervisor = O2.FacSSN AND O1.OffYear = 2003 AND O2.OffYear = 2000 AND O1.CourseNo = O2.CourseNo

Multiple Column Grouping Example 20: List the course number, the offering number, and the number of students enrolled. Only include courses offered in spring SELECT CourseNo, Enrollment.OfferNo, Count(*) AS NumStudents FROM Offering, Enrollment WHERE Offering.OfferNo = Enrollment.OfferNo AND OffYear = 2003 AND OffTerm = 'SPRING' GROUP BY Enrollment.OfferNo, CourseNo

Traditional Set Operators A UNION B A INTERSECT B A MINUS B

Union Compatibility Requirement for the traditional set operators Strong requirement –Same number of columns –Each corresponding column is compatible –Positional correspondence Apply to similar tables by removing columns first

SQL UNION Example Example 21: Retrieve basic data about all university people SELECT FacSSN AS SSN, FacFirstName AS FirstName, FacLastName AS LastName, FacCity AS City, FacState AS State FROM Faculty UNION SELECT StdSSN AS SSN, StdFirstName AS FirstName, StdLastName AS LastName, StdCity AS City, StdState AS State FROM Student

Oracle INTERSECT Example Example 22: Show teaching assistants, faculty who are students. Only show the common columns in the result. SELECT FacSSN AS SSN, FacFirstName AS FirstName, FacLastName AS LastName, FacCity AS City, FacState AS State FROM Faculty INTERSECT SELECT StdSSN AS SSN, StdFirstName AS FirstName, StdLastName AS LastName, StdCity AS City, StdState AS State FROM Student

Oracle MINUS Example Example 23: Show faculty who are not students (pure faculty). Only show the common columns in the result. SELECT FacSSN AS SSN, FacFirstName AS FirstName, FacLastName AS LastName, FacCity AS City, FacState AS State FROM Faculty MINUS SELECT StdSSN AS SSN, StdFirstName AS FirstName, StdLastName AS LastName, StdCity AS City, StdState AS State FROM Student

Data Manipulation Statements INSERT: adds one or more rows UPDATE: modifies one or more rows DELETE: removes one or more rows Use SELECT statement to INSERT multiple rows UPDATE and DELETE can use a WHERE clause Not as widely used as SELECT statement

INSERT Example Example 24: Insert a row into the Student table supplying values for all columns. INSERT INTO Student (StdSSN, StdFirstName, StdLastName, StdCity, StdState, StdZip, StdClass, StdMajor, StdGPA) VALUES (' ','JOE','STUDENT','SEATAC', 'WA',' ','FR','IS', 0.0)

UPDATE Example Example 25: Change the major and class of Homer Wells. UPDATE Student SET StdMajor = 'ACCT', StdClass = 'SO' WHERE StdFirstName = 'HOMER' AND StdLastName = 'WELLS'

DELETE Example Example 26: Delete all IS majors who are seniors. DELETE FROM Student WHERE StdMajor = 'IS' AND StdClass = 'SR'

Summary SQL is a broad language SELECT statement is complex Use problem solving guidelines Lots of practice to master query formulation and SQL