1 Joining Tables in Queries. 2 Objectives You will be able to Write SQL queries that use Join operations to retrieve information from multiple tables.

Slides:



Advertisements
Similar presentations
Module 6: Working with Subqueries. Overview Introduction to Subqueries Using a Subquery as a Derived Table Using a Subquery as an Expression Using a Subquery.
Advertisements

SQL Language. Introduction to RDBMS Introduction to RDBMS Basic Data Manipulation - Reading Data Basic Data Manipulation - Reading Data Basic Data Manipulation.
Populating and Querying tables Insert and mostly View (DML)
1 SQL-Structured Query Language SQL is the most common language used for creating and querying relational databases. Many users can access a database applications.
1 Creating a Non-Conditional List A- What are you going to do? You will “list” “all of the records” in a database. (it means you will not use any condition!)
Tutorial 5 Multi-table queries. Tutorial 5 objectives Displaying Data from Multiple Tables –[ ]Write SELECT statements to access data from more than one.
SQLite 1 CS440. What is SQLite?  Open Source Database embedded in Android  SQL syntax  Requires small memory at runtime (250 Kbytes)  Lightweight.
DATA, DATABASES, AND QUERIES Managing Data in Relational Databases CS1100Microsoft Access - Introduction1.
SQL Joins.
DATA, DATABASES, AND QUERIES Managing Data in Relational Databases CS1100Microsoft Access - Introduction1 Created By Martin Schedlbauer
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
CS&E 1111 AcQueries Writing Simple Queries in Access Displaying on specific data fields Filtering data using criteria Objectives: Learn how to use the.
CS&E 1111 AcInnerJoins Inner Joins Objectives: Creating Queries with data from Multiple Tables Joining two tables using an Inner Join Referential Data.
SQL Review Tonga Institute of Higher Education. SQL Introduction SQL (Structured Query Language) a language that allows a developer to work with data.
Database Management. ICT5 Database Administration (DBA) The DBA’s tasks will include the following: 1. The design of the database. After the initial design,
1 Databound Controls. 2 Objectives You will be able to use design time data binding to display and update SQL Server database data without writing any.
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
Module 1: Introduction to Transact-SQL
1 Working with MS SQL Server Textbook Chapter 14.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Working with MSSQL Server Code:G0-C# Version: 1.0 Author: Pham Trung Hai CTD.
T-SQL Transact-SQL is microsoft implementation of SQL. It contains additional programming constracts T-SQL enables you to write programs that contain SQL.
Final Exam Guide PHP NOTE: PHP CODE WILL BE BLUE, HTML IS BLACK EXAMPLE
Module 11: Programming Across Multiple Servers. Overview Introducing Distributed Queries Setting Up a Linked Server Environment Working with Linked Servers.
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to SQL—Topics Introduction to.
JOINS cis 407 Inner join Right and left outer join Full join Cross join.
1 Project 7: Northwind Traders Order Entry. 2 Northwind Order Entry Extend the Select Customer program from Project 6 to permit the user to enter orders.
CS1100: Microsoft Access Managing Data in Relational Databases Created By Martin Schedlbauer CS11001Microsoft Access - Introduction.
Lab 4: Displaying Data from Multiple Tables CISB224 02A, 02B Semester I, 2009/2010 College of Information Technology, Universiti Tenaga Nasional 1.
Programming in R SQL in R. Running SQL in R In this session I will show you how to: Run basic SQL commands within R.
Retrieving XML Data from SQL server.  Using the FOR XML Clause to Retrieve Data Retrieving Data in XML Format How SQL Server Generates XML Using the.
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
Module 7: Implementing Views. Overview Introducing Views Defining and Using Views Using Views to Optimize Performance.
Views, Algebra Temporary Tables. Definition of a view A view is a virtual table which does not physically hold data but instead acts like a window into.
Understanding Databases Lesson 6. Objective Domain Matrix Skills/ConceptsMTA Exam Objectives Understanding Relational Database Concepts Understand relational.
Chapter 14 1 Chapter 14 Storing and Retrieving XML in SQL Server 2000 November 6, 2001 Sook-Kyo Kwon.
Enterprise manager Using the Enterprise manager. Purpose of the Enterprise Manager To design tables To populate / update tables To draw diagrams of tables.
A Guide to SQL, Eighth Edition Chapter Five Multiple-Table Queries.
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
QUERY CONSTRUCTION CS1100: Data, Databases, and Queries CS1100Microsoft Access1.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
IMS 4212: Intro to Multi-Table SELECT Statements 1 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table SELECT Statements—Topics.
1 Low Level ADO.NET Operations II Microsoft Visual C# 2008 Step by Step Chapter 25.
Day 5 - More Complexity With Queries Explanation of JOIN & Examples Explanation of JOIN & Examples Explanation & Examples of Aggregation Explanation &
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.
CFUNITED – The premier ColdFusion conference Beyond Basic SQL for CF Nate Nelson
1 Project 6: Northwind Orders. 2 The Northwind Traders Database The Northwind Traders database was created by Microsoft for training and demonstration.
Writing Simple Queries in Access
Structured Query Language
Database Management Systems II
Using DML to Modify Data
Inner Joins Objectives: Creating Queries with data from Multiple Tables Joining two tables using an Inner Join Referential Data Integrity Cascade Update.
Querying Multiple Tables
LESSON Database Administration Fundamentals Inserting Data.
© 2010, Mike Murach & Associates, Inc.
20761A 10: Using Subqueries Module 10   Using Subqueries.
20761A 11: Using Set Operators Module 11   Using Set Operators.
Querying Multiple Tables
06 | Using Subqueries and APPLY
20761B 12: Using Set Operators Module 12   Using Set Operators.
20761B 10: Using Subqueries Module 10   Using Subqueries.
- Review. - Joins. - Views. - Calculated Values
Aggregations Various Aggregation Functions GROUP BY HAVING.
Advanced Joins IN ( ) Expression Subqueries with IN ( ) Expression
CISB224 01A, 01B, 02A, 02B CCSB244 01A, 01B Semester I, 2007/2008
Rob Gleasure robgleasure.com
Using DML to Modify Data
Presentation transcript:

1 Joining Tables in Queries

2 Objectives You will be able to Write SQL queries that use Join operations to retrieve information from multiple tables.

3 Retrieving from Multiple Tables We often need to retrieve information from multiple tables in a single query. Example: Show the name of the customer contact for all orders in the Northwinds database.

The Northwinds Database (Subset)

5 Retrieving from Multiple Tables The Orders table has the Customer ID but not the customer’s contact name. The Customers table has the contact name. In order to determine the customer contact for an order, we need to get the Customer ID from the Orders table and then get the contact name for that Customer ID from the Customers table. The SQL “join” operation makes this possible with a single query. Retrieve pairs of rows from two tables having identical values of some key.

6 Types of Joins SQL defines several types of joins. The simplest is the inner join. It has the form: SELECT TABLE1.COLUMN1, TABLE2.COLUMN2 FROM TABLE1, TABLE2 WHERE TABLE1.COLUMN_X = TABLE2.COLUMN_Y Whatever you want from either table Query will return selected items from every pair of rows for which this condition is true.

7 Inner Join Example Running sqlcmd with the Northwind Database

8 Inner Join Example Objective: Determine the name of the customer's contact on all orders.

9 Inner Join Example 1> SELECT ORDERS.ORDERID, CUSTOMERS.CONTACTNAME 2> FROM ORDERS, CUSTOMERS 3> WHERE CUSTOMERS.CUSTOMERID = ORDERS.CUSTOMERID 4> GO ORDERID CONTACTNAME Maria Anders Maria Anders Maria Anders Maria Anders Maria Anders Maria Anders Carine Schmitt Carine Schmitt (830 rows affected) 1>

10 Being More Selective We could add more conditions to the WHERE clause. Suppose we wanted the contact name for just one specific order. We could add to the query: AND ORDERS.ORDERID=11012

11 Inner Join Example 1> SELECT ORDERS.ORDERID, CUSTOMERS.CONTACTNAME 2> FROM ORDERS, CUSTOMERS 3> WHERE CUSTOMERS.CUSTOMERID = ORDERS.CUSTOMERID 4> AND ORDERS.ORDERID= > GO ORDERID CONTACTNAME Peter Franken (1 rows affected) 1>

12 Table Aliases We can give a table a temporary name within a single SQL statement A short name saves keystokes and makes the statement easier to read and understand. Write the (short) temporary name immediately after the real table name in the FROM clause.

13 1> SELECT O.ORDERID, C.CONTACTNAME 2> FROM ORDERS O, CUSTOMERS C 3> WHERE C.CUSTOMERID = O.CUSTOMERID 4> AND O.ORDERID = > GO ORDERID CONTACTNAME Bernardo Batista (1 rows affected) 1> Table Aliases

14 Joining More than Two Tables Any number of tables can be included in a join operation. Suppose we want to see the name of each product on any order by Customer VINET VINET is the Customer ID

Joining More than Two Tables 1> SELECT P.ProductName 2> FROM Products P, [Order Details] OD, Orders O, Customers C 3> WHERE P.ProductID = OD.ProductID 4> AND OD.OrderID = O.OrderID 5> AND O.CustomerID = C.CustomerID 6> AND C.CustomerID = 'VINET' 7> GO ProductName Queso Cabrales Singaporean Hokkien Fried Mee Mozzarella di Giovanni Flotemysost Mozzarella di Giovanni Gnocchi di nonna Alice Konbu Jack's New England Clam Chowder Inlagd Sill Filo Mix (10 rows affected) 1>

17 The Northwind Product Browser Let’s extend the Northwind Product Browser to show the supplier for each product. Download the final version of the example done in class: Downloads/2011_04_05_Northwind_Product_Browser/ Downloads/2011_04_05_Northwind_Product_Browser/ File Northwind_Product_Browser.zip Expand zip file. Build and run.

18 The Northwinds Product Browser

19 The Northwind Product Browser We would like to show the supplier for each product along with the other product information. We can use a join to get related information along with the product information.

Products and Suppliers

21 Products and Suppliers The Product table includes a SupplierID. Not meaningful to the user. The Supplier table includes the supplier's CompanyName which is meaningful. Tables are related by SupplierID Use an inner join to get the CompanyName of the supplier of each product from the Supplier table.

22 Check Command in SQLCMD

23 Class Products Class Products is responsible for the query. SqlCommand1.CommandText = "SELECT P.*, S.CompanyName " + "FROM Products P, Suppliers S " + "WHERE P.SupplierID = S.SupplierID"; Build and run. Existing code is not affected by the change to the query.

24 Class Product public class Product { private String product_name; private int product_id; private decimal unit_price; private short units_in_stock; private bool discontinued; private String supplier_name;... public String Supplier_name { get { return supplier_name; } set { supplier_name = value; } }

25 Class Product // This constructor initializes a product // using a query result. public Product(SqlDataReader rdr) { Product_name = rdr.GetString(1); Product_id = rdr.GetInt32(0); Supplier_name = rdr.GetString(10); …

Class Product_Information

27 Product_Information.cs private void Display_Current_Record() { Product p = Product_List[current_record_number]; tbProductName.Text = p.Product_name; tbProductID.Text = p.Product_id.ToString(); tbUnitPrice.Text = p.Unit_price.ToString(); tbUnitsInStock.Text = p.Units_in_stock.ToString(); cbDiscontinued.Checked = p.Discontinued; tbSupplier.Text = p.Supplier_name; tbRecordNumber.Text = "Record " + (current_record_number + 1) + " of " + Product_List.Count; Update_Buttons(); }

28 Product Browser in Action

29 List Alphabetically Let’s show the products in alphabetical order by ProductName. Revised query: sc.CommandText = "SELECT P.*, S.CompanyName " + "FROM Products P, Suppliers S " + "WHERE P.SupplierID = S.SupplierID " + "ORDER BY P.ProductName" ;

30 App in Action End of Presentation