ZEIT2301 Design of Information Systems Multi-Table Queries in SQL School of Engineering and Information Technology Dr Kathryn Merrick.

Slides:



Advertisements
Similar presentations
SQL – Lesson II Grade 12.
Advertisements

Advanced SQL Topics Edward Wu.
Using the Set Operators
Advanced SQL (part 1) CS263 Lecture 7.
© Abdou Illia MIS Spring 2014
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.
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Join Queries CS 146. Introduction: Join Queries So far, our SELECT queries have retrieved data from a single table Usually queries combine data from multiple.
Chapter 4 Joining Multiple Tables
Creating Tables, Setting Constraints, and Datatypes What is a constraint and why do we use it? What is a datatype? What does CHAR mean? Page 97 in Course.
Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.
Displaying Data from Multiple Tables
Creating Tables. 2 home back first prev next last What Will I Learn? List and provide an example of each of the number, character, and date data types.
ZEIT2301 Design of Information Systems Relational Database Schema School of Engineering and Information Technology Dr Kathryn Merrick.
Writing Basic SQL SELECT Statements. Capabilities of SQL SELECT Statements A SELECT statement retrieves information from the database. Using a SELECT.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
Introduction to Oracle9i: SQL1 Basic SQL SELECT Statements.
Inner join, self join and Outer join Sen Zhang. Joining data together is one of the most significant strengths of a relational database. A join is a query.
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.
Objectives After completing this lesson, you should be able to do the following: Write SELECT statements to access data from more than one table using.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
Learningcomputer.com SQL Server 2008 – Entity Relationships in a Database.
Chapter 9 Joining Data from Multiple Tables
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
Programming using C# Joins SQL Injection Stored Procedures
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
JOI/1 Data Manipulation - Joins Objectives –To learn how to join several tables together to produce output Contents –Extending a Select to retrieve data.
Week 10 Quiz 9 Answers Group 28 Christine Hallstrom Deena Phadnis.
Recap of SQL Lab no 8 Advance Database Management System.
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
I NTRODUCTION TO SQL II. T ABLE JOINS A simple SQL select statement is one that selects one or more columns from any single table There are two types.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
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.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
1 DBS201: More on SQL Lecture 3. 2 Agenda How to use SQL to update table definitions How to update data in a table How to join tables together.
Working with Columns, Characters, and Rows. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Apply the concatenation.
LINQ to DATABASE-2.  Creating the BooksDataContext  The code combines data from the three tables in the Books database and displays the relationships.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
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.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
Slide 1 of 32ASH-Training Querying and Managing Data Using SQL Server 2014 By: Segla In this session, you will learn to: Query data by using joins Query.
1 Copyright © 2007, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
Copyright © 2016 Pearson Education, Inc. CHAPTER 7: ADVANCED SQL (PART I) Modern Database Management 12 th Edition Jeff Hoffer, Ramesh Venkataraman, Heikki.
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.
1 Copyright © 2009, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
LEC-8 SQL. Indexes The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading.
Advanced SQL Advanced Database Dr. AlaaEddin Almabhouh.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Standards and Conventions
IFS180 Intro. to Data Management Chapter 10 - Unions.
Rob Gleasure robgleasure.com
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Writing Basic SQL SELECT Statements
JOINS (Joinining multiple tables)
Rob Gleasure robgleasure.com
Writing Basic SQL SELECT Statements
CSC 453 Database Systems Lecture
Rob Gleasure robgleasure.com
Displaying Data from Multiple Tables
Manipulating Data Lesson 3.
Use of SQL – The Patricia database
JOINS (Joinining multiple tables)
Presentation transcript:

ZEIT2301 Design of Information Systems Multi-Table Queries in SQL School of Engineering and Information Technology Dr Kathryn Merrick

Topic 12: Multi-Table Queries in SQL Todays lecture will look at how to write SQL statements for multi-table queries: Inner (Natural) Joins Outer Joins Unions References: Connolly & Begg, Database Solutions, Pearson, 2004.

Combining Tables Very often, in order to answer a query, it is necessary to combine data from different tables – that is, it is necessary to perform a JOIN This can be done using the SQL SELECT statement by: listing the tables to be joined after the FROM keyword, and specifying how they are to be joined using the WHERE clause

Joining Tables in SQL Consider the database design: student(studentNo, Name, DOB, Address, Gender, Degree) enrolIn(studentNo, courseCode, Mark) course(courseCode, courseName, Lecturer) lecturer(Name, Department, Telephone, Title)

Joining Tables in SQL Now, how can we find out which Course (i.e. the courseCode) student Jane Doe is enrolled in? The data we need is spread across two tables: student (has student name) and enrolIn (has course code). We need a JOIN of the student and enrolIn tables. JOINs are undertaken typically via the Primary Key/Foreign Key links between tables. (In this example, the PK/FK link is studentNo). Your Relational Schema helps you to see these PK/FK links

Join Conditions The query is: SELECT Name, courseCode FROM student, enrolIn WHERE student.studentNo = enrolIn.studentNo AND Name = Jane Doe; The condition in italics is the JOIN condition – it determines how the two tables are linked together student(studentNo, Name, DOB, Address, Gender, Degree) enrolIn(studentNo, courseCode, Mark) Note: Both tables listed in FROM clause

Referencing Attributes If two attributes in different tables have the same name then these need to be distinguished in an SQL query by attaching the relevant table name to the attribute (i.e. tableName.attributeName) Example: lecturer.Name student.Name student(studentNo, Name, DOB, Address, Gender, Degree) lecturer(Name, Department, Telephone, Title)

Table Name Aliases Table name aliases can be used for table names (or column names) to simplify statements and give tables temporary names Aliasing a table name: FROM lecturer AS Lor simply FROM lecturer L L can then be used in place of Lecturer eg where L.name LIKE kathryn instead of: Lecturer.name LIKE kathryn

Inner (Natural) Joins Show students and their enrolled courses: SELECT Name, courseCode FROM student, enrolIn WHERE student.studentNo = enrolIn.studentNo; A NATURAL or INNER join: only returns matching rows from the tables concerned If a student was not enrolled in a course (i.e. no entry in the enrolIn table), then their name is not displayed

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons, Orders WHERE Persons.P_Id = Orders.P_Id

Two-Way Natural Joins For example, to answer the question Which Courses (by name) are taught by D. Hart? SELECT courseName FROM course, lecturer WHERE lecturer = name AND name = D. Hart; This is another example of a two-way join (i.e. involves 2 tables), but joins can also be carried out between as many tables as necessary … course(courseCode, courseName, lecturer) lecturer(name, department, telephone, title)

Three-Way Natural Joins Example: to answer the question Which Courses (by Course name) is Jane Doe enrolled in? SELECT courseName FROM course, student, enrolIn WHERE course.courseCode = enrolIn.courseCode AND student.studentNo = enrolIn.studentNo AND name = Jane Doe; student(studentNo, Name, DOB, Address, Gender, Degree) enrolIn(studentNo, courseCode, Mark) course(courseCode, courseName, Lecturer)

In-class Exercise 1 Exercise: List the names (last & other) and teams of all players Solution: SELECT lastName, otherNames, teamName FROM player, playsFor WHERE player.playerID = playsFor.playerID; player ( playerID, lastName, otherNames, ………) playsFor ( playerID, teamName )

In-class Exercise 2 Exercise: Show the names and addresses for the coaches of the Dead Heads team. Solution: SELECT coach.coachName, address FROM coach, coaches WHERE coach.coachName = coaches.coachName AND teamName = Dead Heads; coach ( coachName, phoneNo, address, DOB ) coaches ( coachName, teamName, startDate, endDate )

Alternative Syntax for Joins There is an alternative join syntax that specifies the join attributes in the FROM clause rather than the WHERE clause This syntax applies to joins other than Natural Joins MsAccess use this alternative syntax SELECT column1, column2 FROM table1 JOIN table2 ON join-condition;

Alternative Syntax Example List the names and teams of all players: SELECT lastName, otherNames, teamName FROM player JOIN playsFor ON player.playerID = playsFor.playerID; player ( playerID, lastName, otherNames, ………) playsFor ( playerID, teamName )

Other Alternative Syntax for Joins Alternative 2 SELECT column1, column2 FROM table1 JOIN table2 USING column1; Alternative 3 SELECT column1, column2 FROM table1 NATURAL JOIN table2; Alternative 4 SELECT column1, column2 FROM table1 INNER JOIN table2; Note: The alternatives you use may depend on Your personal preference The software you are using

Outer Joins A NATURAL join: only returns matching rows from the tables concerned An OUTER join: permit rows to be included in the result, even when there is no match in one of the tables There are two kinds: LEFT JOIN RIGHT JOIN

Left (Outer) Joins The LEFT JOIN keyword returns all rows from the left (first mentioned) table, even if there are no matches in the right (second mentioned) table. Non matching rows are completed with null values

Right and Full (Outer) Joins The RIGHT JOIN keyword returns all the rows from the right (second mentioned) table even if there are no matches in the left (first mentioned) table. Non matching rows are completed with null values The FULL JOIN keyword returns all rows from both tables, even if there is no match in the other table. Non matching rows are completed with null values See: and for worked exampleshttp://

Dont forget the JOIN clause! What happens if you use more than one table in your query but forget to join the tables? Your result will be the Cartesian Product Ie: every row from Table 1 combined with every row from Table 2 Eg: If table 1 has 10 rows and Table 2 has 6 rows, your result will have 60 rows. This is a BAD THING! Your query can produce a huge result table – check your joins!

Example Missing JOIN Clause SELECT Employee.EmpNo, Employee.Name, EmpDept, Dept.Name, Dept.Location FROM Dept, Employee;

Result table : 15 rows

The result from the above query (with no join specified) is 3x5=15 rows. Notice the spurious, and incorrect data: Eg: employee Marcus Aarents is shown as working at all three departments A join would ensure that only the valid rows are selected might be: WHERE employee.EmpDept = dept.Name Example – no JOIN clause

Session 2, Only 5 rows are valid (ie where Dept names match)

Unions The UNION operator is used to combine the result-set of two or more SELECT statements. Hint: this may be of use for Ass 2 Each SELECT statement within the UNION must have: The same number of columns. With the same data types. In the same order. Caveat: The UNION operator selects distinct values by default. Use UNION ALL for duplicates.

Summary SQL is use to retrieve data from tables in a Relational database When retrieving data from more than one table, those tables must be joined using matching PK and FK values. After todays lecture you should be able to use SQL: Joins Unions