0% found this document useful (0 votes)
0 views

SQLDEV 320A Week 2-1

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

SQLDEV 320A Week 2-1

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Instructor:

SQL Server boB Taylor


Developme
nt [email protected]
SQLDEV
320 A
Spring
2021 MCA, MCM, MCSM,
Week 2 MCSE, MCSD, MCT,
Data Scientist
TODAY REVIEW
• RECAP WEEK 1 – VENN DIAGRAMS

FROM RELATIONS TO SQL


LANGUAGE

SQL LANGUAGE, BIG PICTURE

QUERYING

SQL SCRIPT PROGRAMMING


Logical processing of a JOIN clause
Every input data set in a FROM and JOIN clause
are processed in pairs until every single data set
is joined
JOIN clause performs filtering over data sets
Product Employee
Product
𝑽𝑻 𝟏=𝑷𝒓𝒐𝒅𝒖𝒄𝒕∩ 𝑬𝒎𝒑𝒍𝒐𝒚𝒆𝒆
Employee Sales
VT1 Sales
𝑽𝑻 𝟏 ∩ 𝑺𝒂𝒍𝒆𝒔
𝑷𝒓𝒐𝒅𝒖𝒄𝒕∩𝑬𝒎𝒑𝒍𝒐𝒚𝒆𝒆∩𝑺𝒂𝒍𝒆𝒔
Inner Join Examples
Join based on single matching attribute
List tables in FROM Clause separated by JOIN
operator
Table aliases preferred
Table order does not matter e
cr p

sd p sp bea
a
Returns all rows from one table and any matching
rows from second table

Table ordering DOES matter here when written

Outer One table’s rows are “preserved”

Joins LEFT vs RIGHT refers to which table’s output will be


reserved

Additional rows added to results for non-matched


rows
• NULLs added in place where attributes do not match
Outer Join Examples
Return everything from Numbers1 and values from
Numbers2 if they exist (join by NumberCol in both
tables)

n1 n2

Return everything from Numbers2 and values from


Numbers1 if they exist (join by NumberCol in both
tables)

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

FILTERS A GROUP OR TYPICALLY USED WITH A IF NOT USED WITH A


AGGREGATE GROUP BY GROUP BY, THERE IS ONLY
1 SINGLE AGGREGATED
GROUP

Set Tn+2
HAVING clause
excludes this
region.
Generates Tn+3
The DISTINCT clause
DISTINCT creates a new grouped data set

• It takes a single occurrence of a row that may be duplicated

It is often used to eliminate duplicated rows from Cartesian products

• This could expose a programming logic failure on the FROM, JOIN or WHERE phase

Set Tn+3 𝚺 Set Tn+4


The ORDER BY Clause

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

ORACLE, Oracle (1979)

IBM, System/38 (1979)

University of California – Berkeley, Ingres (1980)

IBM, SQL/DS (1981)

IBM, DB2 (1983)

SQL Server 1.0 (1989)


SQL Server 4.2 A (1992) & B (1993) – only on OS2 presentation manager
(Sybase)
SQL Server 4.2.1a (1993) – Windows NT – first Microsoft only version
Meet
AdventureWorks
DEMO
AdventureWorks 2019 Main Tables
Programmi
ng

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

Prod uctCat eg oryID


(Production)
Prod uctS ub cat eg oryID ReorderPoint OrderQt y
PurchaseOrderNum b
er
s
LastNam e
Nam e Gend er
AccountNum be
Prod uctCat eg oryID S tand ardCos Prod uctID r Suffix
rowguid t HireDate
Cust om erID
Nam e ListPrice SpecialOff erID Em ailPro m o tio
SalariedFla
M odifi edDate n
SalesPersonI g
rowguid Siz e UnitPrice D AdditionalContactInf
VacationHour
Territo ryI D o
M odifi edDate SizeUnitM easureCo s
UnitPriceDiscount Dem ographic
de SickLeaveHo ur
BillToAddressID SalesTerritory s
s
WeightUnitM easureCod LineTotal
e (Sales)
TerritoryID CurrentFla
ro wg uid
S hip ToAd d ressID g
W eig ht rowguid
Nam e
ShipMethodID
DaysToManufactur
e Cou nt ryRegi onCode
C red itC ard I
Pro d uctLine
D [ Group ]
CreditCardApprovalCo.
C las s
.. SalesYTD
CurrencyRateI
Style
D SalesLastYear
SubTotal
Prod uctS ub cat eg oryI
Cost YTD
CountryRegion
D
Pro d uctMo d elI D
TaxAm t (Person)
Cou nt ryRegi onCode
Cost Last Year
Freight Nam e
SellStartDat
e rowguid
TotalDue M odifi edDate
SellEndDat
e M odifi edDate
StateProvince
(Person)
StateProvinceID

StateProvinceCode

Cou nt ryRegi onCode

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 states the desired result


In opposition to define
a method, process or
algorithm to get a
result

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

WHAT do you want to see


SQL as result --> Project

language WHAT is the source of


your data --> Relation

WHAT subset are you


interested in --> Selection
SQL language
SELECT statement (basics)
SELECT <column expression> [AS <column alias>][, <column --> Projection
expression> …]
[FROM <table expression> [AS <table alias>][, <table expression> --> Relation
…]
[WHERE <Boolean expression>]] --> Selection
SQL language
Elements of the SELECT
clause
<column
<column name>::=
expression>
<unary operator> <column expression>
<column expression> <binary operator> <column
expression>
<function<(<column name>| <column expression>)[,
…]>>

<unary operator>, <binary operator>


+ (Unary Plus) (Transact-SQL) - SQL Server | Microsoft Docs

<function<(<column name>| <column expression>)[, …]>>


SQL language
Elements of the FROM clause
<table expression> ::=
<qualified table name>
<SELECT statement>
<table expression> <join operator> <table expression> ON <logical
expression>

<join operator>
[ INNER ] [ <join hint> ] JOIN
LEFT [ OUTER ] JOIN
RIGHT [ OUTER ] JOIN
FULL [ OUTER ] JOIN
CROSS JOIN

<Cartesian Product operator> -- This is the old, non-ANSI method


,

<Apply product operator> 6


CROSS | OUTER) APPLY
Built-in Functions
SQL
languag
e
String
Mathematical
Date and Time
Conversion
Many more not listed here
SQL
Language
SELECT <column expression>[, <column
expression> …][, <aggregate
expression>]
FROM <table expression>[, <table
expression> …]
[WHERE <Boolean expression>]
[GROUP BY <column expression>[,
<column expression> …]
[HAVING <Boolean expression>]]
SQL language
Aggregate functions perform
a calculation on a set of
values and return a single
value. Except for COUNT(*),
aggregate functions ignore
null values.

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

<Cartesian Product operator>


CROSS JOIN
,
JOINs

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.

Expressio • CTEs can be used in user-

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

You might also like