SlideShare a Scribd company logo
1 of 94
Download to read offline
MODULE 7: WORKING WITH MULTIPLE
TABLES
SQL and Scripting Training
(C) 2020-2021 Highervista, LLC 1
2
TOPICS
Introduction to Joins
Joins and the relational database
structure
Joins and aliases
Inner join, left outer join, and right outer
join
Joining more than two tables
Adding calculations to queries
Types of functions in SQL
String functions
Date functions
Aggregate functions
Using the WHERE and HAVING clauses
with functions
Grouping by multiple columnssubqueries
and aggregate functions
SELECT statement subqueries
WHERE clause subqueries
Summary
INTRODUCTION TO JOINS
SQL and Scripting
Training
4
ERD OF THE STUNES DATABASE
5
INTRODUCTION TO JOINS
A JOIN is a command that combines fields in two or more tables of a relational database.
As an example: For the sTunes database, it would be logical to query fields from both the
Invoices and Customers tables, since customers can have invoices.
6
INTRODUCTION TO JOINS
Since CustomerId is the primary key of the Customers table and there is a similar field of the
same name in the Invoices table, there is a linkage between these two tables.
Both tables can be merged on the CustomerId field for each.
Note: This type of join is called
an INNER JOIN. We′ll discuss
other types of joins.
7
INTRODUCTION TO JOINS
The query begins with a SELECT * (for
all fields). This will provide fields from
both tables (22 total fields).
The ON keyword provides the linkage
between the two tables. The resulting
table looks like this:
JOINS AND THE RELATIONAL
DATABASE STRUCTURE
SQL and Scripting
Training
9
HOW JOINS INTERACT WITH THE RELATIONAL
DATABASE STRUCTURE
When examining the output from the prior Join command, you can see a repeating set of
information for customer 1 (Luis).
Looking back at an ERD, you can say that this customer (Luis) has a 1:M relationship with the
Invoices table.
Let′s examine the ERD for the sTunes db. Note that the ERD is in an MS/Access type of ERD
notation.
10
STUNES ERD
11
STUNES ERD
The database is normalized (through 3NF).
Examine the linkages between tables (PK to FK).
As noted earlier, the relationship between each pair of tables is bidirectional. It can be
read in either direction.
12
USING JOINS WITH AN ALIAS
Since two tables in any given database may have fields with identical names,
when creating joins it is necessary to specify the table name with the associated
field name.
Aliases reduce the amount of typing required and serve to help readability.
13
IDENTICAL JOINS
SELECT
*
FROM
invoices
INNER JOIN
customers
ON
invoices.CustomerID =
customers.CustomerID
SELECT
*
FROM
Invoices AS i
INNER JOIN
Customers AS c
ON
i.CustomerID = c.CustomerID
14
USING ALIASES WITH FIELD NAMES:
EXAMPLE
SELECT
c.LastName,
c.FirstName,
i.InvoiceID,
i.CustomerID,
i.InvoiceDate,
i.Total
FROM
invoices AS i
INNER JOIN
customers AS c
ON
i.CustomerId = c.CustomerID
ORDER BY
c.Lastname
15
USING ALIASES WITH FIELD NAMES:
RESULTS
16
JOIN TYPES AND THEIR DIFFERENCES
What happens if the data from the tables joined doesn’t match up?
­ For example, suppose a customer deleted his customer database record (removing his record from the
Customers table).
­ Because the company is required to keep financial records, the invoices for the customer were not deleted.
­ It is not unusual to find discrepancies in databases, and you must decide whether queries should include or
exclude data that does not match up.
17
EXAMPLE TABLES (NOT THE STUNES DB)
Discrepancies
1. Invoices table shows someone with a
customer ID of 6 who made a purchase
on 5/1/2017, but this customer does not
show up on the Customers table.
2. It appears that customer ID 1 and
customer ID 5 (on the Customers table)
never made a purchase (they’re not on
the Invoices table).
3. We’ll look at how this is handled with
various JOIN types.
18
INNER JOIN: HOW ARE DISCREPANCIES HANDLED?
Inner Join—Only returns matching records. Any unmatched data from either table is
ignored.
19
INNER JOIN: HOW ARE DISCREPANCIES HANDLED?
Note: In this example, the Inner Join
will join four common records.
20
INNER JOIN: HOW ARE DISCREPANCIES HANDLED?
SELECT
i.InvoiceId,
c.CustomerId,
c.LastName,
c.Address,
i.InvoiceDate,
i.BillingAddress,
i.total
FROM
invoices AS i
INNER JOIN
customers AS c
ON
i.CustomerId = c.CustomerId
21
LEFT OUTER JOIN: HOW ARE DISCREPANCIES
HANDLED?
Note: The concept of a left table and a
right table depends entirely on the order
that tables are listed in the JOIN
statement.
22
LEFT OUTER JOIN: HOW ARE DISCREPANCIES
HANDLED?
Note: With the LEFT OUTER JOIN, everything in the Invoices table will be
displayed. Only common records in the Customers table will be displayed.
23
LEFT OUTER JOIN: HOW ARE DISCREPANCIES
HANDLED?
Can you think of a business case for
displaying all invoices and only
customer data related to invoices?
SELECT
i.InvoiceId,
c.CustomerId,
c.Name,
c.Address,
i.InvoiceDate,
i.BillingAddress,
i.Total
FROM
invoices AS i
LEFT OUTER JOIN
customers AS c
ON
i.CustomerId = c.CustomerId
24
JOIN INVOICES AND
CUSTOMERS TABLE
25
RIGHT OUTER JOIN: HOW ARE DISCREPANCIES
HANDLED?
Note: For LEFT OUTER JOIN or
RIGHT OUTER JOIN, you can use
LEFT JOIN or RIGHT JOIN (same
results).
Note: RIGHT OUTER JOINs are not supported in SQLite
26
RIGHT OUTER JOIN: HOW ARE DISCREPANCIES
HANDLED?
Note: With the RIGHT OUTER JOIN, everything in the Customers table
will be displayed. Only common records in the invoices table will be
displayed.
27
LEFT OUTER JOIN: HOW ARE DISCREPANCIES
HANDLED?
Can you think of a business case for
displaying all customers and only invoice
data related to customers?
SELECT
i.InvoiceId,
c.CustomerId,
c.Name,
c.Address,
i.InvoiceDate,
i.BillingAddress,
i.Total
FROM
invoices AS i
RIGHT OUTER JOIN
customers AS c
ON
i.CustomerId = c.CustomerId
28
INNER JOINS WITH MORE THAN TWO
TABLES
Joins can combine two or more tables.
Adding additional tables using joins is straightforward: It follows the same pattern as inner
joins.
Review database schema on next slide: There is a relationship between Invoices, Customers,
and Employee tables.
­ Note: Look at SupportRepId field (Customers table) and the EmployeeId field (Employees table).
29
INNER JOINS WITH MORE THAN TWO
TABLES
The Invoices table is
related to the Customers
table (bidirectional
relationship).
The Customers table is
related to the Employees
table (bidirectional
relationship).
30
INNER JOINS WITH MORE THAN TWO
TABLES
When using two or more
tables in a Join, think
about the fields that you
need from each table.
31
INNER JOINS WITH MORE THAN TWO
TABLES SELECT
e.FirstName,
e.LastName
e.EmployeeId,
c.FirstName,
c.LastName,
c.SupportRepID,
i.CustomerId,
i.Total
FROM
invoices AS i
INNER JOIN
customers AS c
ON
i.CustomerId = c.CustomerId
INNER JOIN
employees AS e
ON
c.SupportRepId = e.EmployeeId
ORDER BY
i.Total DESC
LIMIT 10
32
INNER JOINS WITH
MORE THAN TWO
TABLES
33
SQL
SELECT
e.FirstName,
e.LastName,
e.EmployeeId,
c.FirstName,
c.LastName,
c.SupportRepId,
i.CustomerId,
i.Total
FROM
invoices AS i
INNER JOIN
customers AS c
ON
i.CustomerId = c.CustomerId
INNER JOIN
employees AS e
ON
c.SupportRepId = e.EmployeeId
ORDER BY
i.Total DESC
LIMIT 10
34
USING LEFT OUTER JOINS WITH NULL, IS, AND
NOT
Left Outer Join—shows everything from the left table and all matching information from the
right table.
When looking at the artists and albums tables in the sTunes database, if you want to
generate a list of all artists who do not have an album, what is the process?
35
USING LEFT OUTER JOINS WITH NULL, IS, AND
NOT
A Left Outer Join provides a list of all artists along with any associated albums for artists
with albums.
The Left Outer Join will fill in any fields that do not have album titles with NULL values.
36
USING LEFT OUTER JOINS WITH NULL, IS,
AND NOT SELECT
ar.ArtistId AS [ArtistId From Artist Table],
al.ArtistId AS [ArtistId From Albums Table],
ar.Name AS [Artist Name],
al.Title AS [Album Title]
FROM
artists AS ar
LEFT OUTER JOIN
albums AS al
ON
ar.ArtistId = al.ArtistId
37
USING LEFT OUTER JOINS WITH NULL, IS,
AND NOT
SELECT
ar.ArtistId AS [ArtistId From Artist Table],
al.ArtistId AS [ArtistId From Albums
Table],
ar.Name AS [Artist Name],
al.Title AS [Album Title]
FROM
artists AS ar
LEFT OUTER JOIN
albums AS al
ON
ar.ArtistId = al.ArtistId
Note: The result will include artists with albums and artist without
albums (NULL).
38
USING LEFT OUTER JOINS WITH NULL, IS,
AND NOT SELECT
ar.ArtistId AS [ArtistId From Artist Table],
al.ArtistId AS [ArtistId From Albums
Table],
ar.Name AS [Artist Name],
al.Title AS [Album Title]
FROM
artists AS ar
LEFT OUTER JOIN
albums AS al
ON
ar.ArtistId = al.ArtistId
WHERE
al.ArtistId IS NULL
Note: To generate a report that shows artists who
do not have albums (IS NULL), include a
comparison statement where the ArtistId on the
Albums table is NULL.
Use (NOT NULL) to return only values
that were not NULL.
39
TURNING A RIGHT JOIN INTO A LEFT
JOIN
Since RIGHT OUTER JOINS are not supported in SQLite, keep in mind that:
40
DAY 7, ASSIGNMENT 2: IDENTIFY PK, FK,
CREATE INNER JOIN
Use
Using the Genres table, create a third inner
join to include the Name field from the table
in your result set.
Create
Create an inner join between the Albums and
Tracks tables and display the album names and
track names in a single result set.
Identify Identify PKs and FKs in other tables that are
associated to the Tracks table.
Use Using the sTunes ERD, view the Tracks table.
ADDING CALCULATIONS TO
QUERIES
SQL and Scripting
Training
42
ADDING CALCULATIONS TO QUERIES
Calculations, like counting the number of records returned, can be performed by
adding functions to queries.
The function COUNT ( ) can count a given field, like LastName. You can put the results
in a temporary field such as NameCount.
SELECT
COUNT (LastName) AS [NameCount]
FROM
customers
WHERE
LastName LIKE ‘B%’
TYPES OF FUNCTIONS IN SQL
SQL and Scripting
Training
44
FUNCTIONS IN SQL
Functions are special keywords that accept certain parameters,
perform an operation (such as a calculation or modification of the
data in a field), and return the result of that operation as a value.
There is a list of all SQLite functions on the SQLite website.
Note: Other DBMSs may have an extended set of
functions.
45
FUNCTIONS
• String functions modify
character and text-based
data.
• Date functions modify time
and date data.
• Aggregate functions
perform mathematical
operations.
46
FUNCTIONS
• Functions in SQL operate similarly to the way functions operate
in a spreadsheet.
• If you’ve ever used Excel functions, there is a ″pop-up″ style
definitions box that prompts the user for parameters.
• In SQL, you will need to supply the parameters when calling the
function.
STRING FUNCTIONS
SQL and Scripting
Training
48
STRING FUNCTIONS: EXAMPLE
Note: NVARCHAR is a variable character data format.
The following query would return all names with mailing addresses in the United States:
SELECT
FirstName,
LastName,
Address
FROM
customers
WHERE
Country = ‘USA’
Problem: Name data is split into parts in the database.
49
CONCATENATING STRINGS OF TEXT
Joining fields is known as concatenation.
To add two fields together, use the double pipe symbol ||
For example:
SELECT
FirstName || LastName
FROM
customers
WHERE
CustomerId = 1
50
CONCATENATING STRINGS OF TEXT
Another example:SELECT
FirstName,
LastName,
FirstName || ‘ ‘ || LastName
FROM
customers
WHERE
Country = “USA”
51
USING MULTIPLE CONCATENATIONS
Using multiple concatenations, you can create a one-line name and address list for all
customers.
SELECT
FirstName || ‘ ‘ || LastName || ‘
‘ || Address || ‘, ‘ || City || ‘, ‘ || State || ‘
‘ || PostalCode AS [MainlingAddress}
FROM
customers
WHERE
Country = “USA”
52
TRUNCATING TEXT
You can separate or truncate text to create more uniformity in the
output.
Remember that users can input inconsistencies or errors in database
fields. Using truncation is one tool to clean up how data looks in
reports.
You can use LENGTH ( ) to examine how a given value was entered in
a field.
SELECT
PostalCode,
LENGTH(PostalCode) AS [Postal
Code Length]
FROM
customers
WHERE
Country = “USA”
53
TRUNCATING TEXT
Since there are different sizes in the field, you can use another function SUBSTR() to
substring the field value and place the output on the report.
More detail on the SUBSTR ( ) function:
54
TRUNCATING TEXT: POSTAL CODE
SELECT
PostalCode,
SUBSTR(PostalCode, 1, 5) AS [Five Digit Postal Code]
FROM
customers
WHERE
Country = “USA”
55
MORE STRING FUNCTIONS: UPPER( ) AND
LOWER( )
56
UPPER AND LOWER EXAMPLE
SELECT
FirstName as [First Name Unmodified],
UPPER(FirstName) as [First Name in UPPERCASE],
LOWER(FirstName) as [First Name in lowercase],
UPPER(FirstName) || ‘ ‘ || UPPER(LastName) AS [Full Name in
UPPERCASE]
FROM
customers
DATE FUNCTIONS
SQL and Scripting
Training
58
DATE FUNCTIONS
Date functions allow you to
manipulate data stored in various
date and time formats.
In sTunes, date information is stored
in DATETIME format: YYYY-MM-DD
HH:MM:SS
All timecodes not being used are
stored as 00:00:00
Two date functions (out of several)
59
STRFTIME FUNCTION—ARGUMENTS IN ORDER:
FORMAT, TIMESTRING, MODIFIER (OPTIONAL)
60
STRFTIME FUNCTION—ARGUMENTS IN ORDER:
FORMAT, TIMESTRING, MODIFIER (OPTIONAL)
61
STRFTIME FUNCTION—ARGUMENTS IN
ORDER: FORMAT, TIMESTRING, MODIFIER
(OPTIONAL)
62
STRFTIME EXAMPLE
SELECT
STRFTIME(‘The Year is: %Y The Day
is: %d The Month is %m’, ‘2011-05-22’)
AS [Text with Conversion Specifications]
63
STRFTIME EXAMPLE—CALCULATE EMPLOYEE′S
AGE
SELECT
LastName,
FirstName,
STRFTIME(‘%Y-%m-%d’,BirthDate) AS
[Birthday No Timecode],
STRFTIME(‘%Y-%m-%d’,’now’) –
STRFTIME(‘%Y-%m-%d’, BirthDate) AS [Age]
FROM
employees
ORDER BY
Age
AGGREGATE FUNCTIONS
SQL and Scripting
Training
65
AGGREGATE FUNCTIONS
Aggregate functions can turn a
range of numbers into a single
data point based on a variety of
mathematical functions.
Previously, we used the COUNT (
) function to find the total number
of customers.
Additional aggregate functions
(not a complete list):
66
AGGREGATE FUNCTIONS: EXAMPLE
SELECT
SUM(Total) AS TotalSales,
AVG(Total) AS AverageSales,
MAX(Total) AS MaximumSale,
MIN(Total) AS MinSale,
COUNT(*) AS SalesCount
FROM
invoices
67
NESTING FUNCTIONS WITH THE ROUND (
) FUNCTION
A nested function is a function contained within another function.
One reason that you want to nest functions is to further modify the format of the inner
function.
For example, if you use the AVG ( ) function, you will see too many decimal places. You
can use the ROUND ( ) function to limit the number of decimal places.
68
NESTING FUNCTIONS WITH THE ROUND (
) FUNCTION
SELECT
AVG (Total) AS [Average Sales],
ROUND(AVG(Total), 2) AS [Rounded Average Sales]
FROM
invoices
Note: When using the ROUND ( )
function with monetary values, be
careful of rounding up, since this may
change intermediary calculations!
USING THE WHERE AND HAVING
CLAUSES WITH FUNCTIONS
SQL and Scripting
Training
70
USING AGGREGATE FUNCTIONS WITH THE
GROUP BY CLAUSE
A useful feature of aggregate functions is their ability to calculate subtotals or
aggregates for different groups of data.
SELECT
BillingCity,
AVG(Total)
FROM
invoices
ORDER BY
BillingCity
Something is wrong!?!?
71
USING AGGREGATE FUNCTIONS WITH THE
GROUP BY CLAUSE
Incorrect: A global average of all cities is calculated and ′Delhi′ is the first in the db.
To correct, you need a GROUP BY clause.
SELECT
BillingCity,
AVG(Total)
FROM
invoices
GROUP BY
BillingCity
ORDER BY
BillingCity
72
HAVING CLAUSES WITH GROUPED QUERIES
Adding criteria to a grouped query works like previous queries.
The WHERE clause allows you to add new criteria.
73
AGGREGATE FUNCTIONS: IDENTIFYING AN
ERROR
SELECT
BillingCity,
AVG(Total)
FROM
invoices
WHERE
AVG(Total) > 5
GROUP BY
BillingCity
ORDER BY
BillingCity
Note the following error message from this query:
Misuse of aggregate: AVG():
We cannot use the WHERE clause to create a
condition based on an aggregate function. The
WHERE clause can only direct the query about
what information to pull from the fields in our
SELECT clause. If you want additional filtering
based on aggregate functions, use the HAVING
clause.
74
AGGREGATE FUNCTIONS: CORRECTING AN
ERROR
SELECT
BillingCity,
AVG(Total)
FROM
invoices
GROUP BY
BillingCity
HAVING
AVG(Total) > 5
ORDER BY
BillingCity
SELECT
BillingCity,
AVG(Total)
FROM
invoices
WHERE
AVG(Total) > 5
GROUP BY
BillingCity
ORDER BY
BillingCity
Note: With a GROUP BY clause,
you must use HAVING, or you will
get an error.
75
WHERE VS. HAVING
The WHERE clause is for filtering non-aggregate data. The WHERE
clause tells the query what information to include from the table.
The HAVING clause is for filtering results containing aggregates. The
HAVING clause acts as a further filter following the WHERE.
76
WHERE VS. HAVING: EXAMPLE
SELECT
BillingCity,
AVG(Total)
FROM
invoices
WHERE
BillingCity LIKE ‘B%’
GROUP BY
BillingCIty
HAVING
AVG(Total) > 5
ORDER BY
BillingCIty
GROUPING BY MULTIPLE
COLUMNS
SQL and Scripting
Training
78
USING GROUP BY WITH MULTIPLE FIELDS
It is possible to group by more than one aggregate field at a time.
In the following example, data are grouped first by country and then by
city.
79
USING GROUP BY WITH MULTIPLE FIELDS:
EXAMPLE
SELECT
BillingCountry
BillingCity,
AVG(Total)
FROM
invoices
GROUP BY
BillingCountry, BillingCIty
HAVING
AVG(Total) > 5
ORDER BY
BillingCIty
Note: Database files are likely to contain
spelling errors.
80
SUBQUERY
A subquery is one query nested inside of another query, usually in the
SELECT, FROM, or WHERE clause.
Subqueries are useful when the query you want to create requires a few
more steps or calculations to produce the required dataset.
Instead of writing one query and copying the results to another one, you
can use a subquery to perform both operations.
81
INTRODUCTION TO SUBQUERIES
SELECT
ROUND (AVG (Total), 2) AS [Average Total]
FROM
invoices
82
INTRODUCTION TO SUBQUERIES USING AGGREGATE FUNCTIONS
SELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total
FROM
invoices
WHERE Total <
(
select
AVG (Total)
from
invoices)
ORDER BY
Total DESC
Scenario: From sTunes, gather data about all invoices
that are lower than the average. Show InvoiceDate,
BillingAddress, BillingCity, and Total.
83
USING A SUBQUERY IN THE SELECT STATEMENT
SELECT
BillingCity,
AVG(Total) AS [City Average],
FROM
invoices
select
AVG (Total)
from
invoices)
FROM
invoices
GROUP BY
BillingCity
ORDER BY
BillingCity
WHERE CLAUSE SUBQUERIES
SQL and Scripting
Training
85
USING A WHERE CLAUSE IN A SUBQUERY
Our outer query can have a WHERE clause which, in turn, contains a
subquery with its own WHERE clause.
For example, if you want to find the all-time largest sale from the
dataset (records between the years of 2009-2012) and see if there are
any invoice totals in the latest year of the records (2013) that are higher
than that value (in the range 2009-2012), you would first have to get
the largest sale prior to 2013. This is done in the next example.
86
USING A WHERE CLAUSE IN A SUBQUERY
SELECT
MAX(Total)
FROM
invoices
WHERE
InvoiceDate < ‘2013-01-01’
Note: An initial look at the MAX(Total), largest sale, from years < 2013.
87
USING A WHERE CLAUSE IN A SUBQUERY
SELECT
InvoiceDate,
BillingCity,
Total
FROM
invoices
WHERE
InvoiceDate >= ‘2013-01-01’AND total >
(select
max(Total)
from
invoices
where
InvoiceDate < ‘2013-01-01’)
Note: You can build out the query by wrapping the MAX(Total) query in parentheses and write the
outer query.
88
SUMMARY
Joins harness the power of a relational database to bring data together from different tables.
Use of an entity relationship diagram is helpful when writing joins.
When selecting fields from multiple tables at once, aliases are needed to specify the table of origin.
Inner joins do not include rows where there is no corresponding data
Outer joins include all rows of one table, even when there is no corresponding data between tables. Rows that do not
match show up as NULL.
The IS and NOT keywords must be used to test for NULL values.
Right joins can be used in implementations of SQL but are not available in SQLite. To do the equivalent of a right join
in SQLite, simply switch the position of the two tables you are comparing in your query statement.
89
SUMMARY
Functions allow you to alter, reformat, and perform calculations on the data in your tables.
Queries containing numerical data can be manipulated with arithmetic operations and aggregate functions
Queries containing text can be split, concatenated, capitalized, etc.
Once data is aggregated with functions, it can be further sorted by the GROUP BY and HAVING Clauses.
The HAVING Clause does for aggregate fields what the WHERE clause does for non-aggregate fields.
The HAVING clause can be used in a query only if a GROUP BY clause is also present.
You can use GROUP BY with multiple fields to further narrow down your aggregated data.
90
SUMMARY
Subqueries allow you to execute multiple SQL statements within a single query.
Subqueries are comprised of two or more separate SQL statements identified as
inner and outer queries.
Subqueries are usually used to compare existing data with data you derive with
aggregates or other functions
The DISTINCT keyword allows you to ignore redundant data in records and
search for unique instances only.
91
REFERENCES
Allen, G., & Owens, M. (2010). The definitive guide to SQLite. Apress. (PDF)
Shields, W. (2019). Sql quickstart guide: the simplified beginner's guide to managing, analyzing,
and manipulating data with Sql. Clydebank Media.
Tutorialspoint SQLite: https://www.tutorialspoint.com/sqlite/index.htm
92
INTRODUCTION
Ron McFarland
Technologist, Educator
Source: Microsoft Images
93
ABOUT THIS COURSE
This course is distributed free. I use several
sources. But importantly, I use the book noted
on the next slide.
If you are using these PowerPoints, please
attribute Highervista, LLC and me (Ron
McFarland). IN ADDITION, please attribute
the author noted on the next slide, as the
author’s textbook provides essential
information for this course.
Source: Microsoft Images
94
INTRODUCTION
This course is offered to you free. HOWEVER, please
purchase the following book, as it is a primary resource for
this course. I do not make any $ from this course or this
book. So, since a handful of good content is derived from the
following text, please support this author!
Title: SQL Quickstart Guide
Author: Walter Shields
Available: Amazon, B&N, and through ClydeBank media
website at:
https://www.clydebankmedia.com/books/programming-
tech/sql-quickstart-guide

More Related Content

What's hot

Physical elements of data
Physical elements of dataPhysical elements of data
Physical elements of dataDimara Hakim
 
Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Jennifer Berk
 
BCS4L1-Database Management lab.pdf
BCS4L1-Database Management lab.pdfBCS4L1-Database Management lab.pdf
BCS4L1-Database Management lab.pdfKeerthanaP37
 
Partitioning tables and indexing them
Partitioning tables and indexing them Partitioning tables and indexing them
Partitioning tables and indexing them Hemant K Chitale
 
PBDJ 19-4(woolley rev)
PBDJ 19-4(woolley rev)PBDJ 19-4(woolley rev)
PBDJ 19-4(woolley rev)Buck Woolley
 
Partitioning Tables and Indexing Them --- Article
Partitioning Tables and Indexing Them --- ArticlePartitioning Tables and Indexing Them --- Article
Partitioning Tables and Indexing Them --- ArticleHemant K Chitale
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)Sabana Maharjan
 
Understanding about relational database m-square systems inc
Understanding about relational database m-square systems incUnderstanding about relational database m-square systems inc
Understanding about relational database m-square systems incMuthu Natarajan
 
Create a table access - office
Create a table   access - officeCreate a table   access - office
Create a table access - officePavan Kumar
 
ECDL module 5: using databases [To be continued]
ECDL module 5: using databases [To be continued] ECDL module 5: using databases [To be continued]
ECDL module 5: using databases [To be continued] Hassan Ayad
 
Ecdl v5 module 5 print
Ecdl v5 module 5 printEcdl v5 module 5 print
Ecdl v5 module 5 printMichael Lew
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginnersRam Sagar Mourya
 

What's hot (20)

Create table
Create tableCreate table
Create table
 
Sq lite module5
Sq lite module5Sq lite module5
Sq lite module5
 
Ch 9 S Q L
Ch 9  S Q LCh 9  S Q L
Ch 9 S Q L
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Physical elements of data
Physical elements of dataPhysical elements of data
Physical elements of data
 
Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
BCS4L1-Database Management lab.pdf
BCS4L1-Database Management lab.pdfBCS4L1-Database Management lab.pdf
BCS4L1-Database Management lab.pdf
 
Partitioning tables and indexing them
Partitioning tables and indexing them Partitioning tables and indexing them
Partitioning tables and indexing them
 
PBDJ 19-4(woolley rev)
PBDJ 19-4(woolley rev)PBDJ 19-4(woolley rev)
PBDJ 19-4(woolley rev)
 
Partitioning Tables and Indexing Them --- Article
Partitioning Tables and Indexing Them --- ArticlePartitioning Tables and Indexing Them --- Article
Partitioning Tables and Indexing Them --- Article
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Understanding about relational database m-square systems inc
Understanding about relational database m-square systems incUnderstanding about relational database m-square systems inc
Understanding about relational database m-square systems inc
 
Create a table access - office
Create a table   access - officeCreate a table   access - office
Create a table access - office
 
Db2 tutorial
Db2 tutorialDb2 tutorial
Db2 tutorial
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
ECDL module 5: using databases [To be continued]
ECDL module 5: using databases [To be continued] ECDL module 5: using databases [To be continued]
ECDL module 5: using databases [To be continued]
 
Ecdl v5 module 5 print
Ecdl v5 module 5 printEcdl v5 module 5 print
Ecdl v5 module 5 print
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 

Similar to Sq lite module7

Day-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxDay-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxuzmasulthana3
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 
Les05 (Displaying Data from Multiple Table)
Les05 (Displaying Data from Multiple Table)Les05 (Displaying Data from Multiple Table)
Les05 (Displaying Data from Multiple Table)Achmad Solichin
 
Sap abap-data structures and internal tables
Sap abap-data structures and internal tablesSap abap-data structures and internal tables
Sap abap-data structures and internal tablesMustafa Nadim
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)Huda Alameen
 
SQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptxSQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptxssuser6bf2d1
 
04 quiz 1 answer key
04 quiz 1 answer key04 quiz 1 answer key
04 quiz 1 answer keyAnne Lee
 
SQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfSQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfAnishurRehman1
 
45 Essential SQL Interview Questions
45 Essential SQL Interview Questions45 Essential SQL Interview Questions
45 Essential SQL Interview QuestionsBest SEO Tampa
 
Lesson 6 - Relational Algebra.pdf
Lesson 6 - Relational Algebra.pdfLesson 6 - Relational Algebra.pdf
Lesson 6 - Relational Algebra.pdfHasankaWijesinghe1
 
SQL Practice Question set
SQL Practice Question set SQL Practice Question set
SQL Practice Question set Mohd Tousif
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 

Similar to Sq lite module7 (20)

Day-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxDay-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptx
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
 
Chapter9 more on database and sql
Chapter9 more on database and sqlChapter9 more on database and sql
Chapter9 more on database and sql
 
Sql joins
Sql joinsSql joins
Sql joins
 
Les05 (Displaying Data from Multiple Table)
Les05 (Displaying Data from Multiple Table)Les05 (Displaying Data from Multiple Table)
Les05 (Displaying Data from Multiple Table)
 
Sap abap-data structures and internal tables
Sap abap-data structures and internal tablesSap abap-data structures and internal tables
Sap abap-data structures and internal tables
 
Les05
Les05Les05
Les05
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)
 
SQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptxSQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptx
 
04 quiz 1 answer key
04 quiz 1 answer key04 quiz 1 answer key
04 quiz 1 answer key
 
SQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfSQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdf
 
SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables  SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables
 
SQL JOINS- Reena P V
SQL JOINS- Reena P VSQL JOINS- Reena P V
SQL JOINS- Reena P V
 
45 Essential SQL Interview Questions
45 Essential SQL Interview Questions45 Essential SQL Interview Questions
45 Essential SQL Interview Questions
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Lesson 6 - Relational Algebra.pdf
Lesson 6 - Relational Algebra.pdfLesson 6 - Relational Algebra.pdf
Lesson 6 - Relational Algebra.pdf
 
SQL Practice Question set
SQL Practice Question set SQL Practice Question set
SQL Practice Question set
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
Joins SQL Server
Joins SQL ServerJoins SQL Server
Joins SQL Server
 

More from Highervista

Cyber security training using virtual labs 3 cs umuc presentation august 2018
Cyber security training using virtual labs 3 cs umuc presentation august 2018Cyber security training using virtual labs 3 cs umuc presentation august 2018
Cyber security training using virtual labs 3 cs umuc presentation august 2018Highervista
 
Cyber security for manufacturers umuc cadf-ron mcfarland
Cyber security for manufacturers umuc cadf-ron mcfarlandCyber security for manufacturers umuc cadf-ron mcfarland
Cyber security for manufacturers umuc cadf-ron mcfarlandHighervista
 
Intro infosec version 2
Intro infosec version 2Intro infosec version 2
Intro infosec version 2Highervista
 
How to create a maker space v2 ebook
How to create a maker space v2 ebookHow to create a maker space v2 ebook
How to create a maker space v2 ebookHighervista
 
Love and silence v3 scribd slide share
Love and silence v3 scribd slide shareLove and silence v3 scribd slide share
Love and silence v3 scribd slide shareHighervista
 

More from Highervista (10)

Sq lite module1
Sq lite module1Sq lite module1
Sq lite module1
 
Sq lite module2
Sq lite module2Sq lite module2
Sq lite module2
 
Sq lite module3
Sq lite module3Sq lite module3
Sq lite module3
 
Sq lite module4
Sq lite module4Sq lite module4
Sq lite module4
 
Sq lite module9
Sq lite module9Sq lite module9
Sq lite module9
 
Cyber security training using virtual labs 3 cs umuc presentation august 2018
Cyber security training using virtual labs 3 cs umuc presentation august 2018Cyber security training using virtual labs 3 cs umuc presentation august 2018
Cyber security training using virtual labs 3 cs umuc presentation august 2018
 
Cyber security for manufacturers umuc cadf-ron mcfarland
Cyber security for manufacturers umuc cadf-ron mcfarlandCyber security for manufacturers umuc cadf-ron mcfarland
Cyber security for manufacturers umuc cadf-ron mcfarland
 
Intro infosec version 2
Intro infosec version 2Intro infosec version 2
Intro infosec version 2
 
How to create a maker space v2 ebook
How to create a maker space v2 ebookHow to create a maker space v2 ebook
How to create a maker space v2 ebook
 
Love and silence v3 scribd slide share
Love and silence v3 scribd slide shareLove and silence v3 scribd slide share
Love and silence v3 scribd slide share
 

Recently uploaded

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Recently uploaded (20)

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Sq lite module7

  • 1. MODULE 7: WORKING WITH MULTIPLE TABLES SQL and Scripting Training (C) 2020-2021 Highervista, LLC 1
  • 2. 2 TOPICS Introduction to Joins Joins and the relational database structure Joins and aliases Inner join, left outer join, and right outer join Joining more than two tables Adding calculations to queries Types of functions in SQL String functions Date functions Aggregate functions Using the WHERE and HAVING clauses with functions Grouping by multiple columnssubqueries and aggregate functions SELECT statement subqueries WHERE clause subqueries Summary
  • 3. INTRODUCTION TO JOINS SQL and Scripting Training
  • 4. 4 ERD OF THE STUNES DATABASE
  • 5. 5 INTRODUCTION TO JOINS A JOIN is a command that combines fields in two or more tables of a relational database. As an example: For the sTunes database, it would be logical to query fields from both the Invoices and Customers tables, since customers can have invoices.
  • 6. 6 INTRODUCTION TO JOINS Since CustomerId is the primary key of the Customers table and there is a similar field of the same name in the Invoices table, there is a linkage between these two tables. Both tables can be merged on the CustomerId field for each. Note: This type of join is called an INNER JOIN. We′ll discuss other types of joins.
  • 7. 7 INTRODUCTION TO JOINS The query begins with a SELECT * (for all fields). This will provide fields from both tables (22 total fields). The ON keyword provides the linkage between the two tables. The resulting table looks like this:
  • 8. JOINS AND THE RELATIONAL DATABASE STRUCTURE SQL and Scripting Training
  • 9. 9 HOW JOINS INTERACT WITH THE RELATIONAL DATABASE STRUCTURE When examining the output from the prior Join command, you can see a repeating set of information for customer 1 (Luis). Looking back at an ERD, you can say that this customer (Luis) has a 1:M relationship with the Invoices table. Let′s examine the ERD for the sTunes db. Note that the ERD is in an MS/Access type of ERD notation.
  • 11. 11 STUNES ERD The database is normalized (through 3NF). Examine the linkages between tables (PK to FK). As noted earlier, the relationship between each pair of tables is bidirectional. It can be read in either direction.
  • 12. 12 USING JOINS WITH AN ALIAS Since two tables in any given database may have fields with identical names, when creating joins it is necessary to specify the table name with the associated field name. Aliases reduce the amount of typing required and serve to help readability.
  • 13. 13 IDENTICAL JOINS SELECT * FROM invoices INNER JOIN customers ON invoices.CustomerID = customers.CustomerID SELECT * FROM Invoices AS i INNER JOIN Customers AS c ON i.CustomerID = c.CustomerID
  • 14. 14 USING ALIASES WITH FIELD NAMES: EXAMPLE SELECT c.LastName, c.FirstName, i.InvoiceID, i.CustomerID, i.InvoiceDate, i.Total FROM invoices AS i INNER JOIN customers AS c ON i.CustomerId = c.CustomerID ORDER BY c.Lastname
  • 15. 15 USING ALIASES WITH FIELD NAMES: RESULTS
  • 16. 16 JOIN TYPES AND THEIR DIFFERENCES What happens if the data from the tables joined doesn’t match up? ­ For example, suppose a customer deleted his customer database record (removing his record from the Customers table). ­ Because the company is required to keep financial records, the invoices for the customer were not deleted. ­ It is not unusual to find discrepancies in databases, and you must decide whether queries should include or exclude data that does not match up.
  • 17. 17 EXAMPLE TABLES (NOT THE STUNES DB) Discrepancies 1. Invoices table shows someone with a customer ID of 6 who made a purchase on 5/1/2017, but this customer does not show up on the Customers table. 2. It appears that customer ID 1 and customer ID 5 (on the Customers table) never made a purchase (they’re not on the Invoices table). 3. We’ll look at how this is handled with various JOIN types.
  • 18. 18 INNER JOIN: HOW ARE DISCREPANCIES HANDLED? Inner Join—Only returns matching records. Any unmatched data from either table is ignored.
  • 19. 19 INNER JOIN: HOW ARE DISCREPANCIES HANDLED? Note: In this example, the Inner Join will join four common records.
  • 20. 20 INNER JOIN: HOW ARE DISCREPANCIES HANDLED? SELECT i.InvoiceId, c.CustomerId, c.LastName, c.Address, i.InvoiceDate, i.BillingAddress, i.total FROM invoices AS i INNER JOIN customers AS c ON i.CustomerId = c.CustomerId
  • 21. 21 LEFT OUTER JOIN: HOW ARE DISCREPANCIES HANDLED? Note: The concept of a left table and a right table depends entirely on the order that tables are listed in the JOIN statement.
  • 22. 22 LEFT OUTER JOIN: HOW ARE DISCREPANCIES HANDLED? Note: With the LEFT OUTER JOIN, everything in the Invoices table will be displayed. Only common records in the Customers table will be displayed.
  • 23. 23 LEFT OUTER JOIN: HOW ARE DISCREPANCIES HANDLED? Can you think of a business case for displaying all invoices and only customer data related to invoices? SELECT i.InvoiceId, c.CustomerId, c.Name, c.Address, i.InvoiceDate, i.BillingAddress, i.Total FROM invoices AS i LEFT OUTER JOIN customers AS c ON i.CustomerId = c.CustomerId
  • 25. 25 RIGHT OUTER JOIN: HOW ARE DISCREPANCIES HANDLED? Note: For LEFT OUTER JOIN or RIGHT OUTER JOIN, you can use LEFT JOIN or RIGHT JOIN (same results). Note: RIGHT OUTER JOINs are not supported in SQLite
  • 26. 26 RIGHT OUTER JOIN: HOW ARE DISCREPANCIES HANDLED? Note: With the RIGHT OUTER JOIN, everything in the Customers table will be displayed. Only common records in the invoices table will be displayed.
  • 27. 27 LEFT OUTER JOIN: HOW ARE DISCREPANCIES HANDLED? Can you think of a business case for displaying all customers and only invoice data related to customers? SELECT i.InvoiceId, c.CustomerId, c.Name, c.Address, i.InvoiceDate, i.BillingAddress, i.Total FROM invoices AS i RIGHT OUTER JOIN customers AS c ON i.CustomerId = c.CustomerId
  • 28. 28 INNER JOINS WITH MORE THAN TWO TABLES Joins can combine two or more tables. Adding additional tables using joins is straightforward: It follows the same pattern as inner joins. Review database schema on next slide: There is a relationship between Invoices, Customers, and Employee tables. ­ Note: Look at SupportRepId field (Customers table) and the EmployeeId field (Employees table).
  • 29. 29 INNER JOINS WITH MORE THAN TWO TABLES The Invoices table is related to the Customers table (bidirectional relationship). The Customers table is related to the Employees table (bidirectional relationship).
  • 30. 30 INNER JOINS WITH MORE THAN TWO TABLES When using two or more tables in a Join, think about the fields that you need from each table.
  • 31. 31 INNER JOINS WITH MORE THAN TWO TABLES SELECT e.FirstName, e.LastName e.EmployeeId, c.FirstName, c.LastName, c.SupportRepID, i.CustomerId, i.Total FROM invoices AS i INNER JOIN customers AS c ON i.CustomerId = c.CustomerId INNER JOIN employees AS e ON c.SupportRepId = e.EmployeeId ORDER BY i.Total DESC LIMIT 10
  • 32. 32 INNER JOINS WITH MORE THAN TWO TABLES
  • 33. 33 SQL SELECT e.FirstName, e.LastName, e.EmployeeId, c.FirstName, c.LastName, c.SupportRepId, i.CustomerId, i.Total FROM invoices AS i INNER JOIN customers AS c ON i.CustomerId = c.CustomerId INNER JOIN employees AS e ON c.SupportRepId = e.EmployeeId ORDER BY i.Total DESC LIMIT 10
  • 34. 34 USING LEFT OUTER JOINS WITH NULL, IS, AND NOT Left Outer Join—shows everything from the left table and all matching information from the right table. When looking at the artists and albums tables in the sTunes database, if you want to generate a list of all artists who do not have an album, what is the process?
  • 35. 35 USING LEFT OUTER JOINS WITH NULL, IS, AND NOT A Left Outer Join provides a list of all artists along with any associated albums for artists with albums. The Left Outer Join will fill in any fields that do not have album titles with NULL values.
  • 36. 36 USING LEFT OUTER JOINS WITH NULL, IS, AND NOT SELECT ar.ArtistId AS [ArtistId From Artist Table], al.ArtistId AS [ArtistId From Albums Table], ar.Name AS [Artist Name], al.Title AS [Album Title] FROM artists AS ar LEFT OUTER JOIN albums AS al ON ar.ArtistId = al.ArtistId
  • 37. 37 USING LEFT OUTER JOINS WITH NULL, IS, AND NOT SELECT ar.ArtistId AS [ArtistId From Artist Table], al.ArtistId AS [ArtistId From Albums Table], ar.Name AS [Artist Name], al.Title AS [Album Title] FROM artists AS ar LEFT OUTER JOIN albums AS al ON ar.ArtistId = al.ArtistId Note: The result will include artists with albums and artist without albums (NULL).
  • 38. 38 USING LEFT OUTER JOINS WITH NULL, IS, AND NOT SELECT ar.ArtistId AS [ArtistId From Artist Table], al.ArtistId AS [ArtistId From Albums Table], ar.Name AS [Artist Name], al.Title AS [Album Title] FROM artists AS ar LEFT OUTER JOIN albums AS al ON ar.ArtistId = al.ArtistId WHERE al.ArtistId IS NULL Note: To generate a report that shows artists who do not have albums (IS NULL), include a comparison statement where the ArtistId on the Albums table is NULL. Use (NOT NULL) to return only values that were not NULL.
  • 39. 39 TURNING A RIGHT JOIN INTO A LEFT JOIN Since RIGHT OUTER JOINS are not supported in SQLite, keep in mind that:
  • 40. 40 DAY 7, ASSIGNMENT 2: IDENTIFY PK, FK, CREATE INNER JOIN Use Using the Genres table, create a third inner join to include the Name field from the table in your result set. Create Create an inner join between the Albums and Tracks tables and display the album names and track names in a single result set. Identify Identify PKs and FKs in other tables that are associated to the Tracks table. Use Using the sTunes ERD, view the Tracks table.
  • 41. ADDING CALCULATIONS TO QUERIES SQL and Scripting Training
  • 42. 42 ADDING CALCULATIONS TO QUERIES Calculations, like counting the number of records returned, can be performed by adding functions to queries. The function COUNT ( ) can count a given field, like LastName. You can put the results in a temporary field such as NameCount. SELECT COUNT (LastName) AS [NameCount] FROM customers WHERE LastName LIKE ‘B%’
  • 43. TYPES OF FUNCTIONS IN SQL SQL and Scripting Training
  • 44. 44 FUNCTIONS IN SQL Functions are special keywords that accept certain parameters, perform an operation (such as a calculation or modification of the data in a field), and return the result of that operation as a value. There is a list of all SQLite functions on the SQLite website. Note: Other DBMSs may have an extended set of functions.
  • 45. 45 FUNCTIONS • String functions modify character and text-based data. • Date functions modify time and date data. • Aggregate functions perform mathematical operations.
  • 46. 46 FUNCTIONS • Functions in SQL operate similarly to the way functions operate in a spreadsheet. • If you’ve ever used Excel functions, there is a ″pop-up″ style definitions box that prompts the user for parameters. • In SQL, you will need to supply the parameters when calling the function.
  • 47. STRING FUNCTIONS SQL and Scripting Training
  • 48. 48 STRING FUNCTIONS: EXAMPLE Note: NVARCHAR is a variable character data format. The following query would return all names with mailing addresses in the United States: SELECT FirstName, LastName, Address FROM customers WHERE Country = ‘USA’ Problem: Name data is split into parts in the database.
  • 49. 49 CONCATENATING STRINGS OF TEXT Joining fields is known as concatenation. To add two fields together, use the double pipe symbol || For example: SELECT FirstName || LastName FROM customers WHERE CustomerId = 1
  • 50. 50 CONCATENATING STRINGS OF TEXT Another example:SELECT FirstName, LastName, FirstName || ‘ ‘ || LastName FROM customers WHERE Country = “USA”
  • 51. 51 USING MULTIPLE CONCATENATIONS Using multiple concatenations, you can create a one-line name and address list for all customers. SELECT FirstName || ‘ ‘ || LastName || ‘ ‘ || Address || ‘, ‘ || City || ‘, ‘ || State || ‘ ‘ || PostalCode AS [MainlingAddress} FROM customers WHERE Country = “USA”
  • 52. 52 TRUNCATING TEXT You can separate or truncate text to create more uniformity in the output. Remember that users can input inconsistencies or errors in database fields. Using truncation is one tool to clean up how data looks in reports. You can use LENGTH ( ) to examine how a given value was entered in a field. SELECT PostalCode, LENGTH(PostalCode) AS [Postal Code Length] FROM customers WHERE Country = “USA”
  • 53. 53 TRUNCATING TEXT Since there are different sizes in the field, you can use another function SUBSTR() to substring the field value and place the output on the report. More detail on the SUBSTR ( ) function:
  • 54. 54 TRUNCATING TEXT: POSTAL CODE SELECT PostalCode, SUBSTR(PostalCode, 1, 5) AS [Five Digit Postal Code] FROM customers WHERE Country = “USA”
  • 55. 55 MORE STRING FUNCTIONS: UPPER( ) AND LOWER( )
  • 56. 56 UPPER AND LOWER EXAMPLE SELECT FirstName as [First Name Unmodified], UPPER(FirstName) as [First Name in UPPERCASE], LOWER(FirstName) as [First Name in lowercase], UPPER(FirstName) || ‘ ‘ || UPPER(LastName) AS [Full Name in UPPERCASE] FROM customers
  • 57. DATE FUNCTIONS SQL and Scripting Training
  • 58. 58 DATE FUNCTIONS Date functions allow you to manipulate data stored in various date and time formats. In sTunes, date information is stored in DATETIME format: YYYY-MM-DD HH:MM:SS All timecodes not being used are stored as 00:00:00 Two date functions (out of several)
  • 59. 59 STRFTIME FUNCTION—ARGUMENTS IN ORDER: FORMAT, TIMESTRING, MODIFIER (OPTIONAL)
  • 60. 60 STRFTIME FUNCTION—ARGUMENTS IN ORDER: FORMAT, TIMESTRING, MODIFIER (OPTIONAL)
  • 61. 61 STRFTIME FUNCTION—ARGUMENTS IN ORDER: FORMAT, TIMESTRING, MODIFIER (OPTIONAL)
  • 62. 62 STRFTIME EXAMPLE SELECT STRFTIME(‘The Year is: %Y The Day is: %d The Month is %m’, ‘2011-05-22’) AS [Text with Conversion Specifications]
  • 63. 63 STRFTIME EXAMPLE—CALCULATE EMPLOYEE′S AGE SELECT LastName, FirstName, STRFTIME(‘%Y-%m-%d’,BirthDate) AS [Birthday No Timecode], STRFTIME(‘%Y-%m-%d’,’now’) – STRFTIME(‘%Y-%m-%d’, BirthDate) AS [Age] FROM employees ORDER BY Age
  • 64. AGGREGATE FUNCTIONS SQL and Scripting Training
  • 65. 65 AGGREGATE FUNCTIONS Aggregate functions can turn a range of numbers into a single data point based on a variety of mathematical functions. Previously, we used the COUNT ( ) function to find the total number of customers. Additional aggregate functions (not a complete list):
  • 66. 66 AGGREGATE FUNCTIONS: EXAMPLE SELECT SUM(Total) AS TotalSales, AVG(Total) AS AverageSales, MAX(Total) AS MaximumSale, MIN(Total) AS MinSale, COUNT(*) AS SalesCount FROM invoices
  • 67. 67 NESTING FUNCTIONS WITH THE ROUND ( ) FUNCTION A nested function is a function contained within another function. One reason that you want to nest functions is to further modify the format of the inner function. For example, if you use the AVG ( ) function, you will see too many decimal places. You can use the ROUND ( ) function to limit the number of decimal places.
  • 68. 68 NESTING FUNCTIONS WITH THE ROUND ( ) FUNCTION SELECT AVG (Total) AS [Average Sales], ROUND(AVG(Total), 2) AS [Rounded Average Sales] FROM invoices Note: When using the ROUND ( ) function with monetary values, be careful of rounding up, since this may change intermediary calculations!
  • 69. USING THE WHERE AND HAVING CLAUSES WITH FUNCTIONS SQL and Scripting Training
  • 70. 70 USING AGGREGATE FUNCTIONS WITH THE GROUP BY CLAUSE A useful feature of aggregate functions is their ability to calculate subtotals or aggregates for different groups of data. SELECT BillingCity, AVG(Total) FROM invoices ORDER BY BillingCity Something is wrong!?!?
  • 71. 71 USING AGGREGATE FUNCTIONS WITH THE GROUP BY CLAUSE Incorrect: A global average of all cities is calculated and ′Delhi′ is the first in the db. To correct, you need a GROUP BY clause. SELECT BillingCity, AVG(Total) FROM invoices GROUP BY BillingCity ORDER BY BillingCity
  • 72. 72 HAVING CLAUSES WITH GROUPED QUERIES Adding criteria to a grouped query works like previous queries. The WHERE clause allows you to add new criteria.
  • 73. 73 AGGREGATE FUNCTIONS: IDENTIFYING AN ERROR SELECT BillingCity, AVG(Total) FROM invoices WHERE AVG(Total) > 5 GROUP BY BillingCity ORDER BY BillingCity Note the following error message from this query: Misuse of aggregate: AVG(): We cannot use the WHERE clause to create a condition based on an aggregate function. The WHERE clause can only direct the query about what information to pull from the fields in our SELECT clause. If you want additional filtering based on aggregate functions, use the HAVING clause.
  • 74. 74 AGGREGATE FUNCTIONS: CORRECTING AN ERROR SELECT BillingCity, AVG(Total) FROM invoices GROUP BY BillingCity HAVING AVG(Total) > 5 ORDER BY BillingCity SELECT BillingCity, AVG(Total) FROM invoices WHERE AVG(Total) > 5 GROUP BY BillingCity ORDER BY BillingCity Note: With a GROUP BY clause, you must use HAVING, or you will get an error.
  • 75. 75 WHERE VS. HAVING The WHERE clause is for filtering non-aggregate data. The WHERE clause tells the query what information to include from the table. The HAVING clause is for filtering results containing aggregates. The HAVING clause acts as a further filter following the WHERE.
  • 76. 76 WHERE VS. HAVING: EXAMPLE SELECT BillingCity, AVG(Total) FROM invoices WHERE BillingCity LIKE ‘B%’ GROUP BY BillingCIty HAVING AVG(Total) > 5 ORDER BY BillingCIty
  • 77. GROUPING BY MULTIPLE COLUMNS SQL and Scripting Training
  • 78. 78 USING GROUP BY WITH MULTIPLE FIELDS It is possible to group by more than one aggregate field at a time. In the following example, data are grouped first by country and then by city.
  • 79. 79 USING GROUP BY WITH MULTIPLE FIELDS: EXAMPLE SELECT BillingCountry BillingCity, AVG(Total) FROM invoices GROUP BY BillingCountry, BillingCIty HAVING AVG(Total) > 5 ORDER BY BillingCIty Note: Database files are likely to contain spelling errors.
  • 80. 80 SUBQUERY A subquery is one query nested inside of another query, usually in the SELECT, FROM, or WHERE clause. Subqueries are useful when the query you want to create requires a few more steps or calculations to produce the required dataset. Instead of writing one query and copying the results to another one, you can use a subquery to perform both operations.
  • 81. 81 INTRODUCTION TO SUBQUERIES SELECT ROUND (AVG (Total), 2) AS [Average Total] FROM invoices
  • 82. 82 INTRODUCTION TO SUBQUERIES USING AGGREGATE FUNCTIONS SELECT InvoiceDate, BillingAddress, BillingCity, Total FROM invoices WHERE Total < ( select AVG (Total) from invoices) ORDER BY Total DESC Scenario: From sTunes, gather data about all invoices that are lower than the average. Show InvoiceDate, BillingAddress, BillingCity, and Total.
  • 83. 83 USING A SUBQUERY IN THE SELECT STATEMENT SELECT BillingCity, AVG(Total) AS [City Average], FROM invoices select AVG (Total) from invoices) FROM invoices GROUP BY BillingCity ORDER BY BillingCity
  • 84. WHERE CLAUSE SUBQUERIES SQL and Scripting Training
  • 85. 85 USING A WHERE CLAUSE IN A SUBQUERY Our outer query can have a WHERE clause which, in turn, contains a subquery with its own WHERE clause. For example, if you want to find the all-time largest sale from the dataset (records between the years of 2009-2012) and see if there are any invoice totals in the latest year of the records (2013) that are higher than that value (in the range 2009-2012), you would first have to get the largest sale prior to 2013. This is done in the next example.
  • 86. 86 USING A WHERE CLAUSE IN A SUBQUERY SELECT MAX(Total) FROM invoices WHERE InvoiceDate < ‘2013-01-01’ Note: An initial look at the MAX(Total), largest sale, from years < 2013.
  • 87. 87 USING A WHERE CLAUSE IN A SUBQUERY SELECT InvoiceDate, BillingCity, Total FROM invoices WHERE InvoiceDate >= ‘2013-01-01’AND total > (select max(Total) from invoices where InvoiceDate < ‘2013-01-01’) Note: You can build out the query by wrapping the MAX(Total) query in parentheses and write the outer query.
  • 88. 88 SUMMARY Joins harness the power of a relational database to bring data together from different tables. Use of an entity relationship diagram is helpful when writing joins. When selecting fields from multiple tables at once, aliases are needed to specify the table of origin. Inner joins do not include rows where there is no corresponding data Outer joins include all rows of one table, even when there is no corresponding data between tables. Rows that do not match show up as NULL. The IS and NOT keywords must be used to test for NULL values. Right joins can be used in implementations of SQL but are not available in SQLite. To do the equivalent of a right join in SQLite, simply switch the position of the two tables you are comparing in your query statement.
  • 89. 89 SUMMARY Functions allow you to alter, reformat, and perform calculations on the data in your tables. Queries containing numerical data can be manipulated with arithmetic operations and aggregate functions Queries containing text can be split, concatenated, capitalized, etc. Once data is aggregated with functions, it can be further sorted by the GROUP BY and HAVING Clauses. The HAVING Clause does for aggregate fields what the WHERE clause does for non-aggregate fields. The HAVING clause can be used in a query only if a GROUP BY clause is also present. You can use GROUP BY with multiple fields to further narrow down your aggregated data.
  • 90. 90 SUMMARY Subqueries allow you to execute multiple SQL statements within a single query. Subqueries are comprised of two or more separate SQL statements identified as inner and outer queries. Subqueries are usually used to compare existing data with data you derive with aggregates or other functions The DISTINCT keyword allows you to ignore redundant data in records and search for unique instances only.
  • 91. 91 REFERENCES Allen, G., & Owens, M. (2010). The definitive guide to SQLite. Apress. (PDF) Shields, W. (2019). Sql quickstart guide: the simplified beginner's guide to managing, analyzing, and manipulating data with Sql. Clydebank Media. Tutorialspoint SQLite: https://www.tutorialspoint.com/sqlite/index.htm
  • 93. 93 ABOUT THIS COURSE This course is distributed free. I use several sources. But importantly, I use the book noted on the next slide. If you are using these PowerPoints, please attribute Highervista, LLC and me (Ron McFarland). IN ADDITION, please attribute the author noted on the next slide, as the author’s textbook provides essential information for this course. Source: Microsoft Images
  • 94. 94 INTRODUCTION This course is offered to you free. HOWEVER, please purchase the following book, as it is a primary resource for this course. I do not make any $ from this course or this book. So, since a handful of good content is derived from the following text, please support this author! Title: SQL Quickstart Guide Author: Walter Shields Available: Amazon, B&N, and through ClydeBank media website at: https://www.clydebankmedia.com/books/programming- tech/sql-quickstart-guide