The join operation allows you to combine related rows of data found in two tables into a single result set.



Similar documents
Lab # 5. Retreiving Data from Multiple Tables. Eng. Alaa O Shama

Go Beyond VFP's SQL with SQL Server

Displaying Data from Multiple Tables

Introduction to SQL for Data Scientists

Where? Originating Table Employees Departments

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Displaying Data from Multiple Tables. Copyright 2006, Oracle. All rights reserved.

Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25)

PSU SQL: Introduction. SQL: Introduction. Relational Databases. Activity 1 Examining Tables and Diagrams

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Once the schema has been designed, it can be implemented in the RDBMS.

Excel 2003, MS Access 2003, FileMaker Pro 8. Which One Should I Use?

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Using SQL Queries in Crystal Reports

GET DATA FROM MULTIPLE TABLES QUESTIONS

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Appendix A Practices and Solutions

Lecture 25: Database Notes

Web Programming Step by Step

Microsoft Access Lesson 5: Structured Query Language (SQL)

Microsoft Access 3: Understanding and Creating Queries

Information Systems SQL. Nikolaj Popov

Relational Database: Additional Operations on Relations; SQL

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query

Essentials of SQL. Essential SQL 11/06/2010. NWeHealth, The University of Manchester

Performance Implications of Various Cursor Types in Microsoft SQL Server. By: Edward Whalen Performance Tuning Corporation

A basic create statement for a simple student table would look like the following.

Chapter 1 Overview of the SQL Procedure

SQL SELECT Query: Intermediate

In this Lecture SQL SELECT. Example Tables. SQL SELECT Overview. WHERE Clauses. DISTINCT and ALL SQL SELECT. For more information

Performing Queries Using PROC SQL (1)

Define terms Write single and multiple table SQL queries Write noncorrelated and correlated subqueries Define and use three types of joins

Talking to Databases: SQL for Designers

SQL Programming. Student Workbook

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

CHAPTER 12. SQL Joins. Exam Objectives

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

Using AND in a Query: Step 1: Open Query Design

A Brief Introduction to MySQL

WRITING EFFICIENT SQL. By Selene Bainum

Advanced Query for Query Developers

CSE 530A Database Management Systems. Introduction. Washington University Fall 2013

LAB 1: Getting started with WebMatrix. Introduction. Creating a new database. M1G505190: Introduction to Database Development

1. SELECT DISTINCT f.fname FROM Faculty f, Class c WHERE f.fid = c.fid AND c.room = LWSN1106

SQL Server. 1. What is RDBMS?

Managing Your Class. Managing Users

ing a large amount of recipients

Joining Tables in Access

CS 2316 Data Manipulation for Engineers

David M. Kroenke and David J. Auer Database Processing 11 th Edition Fundamentals, Design, and Implementation. Chapter Objectives

Learning MySQL! Angola Africa SELECT name, gdp/population FROM world WHERE area > !

Database Query 1: SQL Basics

Financial Reporting Using Microsoft Excel. Presented By: Jim Lee

Introducing Microsoft SQL Server 2012 Getting Started with SQL Server Management Studio

ICAB4136B Use structured query language to create database structures and manipulate data

Structured Query Language. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics

Outline. SAS-seminar Proc SQL, the pass-through facility. What is SQL? What is a database? What is Proc SQL? What is SQL and what is a database

Query Builder. The New JMP 12 Tool for Getting Your SQL Data Into JMP WHITE PAPER. By Eric Hill, Software Developer, JMP

Using SQL Queries to Insert, Update, Delete, and View Data: Joining Multiple Tables. Lesson C Objectives. Joining Multiple Tables

Creating Reports Crystal Clear

Introduction to Querying & Reporting with SQL Server

Microsoft Access 2007 Module 1

Oracle Database: SQL and PL/SQL Fundamentals NEW

Understanding the Database Design Process

DbSchema Tutorial with Introduction in SQL Databases

Database CIS 340. lab#6. I.Arwa Najdi

General User/Technical Guide for Microsoft Access

INTRODUCTION TO JOINS IN TABLEAU

VBScript Database Tutorial Part 1

What does student success mean to you?

SUBQUERIES AND VIEWS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6

Querying Microsoft SQL Server 2012

Course 10774A: Querying Microsoft SQL Server 2012 Length: 5 Days Published: May 25, 2012 Language(s): English Audience(s): IT Professionals

Oracle Database: SQL and PL/SQL Fundamentals

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

Course 10774A: Querying Microsoft SQL Server 2012

Course ID#: W 35 Hrs. Course Content

Two new DB2 Web Query options expand Microsoft integration As printed in the September 2009 edition of the IBM Systems Magazine

SQL Server Table Design - Best Practices

Querying Microsoft SQL Server 20461C; 5 days

DIPLOMA IN WEBDEVELOPMENT

Admin Guide Product version: Product date: November, Technical Administration Guide. General

Answers to the Try It Yourself Sections

HRMS Reporting Tool Class

CS251: Fundamentals of Database Systems 1. CS251: Fundamentals of Database Systems. Database Design Project. Trina VanderLouw

Graphing Parabolas With Microsoft Excel

Improving SQL Server Performance

Oracle Database: SQL and PL/SQL Fundamentals

Sample- for evaluation only. Introductory Access. TeachUcomp, Inc. A Presentation of TeachUcomp Incorporated. Copyright TeachUcomp, Inc.

Oracle SQL. Course Summary. Duration. Objectives

Handling Exceptions. Copyright 2008, Oracle. All rights reserved.

CS2Bh: Current Technologies. Introduction to XML and Relational Databases. Introduction to Databases. Why databases? Why not use XML?

Join Example. Join Example Cart Prod Comprehensive Consulting Solutions, Inc.All rights reserved.

UNIVERSE DESIGN BEST PRACTICES. Roxanne Pittman, InfoSol May 8, 2014

Transcription:

(Web) Application Development With Ian Week 3 SQL with Multiple Tables Join The join operation allows you to combine related rows of data found in two tables into a single result set. It works similarly to a query we did last week: SELECT hr.employeeid, hr.title, pc.firstname, pc.lastname FROM HumanResources.Employee hr, Person.Contact pc WHERE hr.employeeid = pc.contactid This query grabs the EmployeeID and Title columns from HumanResources.Employee, and the FirstName & LastName columns from Person.Contact, where the EmployeeID and ContactID are equal to 5. Note the SELECT hr.employeeid short form. I m using pc to refer to Person.Contact. That alias is set: FROM HumanResources.Employee hr. Using a join would make this query easier to understand: SELECT EmployeeID, hr.title, FirstName, LastName FROM HumanResources.Employee hr JOIN Person.Contact pc ON hr.employeeid = pc.contactid Joining two tables returns rows where the ON condition exists. Before continuing, create the School database then add the tables as you see them on the next two pages. 1/7

Table Structure: Teachers Table Teachers Populated: Table Structure: Courses Table Courses Populated 2/7

Table Structure: Students Table Students Populated Table Structure: Grades Table Grades Populated: 3/7

Review: 1) SELECT * FROM Teachers 2) SELECT FirstName FROM Teachers 3) SELECT FirstName, LastName FROM Teachers ORDER BY LastName Desc 4) SELECT CourseID, Title FROM Courses WHERE Instructor = 2 New: 1) Using a join to get the list of class codes, instructors, and course titles: FROM Teachers t JOIN Courses c Notice poor Andrew doesn t show up. He s not actively teaching this year, so he s not assigned to any courses. Thus he is excluded in the join. 2) Lets put some order to that list: FROM Teachers t JOIN Courses c ORDER BY LastName 3) This query will get the same information as, except only returning courses that I teach: FROM Teachers t JOIN Courses c WHERE FirstName = 'Ian' Both of these joins are examples of equi joins, joins where the ON clause uses equals. Unless otherwise specified, such as an outer join, joins are generally assumed to be equi joins. 4/7

4) In SQL Server 2005 you ll get the same results using INNER JOIN as with regular JOIN FROM Teachers t INNER JOIN Courses c 5) Self joins allow you to join a table to itself. This is useful when you need to find information that s based on more than one column (note: this can be a hard concept to get used to!): SELECT 'GradeRank' = x.studentid + ' got a better grade than ' + y.studentid FROM Grades AS x, Grades AS y WHERE y.courseid = 'MEDA59196' AND x.grade < y.grade 6) This can then be ordered by the grade: SELECT 'GradeRank' = x.studentid + ' got a better grade than ' + y.studentid FROM Grades AS x, Grades AS y WHERE y.courseid = 'MEDA59196' AND x.grade < y.grade ORDER BY y.grade ** If 5,6 are unclear don t worry. We ll be doing more examples of this type of join in the coming weeks with data it s easier to see. 7) Nesting joins allows you to join multiple tables. Say you wanted to know the name of any students who failed AND the title of the course they failed: Lets start by joining the Students with their Grades: FROM Students stu JOIN Grades g ON stu.studentid = g.studentid Now add a where clause to restrict it to people who failed: FROM Students stu JOIN Grades g ON stu.studentid = g.studentid WHERE Grade = 'F' 5/7

Now do the 3 table join:, Title FROM Students stu JOIN (Grades grd JOIN Courses c ON grd.courseid = c.courseid) ON stu.studentid = grd.studentid Brackets set precedence So the Grades are joined to the Course FIRST THEN Students are then joined to the Grades Note: building up your queries in steps will let you find mistakes easier. 8a) What if we want to join two tables together, but not all records in table A have a match in B? Remember when we joined Courses and Teachers in example 1 we lost Andrew. He isn t listed in Courses so he didn t show up. FROM Students stu LEFT OUTER JOIN Grades grd ON stu.studentid = grd.studentid Students is the left table, Grades the right. So precedence is given to the Left in this case, meaning all rows from the left will be returned even if they don t have a match in the right. 8b) FROM Students stu RIGHT OUTER JOIN Grades grd ON stu.studentid = grd.studentid Does it the other way around. 9) Counting If you want to know the total number of records, or some subset of records, you can use the count function. SELECT COUNT(*) FROM Courses SELECT COUNT(*) AS [Number of Courses] FROM Courses 6/7

To Try On Your Own: 1) Get a list of all the student names and ID # s. 2) Make the list is #1 display alphabetically by last name. 3a) Create and Assignments table with AssignmentID, Title, and Value columns. 3b) Create a Deliverables table with DeliverableID, ClassID, AssignmentID, and DueDate columns. 3c) Populate some values into both tables. Make sure you use valid ClassID s, etc. (If the data relates to the tables you ve already created, use matching data) (Note: it could be argued that these 2 new tables are not as normalized as they could be. That s fine, it ll make life easier to see what s going on right now.) 4) Using the new tables you created, write the SQL query that will create this table: 5) Using nested joins, add on to the above to create this result: 7/7