Retrieving Data from Multiple Tables

Similar documents
Join, Sub queries and set operators

Database Foundations. 6-9 Joining Tables Using JOIN. Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

Lab # 6. Data Manipulation Language (DML)

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

Intermediate SQL: Aggregated Data, Joins and Set Operators

GIFT Department of Computing Science. CS-217/224: Database Systems. Lab-5 Manual. Displaying Data from Multiple Tables - SQL Joins

KORA. RDBMS Concepts II

EXISTS NOT EXISTS WITH

Oracle Database SQL Basics

HR Database. Sample Output from TechWriter 2007 for Databases

ÇALIŞMA TEST SORULARI

Alkérdések II. Copyright 2004, Oracle. All rights reserved.

Using the Set Operators. Copyright 2006, Oracle. All rights reserved.

Using the Set Operators. Copyright 2004, Oracle. All rights reserved.

Database Programming with SQL

Database Programming with PL/SQL

Additional Practice Solutions

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

Creating Other Schema Objects

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Misc. Triggers Views Roles Sequences - Synonyms. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering

Série n 6 Bis : Ateliers SQL Data Modeler (Oracle)

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Manipulating Data. Copyright 2004, Oracle. All rights reserved.

SQL Retrieving Data from Multiple Tables

Introduction to Oracle9i: SQL

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH

Database Programming with SQL

DEFAULT Values, MERGE, and Multi-Table Inserts. Copyright 2009, Oracle. All rights reserved.

Bsc (Hons) Software Engineering. Examinations for / Semester 1. Resit Examinations for BSE/15A/FT & BSE/16A/FT

CBO SQL TRANSFORMER Document describes a few examples of transformations made by CBO.

Aggregate Functions. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Dept. Database Lab (ECOM 4113)

LECTURE10: DATA MANIPULATION IN SQL, ADVANCED SQL QUERIES

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

Database Programming - Section 3. Instructor Guide

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Database Programming with PL/SQL

Creating Other Schema Objects. Copyright 2004, Oracle. All rights reserved.

Lecture10: Data Manipulation in SQL, Advanced SQL queries

Introduction to Oracle9i: SQL

Exam: 1Z Title : Introduction to Oracle9i: SQL. Ver :

Database Programming with SQL

Tables From Existing Tables

A subquery is a nested query inserted inside a large query Generally occurs with select, from, where Also known as inner query or inner select,

Data Manipulation Language

1Z0-007 ineroduction to oracle9l:sql

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

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

Database Programming - Section 7. Instructor Guide

BackLogic Quick-Start Tutorial

Táblák tartalmának módosítása. Copyright 2004, Oracle. All rights reserved.

Introduction to Explicit Cursors. Copyright 2008, Oracle. All rights reserved.

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

RETRIEVING DATA USING THE SQL SELECT STATEMENT


Database Programming with SQL

Joining tables. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

Database Programming with PL/SQL

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

2. What privilege should a user be given to create tables? The CREATE TABLE privilege

Limit Rows Selected. Copyright 2008, Oracle. All rights reserved.

Updating Column Values and Deleting Rows. Copyright 2008, Oracle. All rights reserved.

Who is the borrower whose id is 12345? σ borrower borrower_id = select * from borrower where borrower_id = '12345'

DUE: 9. Create a query that will return the average order total for all Global Fast Foods orders from January 1, 2002, to December 21, 2002.

Oracle Database 10g: SQL Fundamentals II

Chapter 4 How to retrieve data from two tables

Set theory is a branch of mathematics that studies sets. Sets are a collection of objects.

Database Programming - Section 11. Instructor Guide

Advance Database Systems. Joining Concepts in Advanced SQL Lecture# 4

Database Programming with SQL

Querying Data with Transact SQL

Vendor: Oracle. Exam Code: 1Z Exam Name: Oracle Database: SQL Fundamentals I. Q&As: 292

SELF TEST. List the Capabilities of SQL SELECT Statements

Database Management Systems,

CS 275 Winter 2011 Problem Set 3

Database Management Systems,

Assignment Grading Rubric

20 Essential Oracle SQL and PL/SQL Tuning Tips. John Mullins

CIS 363 MySQL. Chapter 12 Joins Chapter 13 Subqueries

RDBMS- Day 4. Grouped results Relational algebra Joins Sub queries. In today s session we will discuss about the concept of sub queries.

Oracle 1Z Oracle Database 11g : SQL Fundamentals I. Download Full Version :

Data Manipulation Language (DML)

Objectives. After completing this lesson, you should be able to do the following:

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Reference: W3School -

Pragmatic Approach to Query Optimization

More SQL: Complex Queries, Triggers, Views, and Schema Modification

Exam Code: 1z Exam Name: Ineroduction to oracle9l:sql. Vendor: Oracle. Version: DEMO

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

Fravo.com. Certification Made Easy. World No1 Cert Guides. Introduction to Oracle9i: SQL Exam 1Z Edition 1.0

Database Programming with PL/SQL

Database Programming with PL/SQL

Exam : 1Z Title : Introduction to Oracle9i: SQL

Three types of sub queries are supported in SQL are Scalar, Row and Table sub queries.

Subquery: There are basically three types of subqueries are:

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Oracle Database 11g: SQL Fundamentals I

chapter 2 G ETTING I NFORMATION FROM A TABLE

Transcription:

Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Database Lab (ECOM 4113) Lab 5 Retrieving Data from Multiple Tables Eng. Mohammed Alokshiya November 2, 2014

An JOIN clause is used to combine rows from two or more tables, based on a common field between them. The following table lists the types the different JOINs you can use: INNER JOIN: Specifies a join between two tables with an explicit join clause. LEFT OUTER JOIN: Specifies a join between two tables with an explicit join clause, preserving unmatched rows from the first table. RIGHT OUTER JOIN: Specifies a join between two tables with an explicit join clause, preserving unmatched rows from the second table. FULL OUTER JOIN: Return all rows when there is a match in ONE of the tables. NATURAL JOIN: creates an implicit join clause for you based on the common columns in the two tables being joined. Common columns are columns that have the same name in both tables. CROSS JOIN: produces the cross-product of two tables. In general, the syntax of an JOIN clause is: JOIN Syntax SELECT TABLE1.COLUMN, TABLE2.COLUMN FROM TABLE1 [NATURAL JOIN TABLE2] [JOIN TABLE2 USING (COLUMN_NAME)] [JOIN TABLE2 ON (TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME)] [LEFT RIGHT FULL OUTER JOIN TABLE2 ON (TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME)] [CROSS JOIN TABLE2]; INNER JOIN An INNER JOIN is a JOIN operation that allows you to specify an explicit join clause. Syntax: INNER JOIN Syntax TABLE1 [INNER] JOIN TABLE2 USING (COLUMN_NAME) ON (TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME); 2

Example: Join the EMPLOYEES and DEPARTMENTS tables, select employee ID (EMPLOYEE_ID), employee last name, (LAST_NAME), department ID and department name (DEPARTMENT_NAME) of all employees who are hired before 2004. SELECT EMPLOYEE_ID, LAST_NAME, DEPARTMENT_ID, DEPARTMENT_NAME JOIN DEPARTMENTS USING (DEPARTMENT_ID) WHERE HIRE_DATE < '01-JAN-04'; You can also use ON clause instead of USING clause: SELECT E.EMPLOYEE_ID, E.LAST_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME E JOIN DEPARTMENTS D ON E.DEPARTMENT_ID = D.DEPARTMENT_ID WHERE HIRE_DATE < '01-JAN-04'; 3

Creating Three-Way Joins with the ON Clause A three-way join is a join of three tables. Joins are performed from left to right. Example: Write a query to retrieve first name, last name, department name and city, for all employees whose salary is greater than 9000. SELECT E.FIRST_NAME, E.LAST_NAME, E.SALARY, D.DEPARTMENT_NAME, L.CITY E JOIN DEPARTMENTS D ON E.DEPARTMENT_ID = D.DEPARTMENT_ID JOIN LOCATIONS L ON D.LOCATION_ID = L.LOCATION_ID WHERE SALARY > 9000; Example: write a query to retrieve first name, last name, job, department id, and department name for all employees who work in Toronto City. SELECT E.FIRST_NAME, E.LAST_NAME, E.JOB_ID, DEPARTMENT_ID, D.DEPARTMENT_NAME, L.CITY E JOIN DEPARTMENTS D USING (DEPARTMENT_ID) JOIN LOCATIONS L ON (D.LOCATION_ID = L.LOCATION_ID AND CITY = 'Toronto'); 4

Self-Join: Joining a Table to Itself Example: write a query to retrieve the first name, last name and manager full name of all employees. SELECT WORKER.FIRST_NAME, WORKER.LAST_NAME, MANAGER.FIRST_NAME ' ' MANAGER.LAST_NAME "Manager Full Name" WORKER JOIN EMPLOYEES MANAGER ON WORKER.MANAGER_ID = MANAGER.EMPLOYEE_ID; Example: write a query to retrieve employee last names, department numbers, and all the employees who work in the same department as a given employee. SELECT E.LAST_NAME, DEPARTMENT_ID, C.LAST_NAME "Colleague" E JOIN EMPLOYEES C USING (DEPARTMENT_ID) WHERE E.EMPLOYEE_ID <> C.EMPLOYEE_ID ORDER BY 2, 1; 5

Example: write a query to retrieve the names and hire dates of all the employees who are hired before their managers, along with their managers names and hire dates. SELECT WORKER.LAST_NAME, WORKER.HIRE_DATE, MANAGER.LAST_NAME, MANAGER.HIRE_DATE WORKER JOIN EMPLOYEES MANAGER ON WORKER.MANAGER_ID = MANAGER.EMPLOYEE_ID WHERE WORKER.HIRE_DATE < MANAGER.HIRE_DATE; 6

OUTER JOIN By default, joining tables with the NATURAL JOIN, USING, or ON clauses results in an inner join. Any unmatched rows are not displayed in the output. To return the unmatched rows, you can use an outer join. An outer join returns all rows that satisfy the join condition and also returns some or all of those rows from one table for which no rows from the other table satisfy the join condition. There are three types of outer joins: LEFT OUTER RIGHT OUTER FULL OUTER Syntax: OUTER JOIN Syntax TABLE1 {LEFT RIGHT FULL} [OUTER] JOIN TABLE2 USING (COLUMN_NAME) ON (TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME); Example: LEFT OUTER JOIN: SELECT LAST_NAME, DEPARTMENT_NAME E LEFT OUTER JOIN DEPARTMENTS D USING (DEPARTMENT_ID); 7

Example: Right OUTER JOIN: SELECT E.LAST_NAME, E.DEPARTMENT_ID, D.DEPARTMENT_ID, D.DEPARTMENT_NAME E RIGHT OUTER JOIN DEPARTMENTS D ON E.DEPARTMENT_ID = D.DEPARTMENT_ID; Example: FULL OUTER JOIN: SELECT E.LAST_NAME, E.DEPARTMENT_ID, D.DEPARTMENT_ID, D.DEPARTMENT_NAME E FULL OUTER JOIN DEPARTMENTS D ON E.DEPARTMENT_ID = D.DEPARTMENT_ID; 8

NATURAL JOIN operation A NATURAL JOIN is a JOIN operation that creates an implicit join clause for you based on the common columns in the two tables being joined. Common columns are columns that have the same name in both tables. A NATURAL JOIN can be an INNER join, a LEFT OUTER join, or a RIGHT OUTER join. The default is INNER join. If the SELECT statement in which the NATURAL JOIN operation appears has an asterisk (*) in the select list, the asterisk will be expanded to the following list of columns (in this order): All the common columns Every column in the first (left) table that is not a common column Every column in the second (right) table that is not a common column Example: retrieve department id, department name, location id and city for all departments. SELECT DEPARTMENT_ID, DEPARTMENT_NAME, LOCATION_ID, CITY FROM DEPARTMENTS NATURAL JOIN LOCATIONS; 9

Summary: 10

Using Subqueries to Solve Queries Example: retrieving all employees who has a salary greater than the average salaries in department 80. First solution: retrieve targeted employees with two steps; firstly, retrieve average salaries of all employees in dept. 80, then, use the result in another query. The first query: First Query SELECT AVG(SALARY) WHERE DEPARTMENT_ID = 80; Then you will get the average: Use it in a new Query: Second Query SELECT FIRST_NAME, LAST_NAME, SALARY WHERE SALARY > 8955.882; And you will get the targeted employees: A better solution is to embedded the first query in the second query in two parentheses, which is called: inner query: Solution using Inner Query SELECT FIRST_NAME, LAST_NAME, SALARY WHERE SALARY > ( SELECT AVG(SALARY) WHERE DEPARTMENT_ID = 80 ); 11

Types of Subqueries Single-row subqueries: Queries that return only one row from the inner SELECT statement. Multiple-row subqueries: Queries that return more than one row from the inner SELECT statement. A single-row subquery uses a single-row operator (>, <, =, <>, etc...). however, multiple-row subqueries use multiple-row operator (IN, ALL, ANY), instead of a single-row operator. The multiple-row comparison operators are: Operator IN ANY ALL Meaning Equal to any member in the list Must be preceded by =, <>, >, <, <=, >=. Compares a value to each value in a list or returned by a query. Evaluates to FALSE if the query returns no rows. Must be preceded by =, <>, >, <, <=, >=. Compares a value to every value in a list or returned by a query. Evaluates to TRUE if the query returns no rows. Example: retrieving all employees are not IT programmers and whose salary is less than that of any IT programmer. SELECT EMPLOYEE_ID, LAST_NAME, JOB_ID, SALARY WHERE SALARY < ANY (SELECT SALARY WHERE JOB_ID = 'IT_PROG' ) AND JOB_ID <> 'IT_PROG'; 12

Example: retrieving all employees whose salary is less than the salary of all employees with a job ID of IT_PROG and whose job is not IT_PROG. SELECT EMPLOYEE_ID, LAST_NAME, JOB_ID, SALARY WHERE SALARY < ALL (SELECT SALARY WHERE JOB_ID = 'IT_PROG' ) AND JOB_ID <> 'IT_PROG'; Example: write a query to retrieve the employee number and last name of all employees who work in a department with any employee whose last name contains the letter u. SELECT EMPLOYEE_ID, LAST_NAME WHERE DEPARTMENT_ID IN ( SELECT DISTINCT DEPARTMENT_ID WHERE LAST_NAME LIKE '%u%' ); 13

Example: write a query to retrieve the last name, department number, and job ID of all employees whose department location ID is 1700. SELECT LAST_NAME, DEPARTMENT_ID, JOB_ID WHERE DEPARTMENT_ID IN ( SELECT DISTINCT DEPARTMENT_ID FROM DEPARTMENTS WHERE LOCATION_ID = 1700 ); 14

Set Operators: Set operators are used to combine the results of two or more component queries into one result. Queries containing set operators are called compound queries. In oracle, there are 4 Set Operators: UNION: return all rows from multiple tables and eliminate any duplicate rows. A B UNION ALL: return all rows from multiple tables including all duplicate rows. INTERSECT: return all rows from multiple tables and eliminate any duplicate rows. A B MINUS: return all rows from multiple tables and eliminate any duplicate rows. A B 15

Example: write a query to retrieve department IDs for departments that do not contain the job ID ST_CLERK. SELECT DEPARTMENT_ID FROM DEPARTMENTS MINUS SELECT DEPARTMENT_ID WHERE JOB_ID = 'ST_CLERK'; Example: write a query to retrieve name and id for all countries that have no departments located in them. SELECT COUNTRY_ID, COUNTRY_NAME FROM COUNTRIES MINUS SELECT COUNTRY_ID, COUNTRY_NAME FROM DEPARTMENTS JOIN LOCATIONS USING (LOCATION_ID) JOIN COUNTRIES USING (COUNTRY_ID); 16

Exercises: 1. Write a query (without using set operators) to retrieve name and id for all countries that have no departments located in them. 2. Write a query to retrieve all employees whose salary is more than the salary of any employee from department 60. 3. Write a query to retrieve first name, last name, and department name, for employees whose salary is more than all their collagenous salaries in the same department. 4. Write a query to retrieve employees whose job has minimum salary 4200 and maximum salary 9000. 5. Write a query to retrieve departments names and cities for all departments that has more than 5 employees. 17