IMS 4212: Intro to Multi-Table SELECT Statements 1 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table SELECT Statements—Topics.

Slides:



Advertisements
Similar presentations
Sometimes you need to use data from more than one table. In example1, the report displays data from two separate tables. Employee IDs exist in the EMPLOYEES.
Advertisements

© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Chapter 4 Joining Multiple Tables
Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Writing Basic SQL SELECT Statements. Capabilities of SQL SELECT Statements A SELECT statement retrieves information from the database. Using a SELECT.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
Populating and Querying tables Insert and mostly View (DML)
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.
Northwind Sample database (also supplied with MS Access)
Databases Tutorial 2 Further Select Statements. Objectives for Week Data types Sort retrieved data Formatting output.
Tutorial 5 Multi-table queries. Tutorial 5 objectives Displaying Data from Multiple Tables –[ ]Write SELECT statements to access data from more than one.
Advanced SQL SMSU Computer Services Short Course.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
Displaying Data from Multiple Tables. Obtaining Data from Multiple Tables Sometimes you need to use data from more than one table. In the example, the.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Database Programming Sections 5– GROUP BY, HAVING clauses, Rollup & Cube Operations, Grouping Set, Set Operations 11/2/10.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
SQL in Action Amit Bhawnani & Nimesh Shah. Basic Structure SQL is based on set and relational operations with certain modifications and enhancements A.
IMS 6217: Primary Key Reference 1 Dr. Lawrence West, MIS Dept., University of Central Florida Primary Keys Uniqueness of Table Rows Identifier.
IMS 6217: Relationships 1 Dr. Lawrence West, MIS Dept., University of Central Florida Database Design--Topics DB Design Steps Identify.
Chapter 9 Joining Data from Multiple Tables
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
ISM 4212 Lab Creating DB Tables 02 copyright Lars Paul Linden 2007.
IMS 4212: Normalization 1 Dr. Lawrence West, Management Dept., University of Central Florida Normalization—Topics Functional Dependency.
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to SQL—Topics Introduction to.
IMS 4212: Introduction to Data Modeling 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to Data Modeling—Topics.
JOI/1 Data Manipulation - Joins Objectives –To learn how to join several tables together to produce output Contents –Extending a Select to retrieve data.
IMS 4212: Data Modeling—Attributes 1 Dr. Lawrence West, Management Dept., University of Central Florida Attributes and Domains Nonkey.
SQL- DQL (Oracle Version). 2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list]
Lab 4: Displaying Data from Multiple Tables CISB224 02A, 02B Semester I, 2009/2010 College of Information Technology, Universiti Tenaga Nasional 1.
IMS 4212: Data Modeling—More Relationships 1 Dr. Lawrence West, Management Dept., University of Central Florida Data Modeling—Topics.
Relational Databases.  In week 1 we looked at the concept of a key, the primary key is a column/attribute that uniquely identifies the rest of the data.
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
IST 318 – DB Administration Data Retrieval Using SELECT statements.
Connecting (relating) Data Tables to get Custom Records (Queries) Database Basics.
Class11 Introduction to relational databases and MySQL MIS 3501, Fall 2015 Brad Greenwood, PhD MBA Department of MIS Fox School of Business Temple University.
IMS 4212: Database Implementation 1 Dr. Lawrence West, Management Dept., University of Central Florida Physical Database Implementation—Topics.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
IMS 3253: Controls 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Check Boxes Radio Buttons Date Time Picker Masked.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
IMS 4212: Data Modeling—Business Rules 1 Dr. Lawrence West, Management Dept., University of Central Florida Business Rules—Topics Intro.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
IMS 6217: Database Design & Entities 1 Dr. Lawrence West, MIS Dept., University of Central Florida Database Design--Topics DB Design.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
IMS 4212: Indexes (Indices) 1 Dr. Lawrence West, Management Dept., University of Central Florida Indexes—Topics Reasons for concern Data.
IMS 4212: Normalization 1 Dr. Lawrence West, Management Dept., University of Central Florida Normalization—Topics Functional Dependency.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
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.
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
IFS180 Intro. to Data Management Chapter 10 - Unions.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Microsoft Office Access 2010 Lab 3
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Using the Set Operators
Writing Basic SQL SELECT Statements
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Introduction to relational databases and MySQL
Aggregations Various Aggregation Functions GROUP BY HAVING.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Writing Basic SQL SELECT Statements
Contents Preface I Introduction Lesson Objectives I-2
Class11 Introduction to relational databases and MySQL
Lab 4: Displaying Data from Multiple Tables
Advanced Joins IN ( ) Expression Subqueries with IN ( ) Expression
Using the Set Operators
Displaying Data from Multiple Tables
Presentation transcript:

IMS 4212: Intro to Multi-Table SELECT Statements 1 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table SELECT Statements—Topics Multi-Table SELECT Statements Joining Tables in the WHERE Clause –How Multi-Table Queries are Executed –Tables to Include in the FROM Clause –Style in WHERE Clause Joins Using INNER JOIN to join tables Table Aliases Self (Unary) Joins Composite Primary/Foreign Key Joins

IMS 4212: Intro to Multi-Table SELECT Statements 2 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table SELECT Statements The rules of normalization in database design result in data being dispersed into a multitude of tables Data in multiple tables must be routinely queried together to support business needs –Reassemble the data pertaining to a single event, person, etc., when that data is dispersed –Perform research (business intelligence) SQL provides different mechanisms to temporarily join data from multiple tables to produce a result set.

IMS 4212: Intro to Multi-Table SELECT Statements 3 Dr. Lawrence West, MIS Dept., University of Central Florida Joining Tables Two techniques for joining tables require that the primary key values in one table equal the foreign key values in the related table. Only combinations of records where this is true are included in the result set

IMS 4212: Intro to Multi-Table SELECT Statements 4 Dr. Lawrence West, MIS Dept., University of Central Florida Joining Tables in the WHERE Clause Set PK = FK in the WHERE clause 1.List all output columns from any table in the query 2.List all tables needed in the query 3.Set PK = FK for all related tables in the query SELECT Categories.CategoryID, CategoryName, ProductID, ProductName FROM Categories, Products WHERE Categories.CategoryID = Products.CategoryID ORDER BY CategoryID, ProductID 1 2 3

IMS 4212: Intro to Multi-Table SELECT Statements 5 Dr. Lawrence West, MIS Dept., University of Central Florida Joining Tables in the WHERE Clause (cont.) If a column name exists in more than one table used in the query it must be fully qualified in the query TableName.ColumnName Any column can be written this way (and some developers will always qualify all columns, even in a single-table query) SELECT Categories.CategoryID, CategoryName, ProductID, ProductName FROM Categories, Products WHERE Categories.CategoryID = Products.CategoryID ORDER BY CategoryID, ProductID

IMS 4212: Intro to Multi-Table SELECT Statements 6 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table Logic The default (unenhanced) behavior of a multi-table query is to consider every combination of all rows in all included tables When the WHERE clause is true for all criteria the combination of rows is added to the result set

IMS 4212: Intro to Multi-Table SELECT Statements 7 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table Logic (cont.) Run all four of these queries at once SELECT COUNT(*) AS CountOfCategories FROM Categories SELECT COUNT(*) AS CountOfProducts FROM Products SELECT COUNT(*) AS CountOfJoin FROM Categories, Products WHERE Categories.CategoryID = Products.CategoryID SELECT COUNT(*) AS CountOfUnJoined FROM Categories, Products COUNT() is an aggregate function that returns the number of records in the result set What do these results mean?

IMS 4212: Intro to Multi-Table SELECT Statements 8 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table Logic (cont.) Additional row-limiting WHERE expressions are also allowed SELECT COUNT(*) AS CountOfJoinBelow3 FROM Categories, Products WHERE Categories.CategoryID = Products.CategoryID AND Categories.CategoryID < 3 SELECT Categories.CategoryID, CategoryName, ProductID, ProductName FROM Categories, Products WHERE Categories.CategoryID = Products.CategoryID AND Categories.CategoryID < 3 Try changing this to Products.CategoryID

IMS 4212: Intro to Multi-Table SELECT Statements 9 Dr. Lawrence West, MIS Dept., University of Central Florida Exercises Query the order date and contact information for the customer that placed Order # List the product name and Supplier contact information for all products where the units on hand is less than the reorder point (What would be the most useful query to run in this case? Look at the Products table structure carefully.) List the customer contact information for all customers who have purchased Northwoods Cranberry Sauce in 1997 Note: The Order Details table must be written with square brackets→ [Order Details]

IMS 4212: Intro to Multi-Table SELECT Statements 10 Dr. Lawrence West, MIS Dept., University of Central Florida Tables in the FROM Clause A table must be included in the FROM clause if –It contributes columns specified in the SELECT clause –It has columns tested in the WHERE clause –It is needed to connect any tables required for the first two reasons above Only list a table once even if it is used in the SELECT and WHERE clauses Set all PK = FK criteria for all relationships between all tables in the FROM clause

IMS 4212: Intro to Multi-Table SELECT Statements 11 Dr. Lawrence West, MIS Dept., University of Central Florida Style in WHERE Clause Joins When using the WHERE clause join in conjunction with other WHERE clause expressions –Put all joining WHERE clause expressions together –Put all row limiting WHERE clause expressions together I don't care which you put first … … just don't intermix them

IMS 4212: Intro to Multi-Table SELECT Statements 12 Dr. Lawrence West, MIS Dept., University of Central Florida Joining Tables using INNER JOIN This query achieves results identical to the query on Slide #4 SELECT Categories.CategoryID, CategoryName, ProductID, ProductName FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID ORDER BY Categories.CategoryID, ProductID

IMS 4212: Intro to Multi-Table SELECT Statements 13 Dr. Lawrence West, MIS Dept., University of Central Florida Joining Tables using INNER JOIN (cont.) As many tables as necessary can be joined using this syntax The INNER JOIN syntax executes more efficiently than the WHERE clause joins SELECT Categories.CategoryID, CategoryName, ProductID, ProductName, CompanyName FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID ORDER BY Categories.CategoryID, ProductID

IMS 4212: Intro to Multi-Table SELECT Statements 14 Dr. Lawrence West, MIS Dept., University of Central Florida Exercises List all of the product names from German suppliers List the order date and the name of the shipping company used for all orders placed in May of 1998 List the names and order dates of all products that employee Robert King has sold

IMS 4212: Intro to Multi-Table SELECT Statements 15 Dr. Lawrence West, MIS Dept., University of Central Florida Table Aliases Tables can be aliased in a query and then referenced by their alias name instead of the whole table name SELECT Cat.CategoryID, CategoryName, ProductID, ProductName, CompanyName FROM Categories AS Cat INNER JOIN Products AS Prod ON Cat.CategoryID = Prod.CategoryID INNER JOIN Suppliers AS Sup ON Prod.SupplierID = Sup.SupplierID ORDER BY Cat.CategoryID, ProductID The AS is optional Categories AS Cat and Categories Cat are equivalent

IMS 4212: Intro to Multi-Table SELECT Statements 16 Dr. Lawrence West, MIS Dept., University of Central Florida Table Aliases (cont.) Many computer science professionals will alias every table with single character aliases I do not like single-character aliases as they interfere with readability, especially in lengthy SQL –I have reviewed 64-page SQL statements with tables aliased in the first five pages and then referenced again twenty and forty pages later I prefer that you not use aliases without a good reason

IMS 4212: Intro to Multi-Table SELECT Statements 17 Dr. Lawrence West, MIS Dept., University of Central Florida Self Joins Look at the Northwind Employees table ReportsTo is a foreign key in a unary relationship between Employees In any record, ReportsTo contains the EmployeeID for the employee's supervisor

IMS 4212: Intro to Multi-Table SELECT Statements 18 Dr. Lawrence West, MIS Dept., University of Central Florida Self Joins (cont.) Write the SQL to retrieve the name of Robert King's supervisor Use different aliases to create two pointers into the same table Now write the SQL to retrieve the names of the employees that Andrew Fuller supervises SELECT Sup.FirstName, Sup.LastName FROM Employees Emp INNER JOIN Employees Sup ON Emp.ReportsTo = Sup.EmployeeID WHERE Emp.LastName = 'King' AND Emp.FirstName = 'Robert' Alias names should give a hint to the role being filled

IMS 4212: Intro to Multi-Table SELECT Statements 19 Dr. Lawrence West, MIS Dept., University of Central Florida Composite Primary/Foreign Keys Just use AND expressions to join tables on composite primary & foreign keys SELECT … FROM Course INNER JOIN Section ON Course.DeptCode = Section.DeptCode AND Course.CourseNumber = Section.CourseNumber WHERE … SELECT … FROM Course, Section WHERE Course.DeptCode = Section.DeptCode AND Course.CourseNumber = SectionCourseNumber —OR—

IMS 4212: Intro to Multi-Table SELECT Statements 20 Dr. Lawrence West, MIS Dept., University of Central Florida Function of the Day The DateAdd( ) function adds a number of date/time increments to a datetime value to produce a new datetime value that many increments in the future or past Format: DATEADD(datepart, number, date) Examples –DATEADD(dd, 3, '5/20/2008') gives 5/23/2008 –DATEADD(mm, -1, GETDATE()) gives the day one month prior to the current date Hint: Experiment with the use of the mm increment on dates such as January 31 st, March 31 st, etc.

IMS 4212: Intro to Multi-Table SELECT Statements 21 Dr. Lawrence West, MIS Dept., University of Central Florida Function of the Day (cont.) See the list of allowable date part specifications on p. 601 in Vieira –This list works in DateDiff, DatePart, and DateAdd Write a query to determine the date five days in the future of every OrderDate Write a query to determine the date on which each employee will reach their 10 th year of employment with the company.