SQLDEV 320A Week 2-1
SQLDEV 320A Week 2-1
QUERYING
sd p sp bea
a
Returns all rows from one table and any matching
rows from second table
n1 n2
n1 n2
The WHERE Clauses
WHERE clause filters the intermediate data set
returned by FROM clause
Filtered data set forms a new intermediate set for
the next processing phase
e
cr p WHERE clause
excludes this
region.
Intermediate Generates Tn+1
set Tn
sp bea
a
The GROUP BY Clause
Collapses or groups results on 1 or more columns or
column expressions,
Creates a new intermediate set for the next processing phase
Returns 1 row per group
Commonly used with aggregate functions to get
grouped counts, sums, etc.
Set Tn+1
𝚺 Set Tn+2
The HAVING clause
Set Tn+2
HAVING clause
excludes this
region.
Generates Tn+3
The DISTINCT clause
DISTINCT creates a new grouped data set
• This could expose a programming logic failure on the FROM, JOIN or WHERE phase
ORDER BY sorts rows in results for presentation ORDER BY can refer to:
purposes
No guaranteed order of rows without ORDER BY Columns by name, alias or ordinal position (not recommended)
Use of ORDER BY guarantees the sort order of the result Columns not part of SELECT list
Sorts all NULLs together • Unless DISTINCT specified
ASCending or DESCending
Set
Cursor
Tn+4
From Relations to SQL language
Relational Database Management Systems (RDBMS)
IBM, System R (research project) 1974
SalesOrderHeader
(Sales)
SalesOrderID SalesPerson Employee
Product (Sales)
BusinessEntityI (HumanResources)
BusinessEntityI
RevisionNum be
(Production)
Pro d uctI D
r
D D
O rd erDate
Territo ryID NationalIDNumbe
r
Person
Nam e
SalesQuota Lo g inI D (Person)
BusinessEntityI
D
DueDate
ProductNum be
PersonType
r Bo nus OrganizationNod
MakeFlag SalesOrderDetail ShipDate e
(Sales) Com m issionPc OrganizationLev
NameStyl
e
Status t el
FinishedGoodsFla SalesOrderID Title
g SalesYTD JobTitle
OnlineOrderFla
C o lo r SalesOrderDetailID g Firs tNam
Sales Las tYea BirthDate
e
ProductCategory SafetyStockLev
SalesOrderNum b r
ProductSubcategory CarrierTrackingNumber er Mid d leNam e
(Production el ro wg uid MaritalStatu
StateProvinceCode
IsOnlyStateProvinceFlag
Nam e
TerritoryID
rowguid
M odifi edDate
AdventureWorks 2019 Products
Tables Product (Production)
ProductID
Name
ProductNumber
MakeFlag
FinishedGoodsFlag
Color
SafetyStockLevel
ReorderPoint
StandardCost
ProductCategory ListPrice
ProductSubcategory
(Production) (Production) Size
ProductCategoryID ProductSubcategoryID SizeUnitMeasureCode
Name ProductCategoryID WeightUnitMeasureCode
rowguid Name Weight
ModifiedDate rowguid DaysToManufacture
ModifiedDate ProductLine
Class
Style
ProductSubcategoryID
ProductModelID
SellStartDate
SellEndDate
DiscontinuedDate
rowguid
ModifiedDate
AdventureWorks 2019 Sales
TablesSalesOrderHeader
(Sales)
SalesOrderID
RevisionNumber
OrderDate
DueDate
ShipDate SalesOrderDetail
Status (Sales)
SalesOrderID
OnlineOrderFlag
SalesOrderDetailID
SalesOrderNumber
CarrierTrackingNumber
PurchaseOrderNumber
OrderQty
AccountNumber
ProductID
CustomerID
SpecialOfferID
SalesPersonID
UnitPrice
TerritoryID
UnitPriceDiscount
BillToAddressID
LineTotal
ShipToAddressID
rowguid
ShipMethodID
ModifiedDate
CreditCardID
CreditCardApprovalCode
CurrencyRateID
SubTotal
TaxAmt
Freight
TotalDue
Comment
rowguid
ModifiedDate
AdventureWorks 2019 Sales-
People Tables
Employee Person (Person)
(HumanResources) BusinessEntityID
BusinessEntityID
PersonType
SalesPerson (Sales)
NationalIDNumber
BusinessEntityID NameStyle
LoginID
TerritoryID Title
OrganizationNode
SalesQuota FirstName
OrganizationLevel
Bonus MiddleName
JobTitle
CommissionPct LastName
BirthDate
SalesYTD Suffix
MaritalStatus
SalesLastYear EmailPromotion
Gender
rowguid AdditionalContactInfo
HireDate
ModifiedDate Demographics
SalariedFlag
rowguid
VacationHours
ModifiedDate
SickLeaveHours
CurrentFlag
rowguid
ModifiedDate
AdventureWorks 2019 Territories
Tables
SalesTerritory (Sales)
TerritoryID
CountryRegion
Name (Person)
CountryRegionCode CountryRegionCode
StateProvince
[Group] Name
(Person)
SalesYTD StateProvinceID ModifiedDate
SalesLastYear StateProvinceCode
CostYTD CountryRegionCode
CostLastYear IsOnlyStateProvinceFlag
rowguid Name
ModifiedDate TerritoryID
rowguid
ModifiedDate
Meet
AdventureWorks
DEMO
SQL language
It is declarative
In opposition to
procedural
It is transactional
In opposition to
iterative or incremental
SQL language
Data Definition Language (DDL)
CREATE, ALTER, DROP
Data Manipulation Language (DML)
INSERT, UPDATE, DELETE
Data Query Language (DQL)
SELECT
Data Control Language (DCL)
GRANT, REVOKE, DENY
Data Transaction Language (DTL)
BEGIN TRANSACTION, SAVE TRANSACTION,
COMMIT TRANSACTION, ROLLBACK
TRANSACTION
Querying Concepts
<join operator>
[ INNER ] [ <join hint> ] JOIN
LEFT [ OUTER ] JOIN
RIGHT [ OUTER ] JOIN
FULL [ OUTER ] JOIN
CROSS JOIN
Documentation on aggreg
ate functions
COUNT(), COUNT_BIG(), SUM(),
AVG(), MAX(), MIN(),STDEV(),
VAR(), STDEVP(), VARP(),
APPROX_COUNT_DISTINCT
SELECT statement
DEMO
SQL language
SELECT statement
(joins)
SELECT <column expression> [AS <column alias>][, <column expression> …] -->
Project
FROM <table expression> [AS <table alias>][, <table expression> …] -->
Relation
<qualified table name>
<SELECT
<table statement>::=
expression>
<table expression> <join operator> <table expression> ON <logical
expression>
SQL Language - Joins
<join operator>
[ INNER ][ <join hint> ] JOIN
LEFT [ OUTER ] JOIN
RIGHT [ OUTER ] JOIN
FULL [ OUTER ] JOIN
<apply operator>
CROSS APPLY
OUTER APPLY
DEMO
SQL language
SELECT statement (basics)
• SELECT <column expression>[, <column expression> …][, <aggregate
expression>]
• FROM <table expression>[, <table expression> …]
• [WHERE <Boolean expression>]
• [GROUP BY <column expression>[, <column expression> …]
• [HAVING <Boolean expression>]]
• [ORDER BY <column expression>[, <column expression> …][, <aggregate
expression>]
The ORDER BY clause can only be placed on:
• The outermost SELECT statement
• The last SELECT statement of a string of set operations (union, intersection, except), and
applies to the result of the set operations
ORDER BY
DEMO
SQL language
SELECT statement (basics)
• SELECT <column expression>[, <column expression> …][, <aggregate
expression>]
• FROM <table expression>[, <table expression> …]
• [WHERE <Boolean
• <Boolean expression>]
Expression> ::= <column expression> IN <set
expression>
• <set expression> ::= (<element>[,
• <element> …]) ::= (SELECT <column expression> FROM
… )
Sub-queries
DEMO
Correlated
Subqueries
A SQL Server T-SQL correlated
subquery is a special kind of
temporary data store in which
the result set for an inner
query depends on the current
row of its outer query.
In contrast, an SQL Server T-
SQL uncorrelated subquery
has the same result set no
matter what row is current in
its outer query.
Correleated vs. Non-
correlated subqueries
DEMO
Common
A common table expression (CTE) can be thought of as a
temporary result set that is defined within the execution scope
of a single SELECT, INSERT, UPDATE, DELETE, or CREATE
VIEW statement. A CTE is similar to a derived table in that it is
Table not stored as an object and lasts only for the duration of the
query. Unlike a derived table, a CTE can be self-referencing and
can be referenced multiple times in the same query.
ns
defined programming
objects such as functions,
procedures, etc.
• CTE statements can be
referenced for more
modular querysyntax
• Allow recursive iterations
on hierarchical
datastructures
SQL language
Common Table expression clause
[WITH <cte-name> AS(<select statement>)[, …]]
SELECT <column expression>[, <column expression> …][,
<aggregate expression>]
FROM (<table expression>|<cte-name>)[, (<table expression>|
<cte-name>) …]
[WHERE <Boolean expression>]
Common Table
Expressions (CTEs)
DEMO
Week 2 Assignment
QUIZ 2 CODING
ASSIGNMENT