Lesson 4 Week 2JOINS

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

Database Development

G. Mudare

www.belgiumcampus.ac.za
JOINS

2
www.belgiumcampus.ac.za
JOINS
• A single query that accesses data from multiple tables.
• The SQL language supports three distinct types of joins:
➢Inner Joins
➢Outer Joins
➢ Cross Joins

3
www.belgiumcampus.ac.za
INNER JOIN Syntax:
Syntax: SELECT { * | fieldlist }
FROM table1
INNER JOIN table2
ON table1.field1 compoperator table2.field2
The INNER JOIN operator can be used in any FROM clause to combine records from two tables.
INNER JOIN, is also known as an equi-join, and is the most common type of join .
An INNER JOIN returns results that contain the instances that the two tables have in common
Usually in an INNER JOIN a single row from one table is matched with multiple rows in another table
In an INNER JOIN, if none of the rows from one table match any rows in the other table, no rows are
returned
The only rows that are returned in an INNER JOIN are those that have an exact match, according to
the specified criteria, in the other table

4
www.belgiumcampus.ac.za
INNER JOIN Syntax
EMP
DEPT

5
www.belgiumcampus.ac.za
INNER JOIN

6
www.belgiumcampus.ac.za
USING OUTER JOINS
• Outer joins differ from INNER JOINs in that rows that do not have
matches in a joined table can be returned.
• However the conditions are specified in a manner similar to those
from an INNER JOIN.
• The only difference is that the keyword JOIN is preceded by one of
the outer qualifiers.(left, right and full outer joins)
• The qualifier used with the keyword JOIN specifies which table
retains all of its rows,

7
www.belgiumcampus.ac.za
Left outer join

• In a left outer join, all rows are shown from the table on the left of
the JOIN keyword,

8
www.belgiumcampus.ac.za
Left outer join

• In a left outer join, all rows are shown from the table on
the left of the JOIN keyword,
9
www.belgiumcampus.ac.za
Right outer join
• A right outer join includes all of the records from the second (right) of
the two tables, even if there are no matching values for records in the
first.
SELECT DEPT.DEPTNO AS "DEPTNO IN DEPT TABLE",DNAME,ENAME,
JOB,EMP.DEPTNO AS "DEPT NO IN EMP TABLE"
FROM DEPT
RIGHT OUTER JOIN EMP
ON DEPT.DEPTNO = EMP.DEPTNO;

10
www.belgiumcampus.ac.za
Right outer join

A right outer join includes all of the records from the second (right) of the two
tables, even if there are no matching values for records in the first.

11
www.belgiumcampus.ac.za
Full Outer Join

In a full outer join, all rows are retained from both tables.
SELECT DEPT.DEPTNO AS "DEPTNO IN DEPT
TABLE",DNAME,ENAME, JOB,EMP.DEPTNO
AS "DEPT NO IN EMP TABLE“
FROM DEPT
FULL OUTER JOIN EMP
ON DEPT.DEPTNO = EMP.DEPTNO;

12
www.belgiumcampus.ac.za
USING CROSS JOINS
• In a cross join all rows in the left table are matched with all the rows
in the right table AND THE RESULT IS known as a Cartesian Product of
the two tables.
• A cross join can be thought of as an INNER JOIN where there are no
restrictions defined.

13
www.belgiumcampus.ac.za
CROSS JOINS
• To perform a cross join, the first table name is followed by the
keyword CROSS JOIN, which are followed by the second table name.
The keyword ON is not included in the syntax, and there are no
conditions specified in the FROM clause, as shown by the following:
SELECT DEPT.DEPTNO AS "DEPTNO IN DEPT TABLE",DNAME,ENAME,
JOB,EMP.DEPTNO AS "DEPT NO IN EMP TABLE"
FROM DEPT
CROSS JOIN EMP;

14
www.belgiumcampus.ac.za
CROSS JOINS

select dept.deptno
dep_depno,Dname ,
job,emp.deptno
empldeptno
from dept
cross join emp

15
www.belgiumcampus.ac.za
INTRODUCTION TO SUB-QUERIES
• Sub-queries enable you to embed a query inside another query.
• This allows queries to retrieve data with a single step that would
otherwise require several steps.
• The syntax for sub-queries is identical to regular SELECT statements

16
www.belgiumcampus.ac.za
Sub-Queries Used in Expressions
• The simplest use of a sub-query is to return a single value that is used
in an expression.
SELECT title
FROM Titles
WHERE price < (SELECT avg (price) FROM titles );
• This kind of single-valued sub-query can be used anywhere in a query
in place of a single literal value.
• It can even be used in INSERT, DELETE and UPDATE statements

17
www.belgiumcampus.ac.za
Sub-Queries
• A sub-query can be used to control the records returned from a
SELECT statement by controlling which records pass the conditions of
the WHERE clause.
SELECT DISTINCT city
FROM City
WHERE city NOT IN (SELECT distinct city FROM Orders)

The statement returns a list of cities that are in the City table (City column) but
doesn’t exist in the Orders table (ShipCity column).

18
www.belgiumcampus.ac.za
Sub-Queries
• Customer contact information for the country with the fewest
number of orders:
SELECT Country, City, FirstName, LastName
FROM tblCustomers
WHERE Country = (SELECT TOP 1 Country FROM tblCustomers C
INNER JOIN tblOrders O
ON C.CustomerIDPK = O.CustomerIDFK
GROUP BY Country
ORDER BY count(*) asc)

19
www.belgiumcampus.ac.za
Use of a Sub-query in the HAVING clause
• Sub-query to find the number of orders a customer has ordered
where the City the customer resides in, is not Pretoria.
SELECT LastName, FirstName, count(OrdersIDPK) customercount
FROM tblCustomers c
INNER JOIN tblOrders o
ON c.CustomerIDPK = o.CustomerIDFK
GROUP BY LastName, FirstName
HAVING c.LastName in
(SELECT LastName FROM tblCustomers WHERE City <> 'Pretoria')

20
www.belgiumcampus.ac.za
Sub-queries that Are Used with
IN or NOT IN
• The result of a sub-query introduced with IN (or with NOT IN) is a list
of zero or more values.
• After the sub-query returns the result, the outer query makes use of
it.
• USE Pubs
SELECT Pub_name
FROM Publishers
WHERE Pub_id IN (SELECT Pub_id FROM Titles WHERE Type = 'business’ ) ;

21
www.belgiumcampus.ac.za
Sub-queries that Are Used with
Comparison Operators
• Comparison operators that introduce a sub-query can be modified
with the keyword ALL or ANY
• Sub-queries introduced with a modified comparison operator return a
list of zero or more values and can include a GROUP BY or HAVING
clause.
• These sub-queries can be restated with EXISTS. .
• The ALL and ANY keywords each compare a scalar value with a single-
column set of values.
• The ALL keyword applies to every value,
• The ANY keyword applies to at least one value.

22
www.belgiumcampus.ac.za
Here the greater than (>) comparison operator is used with the
ANY keyword:

• USE Pubs
SELECT Title
FROM Titles
WHERE Advance > ANY
( SELECT Advance
FROM Publishers
INNER JOIN Titles
ON Titles.Pub_id = Publishers.Pub_id
WHERE Pub_name = 'Algodata Infosystems’ );

23
www.belgiumcampus.ac.za
Sub-queries that Are Used
with Comparison Operators

24
www.belgiumcampus.ac.za
Sub-queries that Are Used
with Comparison Operators

25
www.belgiumcampus.ac.za
Sub-queries that Are Used
with Comparison Operators

26
www.belgiumcampus.ac.za
27
www.belgiumcampus.ac.za
28
www.belgiumcampus.ac.za
29
www.belgiumcampus.ac.za
30
www.belgiumcampus.ac.za
Subqueries that Are Used with EXISTS and
NOT EXISTS
• When a subquery is introduced with the keyword EXISTS, it functions
as an existence test.
• The WHERE clause of the outer query tests for the existence of rows
returned by the subquery.
• The subquery does not actually produce any data; instead, it returns a
value of TRUE or FALSE.

31
www.belgiumcampus.ac.za
Subqueries that Are Used with EXISTS and
NOT EXISTS
To determine the result of this query, consider each Employee's name in
turn.
In this case, the first Employeer's name is KING, which has an EMPNO 1389.
Are there any rows in the Titles table in which Pub_id is 7839 and the
DNAME is ACCOUNTING?
If so, KING should be one of the values selected. The same process is
repeated for each of the other Employees' names.
The NOT EXISTS keywords works like EXISTS, except the WHERE clause in
which NOT EXISTS is used is satisfied if the sub-query returns no rows.

32
www.belgiumcampus.ac.za
Subqueries that Are Used with EXISTS and
NOT EXISTS
• Let’s take some examples to understand how EXISTS operator works.
• Using EXISTS with a subquery returns NULL example
• See the following customers table from the sample database.

33
www.belgiumcampus.ac.za
Subqueries that Are Used with
EXISTS and NOT EXISTS
SELECT
customer_id,
first_name,
last_name
FROM
sales.customers
WHERE
EXISTS (SELECT NULL)
ORDER BY
first_name,
last_name;

34
www.belgiumcampus.ac.za
Subqueries that Are Used with EXISTS and NOT
EXISTS

35
www.belgiumcampus.ac.za
Subqueries that Are Used with
EXISTS and NOT EXISTS
• In this example, the subquery returned a result set that contains NULL
which also causes the EXISTS operator to evaluate to TRUE.
• B) Using EXISTS with a correlated subquery example
• Consider the following customers and orders tables

36
www.belgiumcampus.ac.za
The following example finds all customers who
have placed more than two orders:
• Select customer_id,
first_name,
last_name FROM
sales.customers c
WHERE EXISTS (
SELECT COUNT (*)
FROM sales.orders o
WHERE
customer_id = c.customer_id
GROUP BY
customer_id
HAVING COUNT (*) > 2
)
ORDER BY first_name, last_name;
37
www.belgiumcampus.ac.za
Subqueries that Are Used with
EXISTS and NOT EXISTS

SELECT Ename ,DeptNO


FROM emp
WHERE EXISTS
( SELECT *
FROM Dept
WHERE dept.deptno = emp.deptno
AND DNAME = ‘ACCOUNTING’) ;

38
www.belgiumcampus.ac.za
Subqueries that Are Used with NOT
EXISTS
The NOT EXISTS keywords work like EXISTS,
except the WHERE clause in which NOT EXISTS is
Excluded in not EXISTS used is satisfied if the sub-query returns no rows for the stated .

39
www.belgiumcampus.ac.za
Subqueries that Are Used
with NOT EXISTS
The NOT EXISTS keywords work like EXISTS,
except the WHERE clause in which NOT EXISTS is
used is satisfied if the sub-query returns no rows for the stated .

40
www.belgiumcampus.ac.za
COMMON TABLE EXPRESSIONS (CTE)
• A common table expression (CTE) – that can be a handy alternative to
derived tables and views
• Create named result sets to reference from within your SELECT,
INSERT, UPDATE, and DELETE statements
• CTE can be replacement for many sub-queries
• they bring to T-SQL query syntax simplicity
• Common Table Expressions in your code is simple,
• fetches a set of data via CTE that you can use in your queries.

41
www.belgiumcampus.ac.za
CTE Syntax
• [WITH <CTE_definition> [,...n]]
• <SELECT, INSERT, UPDATE, or DELETE statement that
• calls the CTEs>
• <CTE_definition>::=
• CTE_name [(column_name [,...n ])]
• AS
• (CTE_query)

42
www.belgiumcampus.ac.za
COMMON TABLE EXPRESSIONS (CTE)
• WITH TitleCount (authorID, titleCount) AS
(
SELECT au_id, COUNT(title_id)
FROM titleauthor
GROUP BY au_id
)
SELECT au_id, au_lname, au_fname, titleCount
FROM authors a
INNER JOIN TitleCount
ON TitleCount.authorID = a.au_id

43
www.belgiumcampus.ac.za
COMMON TABLE EXPRESSIONS (CTE)
WITH ProductSold (ProductID, TotalSold)
AS
(
SELECT ProductID, SUM(OrderQty)
FROM Sales.SalesOrderDetail
GROUP BY ProductID
)
SELECT ps.ProductID, p.Name, p.ProductNumber,
ps.TotalSold
FROM Production.Product AS p
• INNER JOIN ProductSold AS ps
• ON p.ProductID = ps.ProductID

44
www.belgiumcampus.ac.za
COMMON TABLE EXPRESSIONS (CTE
• WITH clause precedes the SELECT statement that references the CTE.
• first line of the WITH clause includes the name of the CTE
(ProductSold)
• AS keyword, followed by the CTE query in parentheses
• SELECT statement that follows the WITH clause references the CTE by
name
• One advantage to using common table expressions is that you can
reference a CTE multiple times in the calling statement

45
www.belgiumcampus.ac.za
Creating multiple CTEs in a WITH
clause
WITH (SELECT ProductID, AVG(OrderQty)
Cost (ProductID, AvgCost) FROM Sales.SalesOrderDetail
AS GROUP BY ProductID)
(SELECT ProductID, AVG(StandardCost) SELECT p.ProductID, p.Name,
FROM Production.ProductCostHistory (AvgCost * AvgSold)AS TotalCost
GROUP BY ProductID), FROM Sold s
Sold (ProductID, AvgSold) INNER JOIN Production.Product p
AS ON s.ProductID = p.ProductID
INNER JOIN Cost c
ON p.ProductID = c.ProductID

46
www.belgiumcampus.ac.za
Creating multiple CTEs in a WITH clause
• You can define multiple CTEs within the WITH clause, and also define CTEs that reference the
CTEs defined before it.
WITH
Cost (ProductID, AvgCost)
AS
(SELECT ProductID, AVG(StandardCost)
FROM Production.ProductCostHistory
GROUP BY ProductID),

Total (ProductID, TotalCost)


AS
(SELECT c.ProductID, (AvgCost * AvgSold)
FROM Cost c

47
www.belgiumcampus.ac.za

You might also like