0% found this document useful (0 votes)
38 views48 pages

DB-Basics-Subqueries-and-JOINs

Here is an inner join query to display address information for the first 50 employees from the SoftUni database who have an address in the Addresses table joined with the Towns table: SELECT e.FirstName, e.LastName, a.AddressText, t.Name AS Town FROM Employees AS e INNER JOIN Addresses AS a ON e.AddressID = a.AddressID INNER JOIN Towns AS t ON a.TownID = t.TownID LIMIT 50

Uploaded by

Hường Vũ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views48 pages

DB-Basics-Subqueries-and-JOINs

Here is an inner join query to display address information for the first 50 employees from the SoftUni database who have an address in the Addresses table joined with the Towns table: SELECT e.FirstName, e.LastName, a.AddressText, t.Name AS Town FROM Employees AS e INNER JOIN Addresses AS a ON e.AddressID = a.AddressID INNER JOIN Towns AS t ON a.TownID = t.TownID LIMIT 50

Uploaded by

Hường Vũ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Joins, Subqueries, CTEs

and Indices
Table of Content
1. Joins
2. Subqueries
3. Common Table Expressions (CTE)
4. Indices

2
JOINS
Gathering Data From Multiple Tables
Data from Multiple Tables
 Sometimes you need data from several tables:
Employees Departments
EmployeeName DepartmentID DepartmentID DepartmentName
Edward 3 3 Sales
John NULL 4 Marketing
5 Purchasing

EmployeeName DepartmentID DepartmentName


Edward 3 Sales

4
Types of Joins
 Inner joins
 Left, right and full outer joins
 Cross joins

7
INNER vs. OUTER Joins
 Inner join
 A join of two tables returning only rows matching the join
condition
 Left (or right) outer join
 Returns the results of the inner join as well as unmatched rows
from the left (or right) table
 Full outer join
 Returns the results of an inner join along with all unmatched rows

8
Inner Join
Employees Departments
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales
270 NULL 4 Marketing
5 Purchasing

Result
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales

9
Inner Join Syntax

SELECT * FROM Employees AS e


Depatments Table
INNER JOIN Departments AS d
ON e.DepartmentID = d.DepartmentID

Join Condition

10
Left Outer Join
Employees Departments
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales
270 NULL X 4 Marketing
5 Purchasing

Result
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales
270 NULL NULL NULL

11
Left Outer Join Syntax

SELECT * FROM Employees AS e Table Depatments


LEFT OUTER JOIN Departments AS d
ON e.DepartmentID = d.DepartmentID

Join Condition

12
Right Outer Join
Employees Departments
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales
270 NULL X 4 Marketing
X 5 Purchasing

Result
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales
NULL NULL 4 Marketing
NULL NULL 5 Purchasing
13
Right Outer Join Syntax

SELECT * FROM Employees AS e Depatments Table


RIGHT OUTER JOIN Departments AS d
ON e.DepartmentID = d.DepartmentID
Join Condition

14
Full Join
Employees Departments
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales
270 NULL X 4 Marketing
X 5 Purchasing

Result
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales
270 NULL NULL NULL
NULL NULL 4 Marketing
NULL NULL 5 Purchasing
15
Full Join Syntax

SELECT * FROM Employees AS e


Depatments Table
FULL JOIN Departments AS d
ON e.DepartmentID = d.DepartmentID
Join Condition

16
Cross Join
Employees Departments
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales
270 NULL 4 Marketing
5 Purchasing
Result
EmployeeID DepartmentID DepartmentID DepartmentName
263 3 3 Sales
263 3 4 Marketing
263 3 5 Purchasing
270 NULL 3 Sales
270 NULL 4 Marketing
270 NULL 5 Purchasing
17
Cross Join Syntax

SELECT * FROM Employees AS e Depatments Table


CROSS JOIN Departments AS d
No Join Conditions

18
Join Overview

Sally 13 18 Accounting
John 10 10 Marketing
Michael 22 12 HR
Bob 11 22 Engineering
Robin 7 8 Sales
Jessica 15 7 Executive

Relation

19
Join Overview

18 Accounting
Sally 13
John 10 10 Marketing
12 HR
Michael 22 22 Engineering
8 Sales
Bob 11
Robin 7 7 Executive
Jessica 15

20
Join Overview
 Inner Join
18 Accounting
Sally 13
John 10 10 Marketing
12 HR
Michael 22 22 Engineering
8 Sales
Bob 11
Robin 7 7 Executive
Jessica 15

21
Join Overview
 Left Outer Join
18 Accounting
Sally 13 NULL NULL
John 10 10 Marketing
12 HR
Michael 22 22 Engineering
8 Sales
Bob 11 NULL NULL
Robin 7 7 Executive
Jessica 15 NULL NULL

22
Join Overview
 Right Outer Join
NULL NULL 18 Accounting
Sally 13
John 10 10 Marketing
NULL NULL 12 HR
Michael 22 22 Engineering
NULL NULL 8 Sales
Bob 11
Robin 7 7 Executive
Jessica 15

23
Join Overview
 Full Outer Join
NULL NULL 18 Accounting
Sally 13 NULL NULL
John 10 10 Marketing
NULL NULL 12 HR
Michael 22 22 Engineering
NULL NULL 8 Sales
Bob 11 NULL NULL
Robin 7 7 Executive
Jessica 15 NULL NULL

24
Join Overview
 Negated Left Outer Join
18 Accounting
Sally 13 NULL NULL
John 10 10 Marketing
12 HR
Michael 22 22 Engineering
8 Sales
Bob 11 NULL NULL
Robin 7 7 Executive
Jessica 15 NULL NULL

25
Join Overview
 Negated Right Outer Join
NULL NULL 18 Accounting
Sally 13
John 10 10 Marketing
NULL NULL 12 HR
Michael 22 22 Engineering
NULL NULL 8 Sales
Bob 11
Robin 7 7 Executive
Jessica 15

26
Join Overview
 Negated Outer Join
NULL NULL 18 Accounting
Sally 13 NULL NULL
John 10 10 Marketing
NULL NULL 12 HR
Michael 22 22 Engineering
NULL NULL 8 Sales
Bob 11 NULL NULL
Robin 7 7 Executive
Jessica 15 NULL NULL

27
Problem: Addresses with Towns
 Display address information of all employees in "SoftUni"
database. Select first 50 employees.
 The exact format of data is shown below.
 Order them by FirstName, then by LastName (ascending).
 Hint: Use three-way join.

28
Solution: Addresses with Towns

SELECT TOP 50 e.FirstName, e.LastName,


t.Name as Town, a.AddressText Employees Table
FROM Employees e
JOIN Addresses a ON e.AddressID = a.AddressID
JOIN Towns t ON a.TownID = t.TownID
ORDER BY e.FirstName, e.LastName
Towns Table

29
Problem: Sales Employees
 Find all employees that are in the "Sales" department. Use
"SoftUni" database.
 Follow the specified format:

 Order them by EmployeeID

30
Solution: Sales Employees

SELECT e.EmployeeID, e.FirstName, e.LastName,


d.Name AS DepartmentName
FROM Employees e Departments Table
INNER JOIN Departments d
ON e.DepartmentID = d.DepartmentID
WHERE d.Name = 'Sales'
ORDER BY e.EmployeeID

31
Problem: Employees Hired After
 Show all employees that:
 Are hired after 1/1/1999
 Are either in "Sales" or "Finance" department

 Sorted by HireDate (ascending).

32
Solution: Employees Hired After

SELECT e.FirstName, e.LastName, e.HireDate,


d.Name as DeptName
FROM Employees e
INNER JOIN Departments d
ON (e.DepartmentId = d.DepartmentId
AND e.HireDate > '1/1/1999'
AND d.Name IN ('Sales', 'Finance'))
ORDER BY e.HireDate ASC
Complex Join Condition

33
Problem: Employee Summary
 Display information about employee's manager and employee's
department .
 Show only the first 50 employees.
 The exact format is shown below:

 Sort by EmployeeID (ascending).

34
Solution: Employee Summary

SELECT TOP 50 Cross Table Selection


e.EmployeeID,
e.FirstName + ' ' + e.LastName AS EmployeeName,
m.FirstName + ' ' + m. LastName AS ManagerName,
d.Name AS DepartmentName
FROM Employees AS e
Self-join
LEFT JOIN Employees AS m ON m.EmployeeID = e.ManagerID
LEFT JOIN Departments AS d ON d.DepartmentID =
e.DepartmentID
ORDER BY e.EmployeeID ASC Table Departments

35


Subqueries
Query Manipulati on on Multiple Levels
Subqueries
 Use a query’s result as data for another query
Employees
EmployeeID Salary
Query
59 19,000
71 43,300
... ...
Subquery
DepartmentID Name
WHERE DepartmentID IN 10 Finance

37
Subquery Syntax

SELECT FROM Employees AS e


WHERE e.DepartmentID IN
(
SELECT d.DepartmentID
Table Depatments
FROM Deparments AS d
WHERE d.Name = 'Finance'
)
Subquery
38
Problem: Min Average Salary
 Display lowest average salary of all departments.
 Calculate average salary for each department.
 Then show the value of smallest one.

39
Solution: Min Average Salary

SELECT
MIN(a.AverageSalary) AS MinAverageSalary
FROM
(
Subquery SELECT e.DepartmentID,
AVG(e.Salary) AS AverageSalary
FROM Employees AS e Table Employees
GROUP BY e.DepartmentID
) AS a

40
Common Table Expressions
Reusable Subqueries
Common Table Expressions
 Common Table Expressions (CTE) can be considered as "named
subqueries".
 They could be used to improve code readability and code reuse.
 Usually they are positioned in the beginning of the query.

WITH CTE_Name (ColumnA, ColumnB…)


AS
(
-- Insert subquery here.
)
42
CTE Syntax

WITH Employees_CTE
(FirstName, LastName, DepartmentName)
AS
(
SELECT e.FirstName, e.LastName, d.Name
FROM Employees AS e
LEFT JOIN Departments AS d ON
d.DepartmentID = e.DepartmentID
)

SELECT FirstName, LastName, DepartmentName


FROM Employees_CTE
43
Indexes
Clustered and Non-Clustered Indexes
Indices
 Indices speed up searching of values in a certain column or
group of columns.
 Usually implemented as B-trees.

 Indices can be built-in the table (clustered) or stored externally


(non-clustered).
 Adding and deleting records in indexed tables is slower!
 Indices should be used for big tables only (e.g. 50 000 rows).

45
Clustered Indexes
 Clustered index is actually the data itself.
 Very useful for fast execution of WHERE, ORDER BY and GROUP BY
clauses.
 Maximum 1 clustered index per table
 If a table has no clustered index, Keys
its data rows are stored in an
0-99 100-199 200-299
unordered structure (heap).

Data ☰ ☰ ☰ ☰ ☰ ☰ ☰

46
Non-Clustered Indexes (1)
 Useful for fast retrieving a single record or a range of records
 Maintained in a separate structure in the DB
 Tend to be much narrower than the base table
 Can locate the exact record(s) with less I/O

 Has at least one more intermediate level than the clustered


index
 Much less valuable if table doesn’t have a clustered index

47
Non-Clustered Indexes (2)
 A non-clustered index has pointers to the actual data rows
(pointers to the clustered index if there is one).

Keys Index

0-99 100-199 200-299 Range 1 Range 2 Range 3

Data ☰ ☰ ☰ ☰ ☰ ☰ ☰ Links ☰ ☰ ☰ ☰ ☰ ☰ ☰

48
Indices Syntax

Index Type

CREATE NONCLUSTERED INDEX


IX_Employees_FirstName_LastName
ON Employees(FirstName, LastName)

Table Name Columns

49
Summary
1. Joins
SELECT * FROM Employees AS e
JOIN Departments AS d ON
d.DepartmentId = e.DepartmentID

2. Subqueries are used to nest queries.


3. CTE's improve code reuse and
readability.
4. Indices improve SQL search performance
if used properly.
50

You might also like