Database Management System - SQL Advanced Training

Moutasm Tamimi
Moutasm Tamimiwww.it-trg.com - CEO
Database Management System
Advanced Training
Practices in 2017
Prepared by: Moutasm Tamimi
Using SQL language
Microsoft SQL Server Management Studio
Versions (2008-2010-2012-2014)
Speaker Information
 Moutasm tamimi
Independent consultant , IT Researcher , CEO at ITG7
Instructor of: Project Development.
DBMS.
.NET applications.
Digital marketing.
Email: tamimi@itg7.com
LinkedIn: click here.
Database Management System - SQL Advanced Training
Joins
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
PName Price
SingleTouch $149.99
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
More Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all Chinese companies that manufacture products both in the
‘electronic’ and ‘toy’ categories
SELECT cname
FROM
WHERE
Cross Join
There are two tables A and B
A has a column Id and data (1,2,3)
B has a column Id and data (A,B)
If I put
Select A.Id, B.Id from A,B
This generates output as
A 1
B 1
C 1
A 2
B 2
C 2
Self Join
There is a table called Emp with the following structure:
empid ename mgrid
1 A null
2 B 1
3 C 1
4 D 2
If I want to print all managers using self join, I should write quey as:
select e1.ename from
emp e1,emp e2
where e1.mgrid = e2.empid
Inner Join
I have 2 tables Student(sid,Name) and Marks(Sid,Subject,Score)
If I want to print the marks of all students in the following format,
Name Subject Score
Select Name,Subject,Score from
Student s join Marks m
On s.sid = m.sid
Outer Join
 Right outer Join
 Print all the records in the second table with null values for missing records in the first
table
 Left outer Join
 Print all the records in the first table with null values for missing records in the second
table
 Full outer Join
 Prints all records in both the table with null values for missing records in both the table
Left Outer Join
I have a table Employee (Eid, Ename, Mid) and
a table Machine (Mid,ManufacturerName)
Employee
EidEName Mid
1 ABC1
2 DEF 3
Machine
Mid ManufacturerName
1 Zenith
2 HP
Left Outer Join
I want to print the employee name and machine name.
If I write a query using inner join, then the second employee will
not be displayed as the mid in his record is not avilable with the second
table.
So I go for left outer join. The query is as shown below:
Select Ename, ManufacturerName from Employee e left outer join
Machine m on e.Mid = m.Mid
Right outer Join
Assume data in the tables like this:
Employee
EidEName Mid
1 ABC1
2 DEF
Machine
Mid ManufacturerName
1 Zenith
2 HP
Right Outer Join
If I want to find which machine is unallocated, I can use right outer join.
The query is as follows:
Select Ename, ManufacturerName from Employee e right outer join
Machine m on e.Mid = m.Mid
This yields a result
ABCZenith
HP
Full Outer Join
Assume data in the tables like this:
Employee
EidEName Mid
1 ABC 1
2 DEF
3 GHI 2
Machine
Mid ManufacturerName
1 Zenith
2 HP
3 Compaq
Full Outer Join
If I want to find people who have been un allocated with a system and
machines that are been un allocated, I can go for full outer join.
Query is like this:
Select Ename, ManufacturerName from Employee e full outer join
Machine m on e.Mid = m.Mid
This yields a result
ABC Zenith
DEF
GHIHP
Compaq
Tuple Variables
SELECT DISTINCT pname, address
FROM Person, Company
WHERE worksfor = cname
Which
address ?
Person(pname, address, worksfor)
Company(cname, address)
SELECT DISTINCT Person.pname, Company.address
FROM Person, Company
WHERE Person.worksfor = Company.cname
SELECT DISTINCT x.pname, y.address
FROM Person AS x, Company AS y
WHERE x.worksfor = y.cname
SQL Functions
 SQL Avg()
 SQL Count()
 SQL First()
 SQL Last()
 SQL Max()
 SQL Min()
 SQL Sum()
 SQL Group By
• SQL HavingSQL Ucase()
• SQL Lcase()
• SQL Mid()
• SQL Len()
• SQL Round()
• SQL Now()
• SQL Format()
Aggregation
SELECT count(*)
FROM Product
WHERE year > 1995
Except count, all aggregations apply to a single attribute
SELECT avg(price)
FROM Product
WHERE maker=“Toyota”
SQL supports several aggregation operations:
sum, count, min, max, avg
COUNT applies to duplicates, unless otherwise stated:
SELECT Count(category)
FROM Product
WHERE year > 1995
same as Count(*)
We probably want:
SELECT Count(DISTINCT category)
FROM Product
WHERE year > 1995
Aggregation: Count
Purchase(product, date, price, quantity)
More Examples
SELECT Sum(price * quantity)
FROM Purchase
SELECT Sum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
What do
they mean ?
Simple Aggregations
Purchase
Product Date Price Quantity
Bagel 10/21 1 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Bagel 10/25 1.50 20
SELECT Sum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
50 (= 20+30)
Grouping and Aggregation
Purchase(product, date, price, quantity)
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
Let’s see what this means…
Find total sales after 10/1/2005 per product.
Grouping and Aggregation
1. Compute the FROM and WHERE clauses.
2. Group by the attributes in the GROUPBY
3. Compute the SELECT clause: grouped attributes and aggregates.
1&2. FROM-WHERE-GROUPBY
Product Date Price Quantity
Bagel 10/21 1 20
Bagel 10/25 1.50 20
Banana 10/3 0.5 10
Banana 10/10 1 10
3. SELECT
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
Product Date Price Quantity
Bagel 10/21 1 20
Bagel 10/25 1.50 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Product TotalSales
Bagel 50
Banana 15
GROUP BY v.s. Nested Quereis
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity)
FROM Purchase y
WHERE x.product = y.product
AND y.date > ‘10/1/2005’)
AS TotalSales
FROM Purchase x
WHERE x.date > ‘10/1/2005’
Another Example
SELECT product,
sum(price * quantity) AS SumSales
max(quantity) AS MaxQuantity
FROM Purchase
GROUP BY product
What does
it mean ?
HAVING Clause
SELECT product, Sum(price * quantity)
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
HAVING Sum(quantity) > 30
Same query, except that we consider only products that had
at least 100 buyers.
HAVING clause contains conditions on aggregates.
General form of Grouping and
Aggregation
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2
S = may contain attributes a1,…,ak and/or any aggregates but NO OTHER
ATTRIBUTES
C1 = is any condition on the attributes in R1,…,Rn
C2 = is any condition on aggregate expressions
Why ?
General form of Grouping and Aggregation
Evaluation steps:
1. Evaluate FROM-WHERE, apply condition C1
2. Group by the attributes a1,…,ak
3. Apply condition C2 to each group (may have aggregates)
4. Compute aggregates in S and return the result
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2
Advanced SQLizing
1. Getting around INTERSECT and EXCEPT
2. Quantifiers
3. Aggregation v.s. subqueries
1. INTERSECT and EXCEPT:
(SELECT R.A, R.B
FROM R)
INTERSECT
(SELECT S.A, S.B
FROM S)
SELECT R.A, R.B
FROM R
WHERE
EXISTS(SELECT *
FROM S
WHERE R.A=S.A and R.B=S.B)
(SELECT R.A, R.B
FROM R)
EXCEPT
(SELECT S.A, S.B
FROM S)
SELECT R.A, R.B
FROM R
WHERE
NOT EXISTS(SELECT *
FROM S
WHERE R.A=S.A and R.B=S.B)
If R, S have no
duplicates, then can
write without
subqueries
(HOW ?)
INTERSECT and EXCEPT: not in SQL Server
2. Quantifiers
Product ( pname, price, company)
Company( cname, city)
Find all companies that make some products with price < 100
SELECT DISTINCT Company.cname
FROM Company, Product
WHERE Company.cname = Product.company and Product.price < 100
Existential: easy ! 
2. Quantifiers
Product ( pname, price, company)
Company( cname, city)
Find all companies s.t. all of their products have price < 100
Universal: hard ! 
Find all companies that make only products with price < 100
same as:
2. Quantifiers
2. Find all companies s.t. all their products have price < 100
1. Find the other companies: i.e. s.t. some product  100
SELECT DISTINCT Company.cname
FROM Company
WHERE Company.cname IN (SELECT Product.company
FROM Product
WHERE Produc.price >= 100
SELECT DISTINCT Company.cname
FROM Company
WHERE Company.cname NOT IN (SELECT Product.company
FROM Product
WHERE Produc.price >= 100
3. Group-by v.s. Nested Query
 Find authors who wrote  10 documents:
 Attempt 1: with nested queries
SELECT DISTINCT Author.name
FROM Author
WHERE count(SELECT Wrote.url
FROM Wrote
WHERE Author.login=Wrote.login)
> 10
This is
SQL by
a novice
Author(login,name)
Wrote(login,url)
3. Group-by v.s. Nested Query
 Find all authors who wrote at least 10 documents:
 Attempt 2: SQL style (with GROUP BY)
SELECT Author.name
FROM Author, Wrote
WHERE Author.login=Wrote.login
GROUP BY Author.name
HAVING count(wrote.url) > 10
This is
SQL by
an expert
No need for DISTINCT: automatically from GROUP BY
3. Group-by v.s. Nested Query
Find authors with vocabulary  10000 words:
SELECT Author.name
FROM Author, Wrote, Mentions
WHERE Author.login=Wrote.login AND Wrote.url=Mentions.url
GROUP BY Author.name
HAVING count(distinct Mentions.word) > 10000
Author(login,name)
Wrote(login,url)
Mentions(url,word)
Two Examples
Store(sid, sname)
Product(pid, pname, price, sid)
Find all stores that sell only products with price > 100
same as:
Find all stores s.t. all their products have price > 100)
SELECT Store.name
FROM Store, Product
WHERE Store.sid = Product.sid
GROUP BY Store.sid, Store.name
HAVING 100 < min(Product.price)
SELECT Store.name
FROM Store
WHERE Store.sid NOT IN
(SELECT Product.sid
FROM Product
WHERE Product.price <= 100)
SELECT Store.name
FROM Store
WHERE
100 < ALL (SELECT Product.price
FROM product
WHERE Store.sid = Product.sid)
Almost equivalent…
Why both ?
Two Examples
Store(sid, sname)
Product(pid, pname, price, sid)
For each store,
find its most expensive product
Two Examples
SELECT Store.sname, max(Product.price)
FROM Store, Product
WHERE Store.sid = Product.sid
GROUP BY Store.sid, Store.sname
SELECT Store.sname, x.pname
FROM Store, Product x
WHERE Store.sid = x.sid and
x.price >=
ALL (SELECT y.price
FROM Product y
WHERE Store.sid = y.sid)
This is easy but doesn’t do what we want:
Better:
But may
return
multiple
product names
per store
Two Examples
SELECT Store.sname, max(x.pname)
FROM Store, Product x
WHERE Store.sid = x.sid and
x.price >=
ALL (SELECT y.price
FROM Product y
WHERE Store.sid = y.sid)
GROUP BY Store.sname
Finally, choose some pid arbitrarily, if there are many
with highest price:
NULLS in SQL
 Whenever we don’t have a value, we can put a NULL
 Can mean many things:
 Value does not exists
 Value exists but is unknown
 Value not applicable
 Etc.
 The schema specifies for each attribute if can be null (nullable
attribute) or not
 How does SQL cope with tables that have NULLs ?
Null Values
 If x= NULL then 4*(3-x)/7 is still NULL
 If x= NULL then x=“Joe” is UNKNOWN
 In SQL there are three boolean values:
FALSE = 0
UNKNOWN = 0.5
TRUE = 1
Null Values
 C1 AND C2 = min(C1, C2)
 C1 OR C2 = max(C1, C2)
 NOT C1 = 1 – C1
Rule in SQL: include only tuples that yield TRUE
SELECT *
FROM Person
WHERE (age < 25) AND
(height > 6 OR weight > 190)
E.g.
age=20
heigth=NULL
weight=200
Null Values
Unexpected behavior:
Some Persons are not included !
SELECT *
FROM Person
WHERE age < 25 OR age >= 25
Null Values
Can test for NULL explicitly:
 x IS NULL
 x IS NOT NULL
Now it includes all Persons
SELECT *
FROM Person
WHERE age < 25 OR age >= 25 OR age IS NULL
Outerjoins
Explicit joins in SQL = “inner joins”:
Product(name, category)
Purchase(prodName, store)
SELECT Product.name, Purchase.store
FROM Product JOIN Purchase ON
Product.name = Purchase.prodName
SELECT Product.name, Purchase.store
FROM Product, Purchase
WHERE Product.name = Purchase.prodName
Same as:
But Products that never sold will be lost !
Outerjoins
Left outer joins in SQL:
Product(name, category)
Purchase(prodName, store)
SELECT Product.name, Purchase.store
FROM Product LEFT OUTER JOIN Purchase ON
Product.name = Purchase.prodName
Name Category
Gizmo gadget
Camera Photo
OneClick Photo
ProdName Store
Gizmo Wiz
Camera Ritz
Camera Wiz
Name Store
Gizmo Wiz
Camera Ritz
Camera Wiz
OneClick NULL
Product Purchase
Application
Compute, for each product, the total number of sales in
‘September’
Product(name, category)
Purchase(prodName, month, store)
SELECT Product.name, count(*)
FROM Product, Purchase
WHERE Product.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
What’s wrong ?
Application
Compute, for each product, the total number of sales in
‘September’
Product(name, category)
Purchase(prodName, month, store)
SELECT Product.name, count(*)
FROM Product LEFT OUTER JOIN Purchase ON
Product.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
Now we also get the products who sold in 0 quantity
Outer Joins
 Left outer join:
 Include the left tuple even if there’s no match
 Right outer join:
 Include the right tuple even if there’s no match
 Full outer join:
 Include the both left and right tuples even if there’s no match
Modifying the Database
Three kinds of modifications
 Insertions
 Deletions
 Updates
Sometimes they are all called “updates”
Insertions
General form:
Missing attribute  NULL.
May drop attribute names if give them in order.
INSERT INTO R(A1,…., An) VALUES (v1,…., vn)
INSERT INTO Purchase(buyer, seller, product, store)
VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’,
‘The Sharper Image’)
Example: Insert a new purchase to the database:
Insertions
INSERT INTO PRODUCT(name)
SELECT DISTINCT Purchase.product
FROM Purchase
WHERE Purchase.date > “10/26/01”
The query replaces the VALUES keyword.
Here we insert many tuples into PRODUCT
Insertion: an Example
prodName is foreign key in Product.name
Suppose database got corrupted and we need to fix it:
name listPrice category
gizmo 100 gadgets
prodName buyerName price
camera John 200
gizmo Smith 80
camera Smith 225
Task: insert in Product all prodNames from Purchase
Product
Product(name, listPrice, category)
Purchase(prodName, buyerName, price)
Purchase
Insertion: an Example
INSERT INTO Product(name)
SELECT DISTINCT prodName
FROM Purchase
WHERE prodName NOT IN (SELECT name FROM Product)
name listPrice category
gizmo 100 Gadgets
camera - -
Insertion: an Example
INSERT INTO Product(name, listPrice)
SELECT DISTINCT prodName, price
FROM Purchase
WHERE prodName NOT IN (SELECT name FROM Product)
name listPrice category
gizmo 100 Gadgets
camera 200 -
camera ?? 225 ?? -
Depends on the implementation
Deletions
DELETE FROM PURCHASE
WHERE seller = ‘Joe’ AND
product = ‘Brooklyn Bridge’
Factoid about SQL: there is no way to delete only a single
occurrence of a tuple that appears twice
in a relation.
Example:
Updates
UPDATE PRODUCT
SET price = price/2
WHERE Product.name IN
(SELECT product
FROM Purchase
WHERE Date =‘Oct, 25, 1999’);
Example:
Database Management System
Advanced Training
Practices in 2017
Prepared by: Moutasm Tamimi
Using SQL language
Microsoft SQL Server Management Studio
Versions (2008-2010-2012-2014)
1 sur 63

Recommandé

Database Management System - SQL beginner Training par
Database Management System - SQL beginner Training Database Management System - SQL beginner Training
Database Management System - SQL beginner Training Moutasm Tamimi
1.3K vues41 diapositives
1 data types par
1 data types1 data types
1 data typesRam Kedem
1.7K vues30 diapositives
Visualbasic tutorial par
Visualbasic tutorialVisualbasic tutorial
Visualbasic tutorialeduardo huarcaya rios
439 vues15 diapositives
Introduction to SQL (for Chicago Booth MBA technology club) par
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
6.9K vues30 diapositives
My Sql concepts par
My Sql conceptsMy Sql concepts
My Sql conceptsPragya Rastogi
415 vues7 diapositives
Sql for biggner par
Sql for biggnerSql for biggner
Sql for biggnerArvind Kumar
491 vues54 diapositives

Contenu connexe

Tendances

BIS05 Introduction to SQL par
BIS05 Introduction to SQLBIS05 Introduction to SQL
BIS05 Introduction to SQLPrithwis Mukerjee
2.1K vues30 diapositives
Introduction to SQL par
Introduction to SQLIntroduction to SQL
Introduction to SQLAmin Choroomi
389 vues29 diapositives
4 execution plans par
4 execution plans4 execution plans
4 execution plansRam Kedem
881 vues23 diapositives
Sql par
SqlSql
Sqlsatu2412
109 vues35 diapositives
Learning sql from w3schools par
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schoolsfarhan516
8K vues110 diapositives
Introduction to SQL par
Introduction to SQLIntroduction to SQL
Introduction to SQLMahir Mahtab Haque
63 vues23 diapositives

Tendances(20)

4 execution plans par Ram Kedem
4 execution plans4 execution plans
4 execution plans
Ram Kedem881 vues
Learning sql from w3schools par farhan516
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
farhan5168K vues
Structure query language (sql) par Nalina Kumari
Structure query language (sql)Structure query language (sql)
Structure query language (sql)
Nalina Kumari196 vues
[Basic HTML/CSS] 4. html - form tags par Hyejin Oh
[Basic HTML/CSS] 4. html - form tags[Basic HTML/CSS] 4. html - form tags
[Basic HTML/CSS] 4. html - form tags
Hyejin Oh594 vues
Introduction To Oracle Sql par Ahmed Yaseen
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle Sql
Ahmed Yaseen3.1K vues
05 html-forms par Palakshya
05 html-forms05 html-forms
05 html-forms
Palakshya627 vues
Microsoft MCSA 70-457 it exams dumps par lilylucy
Microsoft MCSA 70-457 it exams dumpsMicrosoft MCSA 70-457 it exams dumps
Microsoft MCSA 70-457 it exams dumps
lilylucy166 vues
SQL Queries par Nilt1234
SQL QueriesSQL Queries
SQL Queries
Nilt1234702 vues
HTML Forms Tutorial par ProdigyView
HTML Forms TutorialHTML Forms Tutorial
HTML Forms Tutorial
ProdigyView2.1K vues

Similaire à Database Management System - SQL Advanced Training

SQL BASICS.pptx par
SQL BASICS.pptxSQL BASICS.pptx
SQL BASICS.pptxJEEVA R
8 vues78 diapositives
Oracle SQL ppt.ppt par
Oracle SQL ppt.pptOracle SQL ppt.ppt
Oracle SQL ppt.pptMushDev
11 vues78 diapositives
Lecture sql par
Lecture sqlLecture sql
Lecture sqlSini
65 vues78 diapositives
lecture-sql.ppt par
lecture-sql.pptlecture-sql.ppt
lecture-sql.pptrahulnadola3
7 vues78 diapositives
lecture-sql.ppt par
lecture-sql.pptlecture-sql.ppt
lecture-sql.pptJackpeterNdati
6 vues78 diapositives
lecture-sql.ppt par
lecture-sql.pptlecture-sql.ppt
lecture-sql.pptYashaswiniSrinivasan1
6 vues78 diapositives

Similaire à Database Management System - SQL Advanced Training(20)

Plus de Moutasm Tamimi

Software Quality Assessment Practices par
Software Quality Assessment PracticesSoftware Quality Assessment Practices
Software Quality Assessment PracticesMoutasm Tamimi
670 vues28 diapositives
Reengineering PDF-Based Documents Targeting Complex Software Specifications par
Reengineering PDF-Based Documents Targeting Complex Software SpecificationsReengineering PDF-Based Documents Targeting Complex Software Specifications
Reengineering PDF-Based Documents Targeting Complex Software SpecificationsMoutasm Tamimi
163 vues30 diapositives
Software Evolution and Maintenance Models par
Software Evolution and Maintenance ModelsSoftware Evolution and Maintenance Models
Software Evolution and Maintenance ModelsMoutasm Tamimi
4.7K vues20 diapositives
Software evolution and maintenance basic concepts and preliminaries par
Software evolution and maintenance   basic concepts and preliminariesSoftware evolution and maintenance   basic concepts and preliminaries
Software evolution and maintenance basic concepts and preliminariesMoutasm Tamimi
1K vues31 diapositives
An integrated security testing framework and tool par
An integrated security testing framework  and toolAn integrated security testing framework  and tool
An integrated security testing framework and toolMoutasm Tamimi
932 vues47 diapositives
Critical Success Factors along ERP life-cycle in Small medium enterprises par
Critical Success Factors along ERP life-cycle in Small medium enterprises Critical Success Factors along ERP life-cycle in Small medium enterprises
Critical Success Factors along ERP life-cycle in Small medium enterprises Moutasm Tamimi
839 vues44 diapositives

Plus de Moutasm Tamimi(16)

Software Quality Assessment Practices par Moutasm Tamimi
Software Quality Assessment PracticesSoftware Quality Assessment Practices
Software Quality Assessment Practices
Moutasm Tamimi670 vues
Reengineering PDF-Based Documents Targeting Complex Software Specifications par Moutasm Tamimi
Reengineering PDF-Based Documents Targeting Complex Software SpecificationsReengineering PDF-Based Documents Targeting Complex Software Specifications
Reengineering PDF-Based Documents Targeting Complex Software Specifications
Moutasm Tamimi163 vues
Software Evolution and Maintenance Models par Moutasm Tamimi
Software Evolution and Maintenance ModelsSoftware Evolution and Maintenance Models
Software Evolution and Maintenance Models
Moutasm Tamimi4.7K vues
Software evolution and maintenance basic concepts and preliminaries par Moutasm Tamimi
Software evolution and maintenance   basic concepts and preliminariesSoftware evolution and maintenance   basic concepts and preliminaries
Software evolution and maintenance basic concepts and preliminaries
Moutasm Tamimi1K vues
An integrated security testing framework and tool par Moutasm Tamimi
An integrated security testing framework  and toolAn integrated security testing framework  and tool
An integrated security testing framework and tool
Moutasm Tamimi932 vues
Critical Success Factors along ERP life-cycle in Small medium enterprises par Moutasm Tamimi
Critical Success Factors along ERP life-cycle in Small medium enterprises Critical Success Factors along ERP life-cycle in Small medium enterprises
Critical Success Factors along ERP life-cycle in Small medium enterprises
Moutasm Tamimi839 vues
Critical Success Factors (CSFs) In International ERP Implementations with que... par Moutasm Tamimi
Critical Success Factors (CSFs) In International ERP Implementations with que...Critical Success Factors (CSFs) In International ERP Implementations with que...
Critical Success Factors (CSFs) In International ERP Implementations with que...
Moutasm Tamimi554 vues
Best Practices For Business Analyst - Part 3 par Moutasm Tamimi
Best Practices For Business Analyst - Part 3Best Practices For Business Analyst - Part 3
Best Practices For Business Analyst - Part 3
Moutasm Tamimi840 vues
Concepts Of business analyst Practices - Part 1 par Moutasm Tamimi
Concepts Of business analyst Practices - Part 1Concepts Of business analyst Practices - Part 1
Concepts Of business analyst Practices - Part 1
Moutasm Tamimi989 vues
Recovery in Multi database Systems par Moutasm Tamimi
Recovery in Multi database SystemsRecovery in Multi database Systems
Recovery in Multi database Systems
Moutasm Tamimi2.3K vues
Software Quality Models: A Comparative Study paper par Moutasm Tamimi
Software Quality Models: A Comparative Study  paperSoftware Quality Models: A Comparative Study  paper
Software Quality Models: A Comparative Study paper
Moutasm Tamimi4.6K vues
ISO 29110 Software Quality Model For Software SMEs par Moutasm Tamimi
ISO 29110 Software Quality Model For Software SMEsISO 29110 Software Quality Model For Software SMEs
ISO 29110 Software Quality Model For Software SMEs
Moutasm Tamimi1.5K vues
Windows form application - C# Training par Moutasm Tamimi
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training
Moutasm Tamimi5.8K vues
Asp.net Programming Training (Web design, Web development) par Moutasm Tamimi
Asp.net Programming Training (Web design, Web  development)Asp.net Programming Training (Web design, Web  development)
Asp.net Programming Training (Web design, Web development)
Moutasm Tamimi1.1K vues
Measurement and Quality in Object-Oriented Design par Moutasm Tamimi
Measurement and Quality in Object-Oriented DesignMeasurement and Quality in Object-Oriented Design
Measurement and Quality in Object-Oriented Design
Moutasm Tamimi358 vues
SQL Injection and Clickjacking Attack in Web security par Moutasm Tamimi
SQL Injection and Clickjacking Attack in Web securitySQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web security
Moutasm Tamimi1.2K vues

Dernier

Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT par
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITUpdates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITShapeBlue
138 vues8 diapositives
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... par
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...ShapeBlue
128 vues20 diapositives
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... par
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...ShapeBlue
69 vues29 diapositives
Digital Personal Data Protection (DPDP) Practical Approach For CISOs par
Digital Personal Data Protection (DPDP) Practical Approach For CISOsDigital Personal Data Protection (DPDP) Practical Approach For CISOs
Digital Personal Data Protection (DPDP) Practical Approach For CISOsPriyanka Aash
103 vues59 diapositives
Business Analyst Series 2023 - Week 4 Session 7 par
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7DianaGray10
110 vues31 diapositives
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue par
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueShapeBlue
191 vues23 diapositives

Dernier(20)

Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT par ShapeBlue
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITUpdates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
ShapeBlue138 vues
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... par ShapeBlue
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
ShapeBlue128 vues
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... par ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue69 vues
Digital Personal Data Protection (DPDP) Practical Approach For CISOs par Priyanka Aash
Digital Personal Data Protection (DPDP) Practical Approach For CISOsDigital Personal Data Protection (DPDP) Practical Approach For CISOs
Digital Personal Data Protection (DPDP) Practical Approach For CISOs
Priyanka Aash103 vues
Business Analyst Series 2023 - Week 4 Session 7 par DianaGray10
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7
DianaGray10110 vues
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue par ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue191 vues
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... par ShapeBlue
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
ShapeBlue48 vues
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue par ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
ShapeBlue75 vues
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... par Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker50 vues
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ par ShapeBlue
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
ShapeBlue58 vues
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... par ShapeBlue
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
ShapeBlue74 vues
The Power of Heat Decarbonisation Plans in the Built Environment par IES VE
The Power of Heat Decarbonisation Plans in the Built EnvironmentThe Power of Heat Decarbonisation Plans in the Built Environment
The Power of Heat Decarbonisation Plans in the Built Environment
IES VE67 vues
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates par ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue178 vues
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online par ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue154 vues
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... par ShapeBlue
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
ShapeBlue113 vues
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue par ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
ShapeBlue68 vues
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue par ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue134 vues
"Surviving highload with Node.js", Andrii Shumada par Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays49 vues
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit... par ShapeBlue
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
ShapeBlue86 vues

Database Management System - SQL Advanced Training

  • 1. Database Management System Advanced Training Practices in 2017 Prepared by: Moutasm Tamimi Using SQL language Microsoft SQL Server Management Studio Versions (2008-2010-2012-2014)
  • 2. Speaker Information  Moutasm tamimi Independent consultant , IT Researcher , CEO at ITG7 Instructor of: Project Development. DBMS. .NET applications. Digital marketing. Email: tamimi@itg7.com LinkedIn: click here.
  • 4. Joins PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan PName Price SingleTouch $149.99 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
  • 5. More Joins Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all Chinese companies that manufacture products both in the ‘electronic’ and ‘toy’ categories SELECT cname FROM WHERE
  • 6. Cross Join There are two tables A and B A has a column Id and data (1,2,3) B has a column Id and data (A,B) If I put Select A.Id, B.Id from A,B This generates output as A 1 B 1 C 1 A 2 B 2 C 2
  • 7. Self Join There is a table called Emp with the following structure: empid ename mgrid 1 A null 2 B 1 3 C 1 4 D 2 If I want to print all managers using self join, I should write quey as: select e1.ename from emp e1,emp e2 where e1.mgrid = e2.empid
  • 8. Inner Join I have 2 tables Student(sid,Name) and Marks(Sid,Subject,Score) If I want to print the marks of all students in the following format, Name Subject Score Select Name,Subject,Score from Student s join Marks m On s.sid = m.sid
  • 9. Outer Join  Right outer Join  Print all the records in the second table with null values for missing records in the first table  Left outer Join  Print all the records in the first table with null values for missing records in the second table  Full outer Join  Prints all records in both the table with null values for missing records in both the table
  • 10. Left Outer Join I have a table Employee (Eid, Ename, Mid) and a table Machine (Mid,ManufacturerName) Employee EidEName Mid 1 ABC1 2 DEF 3 Machine Mid ManufacturerName 1 Zenith 2 HP
  • 11. Left Outer Join I want to print the employee name and machine name. If I write a query using inner join, then the second employee will not be displayed as the mid in his record is not avilable with the second table. So I go for left outer join. The query is as shown below: Select Ename, ManufacturerName from Employee e left outer join Machine m on e.Mid = m.Mid
  • 12. Right outer Join Assume data in the tables like this: Employee EidEName Mid 1 ABC1 2 DEF Machine Mid ManufacturerName 1 Zenith 2 HP
  • 13. Right Outer Join If I want to find which machine is unallocated, I can use right outer join. The query is as follows: Select Ename, ManufacturerName from Employee e right outer join Machine m on e.Mid = m.Mid This yields a result ABCZenith HP
  • 14. Full Outer Join Assume data in the tables like this: Employee EidEName Mid 1 ABC 1 2 DEF 3 GHI 2 Machine Mid ManufacturerName 1 Zenith 2 HP 3 Compaq
  • 15. Full Outer Join If I want to find people who have been un allocated with a system and machines that are been un allocated, I can go for full outer join. Query is like this: Select Ename, ManufacturerName from Employee e full outer join Machine m on e.Mid = m.Mid This yields a result ABC Zenith DEF GHIHP Compaq
  • 16. Tuple Variables SELECT DISTINCT pname, address FROM Person, Company WHERE worksfor = cname Which address ? Person(pname, address, worksfor) Company(cname, address) SELECT DISTINCT Person.pname, Company.address FROM Person, Company WHERE Person.worksfor = Company.cname SELECT DISTINCT x.pname, y.address FROM Person AS x, Company AS y WHERE x.worksfor = y.cname
  • 17. SQL Functions  SQL Avg()  SQL Count()  SQL First()  SQL Last()  SQL Max()  SQL Min()  SQL Sum()  SQL Group By • SQL HavingSQL Ucase() • SQL Lcase() • SQL Mid() • SQL Len() • SQL Round() • SQL Now() • SQL Format()
  • 18. Aggregation SELECT count(*) FROM Product WHERE year > 1995 Except count, all aggregations apply to a single attribute SELECT avg(price) FROM Product WHERE maker=“Toyota” SQL supports several aggregation operations: sum, count, min, max, avg
  • 19. COUNT applies to duplicates, unless otherwise stated: SELECT Count(category) FROM Product WHERE year > 1995 same as Count(*) We probably want: SELECT Count(DISTINCT category) FROM Product WHERE year > 1995 Aggregation: Count
  • 20. Purchase(product, date, price, quantity) More Examples SELECT Sum(price * quantity) FROM Purchase SELECT Sum(price * quantity) FROM Purchase WHERE product = ‘bagel’ What do they mean ?
  • 21. Simple Aggregations Purchase Product Date Price Quantity Bagel 10/21 1 20 Banana 10/3 0.5 10 Banana 10/10 1 10 Bagel 10/25 1.50 20 SELECT Sum(price * quantity) FROM Purchase WHERE product = ‘bagel’ 50 (= 20+30)
  • 22. Grouping and Aggregation Purchase(product, date, price, quantity) SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product Let’s see what this means… Find total sales after 10/1/2005 per product.
  • 23. Grouping and Aggregation 1. Compute the FROM and WHERE clauses. 2. Group by the attributes in the GROUPBY 3. Compute the SELECT clause: grouped attributes and aggregates.
  • 24. 1&2. FROM-WHERE-GROUPBY Product Date Price Quantity Bagel 10/21 1 20 Bagel 10/25 1.50 20 Banana 10/3 0.5 10 Banana 10/10 1 10
  • 25. 3. SELECT SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product Product Date Price Quantity Bagel 10/21 1 20 Bagel 10/25 1.50 20 Banana 10/3 0.5 10 Banana 10/10 1 10 Product TotalSales Bagel 50 Banana 15
  • 26. GROUP BY v.s. Nested Quereis SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity) FROM Purchase y WHERE x.product = y.product AND y.date > ‘10/1/2005’) AS TotalSales FROM Purchase x WHERE x.date > ‘10/1/2005’
  • 27. Another Example SELECT product, sum(price * quantity) AS SumSales max(quantity) AS MaxQuantity FROM Purchase GROUP BY product What does it mean ?
  • 28. HAVING Clause SELECT product, Sum(price * quantity) FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product HAVING Sum(quantity) > 30 Same query, except that we consider only products that had at least 100 buyers. HAVING clause contains conditions on aggregates.
  • 29. General form of Grouping and Aggregation SELECT S FROM R1,…,Rn WHERE C1 GROUP BY a1,…,ak HAVING C2 S = may contain attributes a1,…,ak and/or any aggregates but NO OTHER ATTRIBUTES C1 = is any condition on the attributes in R1,…,Rn C2 = is any condition on aggregate expressions Why ?
  • 30. General form of Grouping and Aggregation Evaluation steps: 1. Evaluate FROM-WHERE, apply condition C1 2. Group by the attributes a1,…,ak 3. Apply condition C2 to each group (may have aggregates) 4. Compute aggregates in S and return the result SELECT S FROM R1,…,Rn WHERE C1 GROUP BY a1,…,ak HAVING C2
  • 31. Advanced SQLizing 1. Getting around INTERSECT and EXCEPT 2. Quantifiers 3. Aggregation v.s. subqueries
  • 32. 1. INTERSECT and EXCEPT: (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A, S.B FROM S) SELECT R.A, R.B FROM R WHERE EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B) (SELECT R.A, R.B FROM R) EXCEPT (SELECT S.A, S.B FROM S) SELECT R.A, R.B FROM R WHERE NOT EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B) If R, S have no duplicates, then can write without subqueries (HOW ?) INTERSECT and EXCEPT: not in SQL Server
  • 33. 2. Quantifiers Product ( pname, price, company) Company( cname, city) Find all companies that make some products with price < 100 SELECT DISTINCT Company.cname FROM Company, Product WHERE Company.cname = Product.company and Product.price < 100 Existential: easy ! 
  • 34. 2. Quantifiers Product ( pname, price, company) Company( cname, city) Find all companies s.t. all of their products have price < 100 Universal: hard !  Find all companies that make only products with price < 100 same as:
  • 35. 2. Quantifiers 2. Find all companies s.t. all their products have price < 100 1. Find the other companies: i.e. s.t. some product  100 SELECT DISTINCT Company.cname FROM Company WHERE Company.cname IN (SELECT Product.company FROM Product WHERE Produc.price >= 100 SELECT DISTINCT Company.cname FROM Company WHERE Company.cname NOT IN (SELECT Product.company FROM Product WHERE Produc.price >= 100
  • 36. 3. Group-by v.s. Nested Query  Find authors who wrote  10 documents:  Attempt 1: with nested queries SELECT DISTINCT Author.name FROM Author WHERE count(SELECT Wrote.url FROM Wrote WHERE Author.login=Wrote.login) > 10 This is SQL by a novice Author(login,name) Wrote(login,url)
  • 37. 3. Group-by v.s. Nested Query  Find all authors who wrote at least 10 documents:  Attempt 2: SQL style (with GROUP BY) SELECT Author.name FROM Author, Wrote WHERE Author.login=Wrote.login GROUP BY Author.name HAVING count(wrote.url) > 10 This is SQL by an expert No need for DISTINCT: automatically from GROUP BY
  • 38. 3. Group-by v.s. Nested Query Find authors with vocabulary  10000 words: SELECT Author.name FROM Author, Wrote, Mentions WHERE Author.login=Wrote.login AND Wrote.url=Mentions.url GROUP BY Author.name HAVING count(distinct Mentions.word) > 10000 Author(login,name) Wrote(login,url) Mentions(url,word)
  • 39. Two Examples Store(sid, sname) Product(pid, pname, price, sid) Find all stores that sell only products with price > 100 same as: Find all stores s.t. all their products have price > 100)
  • 40. SELECT Store.name FROM Store, Product WHERE Store.sid = Product.sid GROUP BY Store.sid, Store.name HAVING 100 < min(Product.price) SELECT Store.name FROM Store WHERE Store.sid NOT IN (SELECT Product.sid FROM Product WHERE Product.price <= 100) SELECT Store.name FROM Store WHERE 100 < ALL (SELECT Product.price FROM product WHERE Store.sid = Product.sid) Almost equivalent… Why both ?
  • 41. Two Examples Store(sid, sname) Product(pid, pname, price, sid) For each store, find its most expensive product
  • 42. Two Examples SELECT Store.sname, max(Product.price) FROM Store, Product WHERE Store.sid = Product.sid GROUP BY Store.sid, Store.sname SELECT Store.sname, x.pname FROM Store, Product x WHERE Store.sid = x.sid and x.price >= ALL (SELECT y.price FROM Product y WHERE Store.sid = y.sid) This is easy but doesn’t do what we want: Better: But may return multiple product names per store
  • 43. Two Examples SELECT Store.sname, max(x.pname) FROM Store, Product x WHERE Store.sid = x.sid and x.price >= ALL (SELECT y.price FROM Product y WHERE Store.sid = y.sid) GROUP BY Store.sname Finally, choose some pid arbitrarily, if there are many with highest price:
  • 44. NULLS in SQL  Whenever we don’t have a value, we can put a NULL  Can mean many things:  Value does not exists  Value exists but is unknown  Value not applicable  Etc.  The schema specifies for each attribute if can be null (nullable attribute) or not  How does SQL cope with tables that have NULLs ?
  • 45. Null Values  If x= NULL then 4*(3-x)/7 is still NULL  If x= NULL then x=“Joe” is UNKNOWN  In SQL there are three boolean values: FALSE = 0 UNKNOWN = 0.5 TRUE = 1
  • 46. Null Values  C1 AND C2 = min(C1, C2)  C1 OR C2 = max(C1, C2)  NOT C1 = 1 – C1 Rule in SQL: include only tuples that yield TRUE SELECT * FROM Person WHERE (age < 25) AND (height > 6 OR weight > 190) E.g. age=20 heigth=NULL weight=200
  • 47. Null Values Unexpected behavior: Some Persons are not included ! SELECT * FROM Person WHERE age < 25 OR age >= 25
  • 48. Null Values Can test for NULL explicitly:  x IS NULL  x IS NOT NULL Now it includes all Persons SELECT * FROM Person WHERE age < 25 OR age >= 25 OR age IS NULL
  • 49. Outerjoins Explicit joins in SQL = “inner joins”: Product(name, category) Purchase(prodName, store) SELECT Product.name, Purchase.store FROM Product JOIN Purchase ON Product.name = Purchase.prodName SELECT Product.name, Purchase.store FROM Product, Purchase WHERE Product.name = Purchase.prodName Same as: But Products that never sold will be lost !
  • 50. Outerjoins Left outer joins in SQL: Product(name, category) Purchase(prodName, store) SELECT Product.name, Purchase.store FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName
  • 51. Name Category Gizmo gadget Camera Photo OneClick Photo ProdName Store Gizmo Wiz Camera Ritz Camera Wiz Name Store Gizmo Wiz Camera Ritz Camera Wiz OneClick NULL Product Purchase
  • 52. Application Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) SELECT Product.name, count(*) FROM Product, Purchase WHERE Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name What’s wrong ?
  • 53. Application Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) SELECT Product.name, count(*) FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name Now we also get the products who sold in 0 quantity
  • 54. Outer Joins  Left outer join:  Include the left tuple even if there’s no match  Right outer join:  Include the right tuple even if there’s no match  Full outer join:  Include the both left and right tuples even if there’s no match
  • 55. Modifying the Database Three kinds of modifications  Insertions  Deletions  Updates Sometimes they are all called “updates”
  • 56. Insertions General form: Missing attribute  NULL. May drop attribute names if give them in order. INSERT INTO R(A1,…., An) VALUES (v1,…., vn) INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’) Example: Insert a new purchase to the database:
  • 57. Insertions INSERT INTO PRODUCT(name) SELECT DISTINCT Purchase.product FROM Purchase WHERE Purchase.date > “10/26/01” The query replaces the VALUES keyword. Here we insert many tuples into PRODUCT
  • 58. Insertion: an Example prodName is foreign key in Product.name Suppose database got corrupted and we need to fix it: name listPrice category gizmo 100 gadgets prodName buyerName price camera John 200 gizmo Smith 80 camera Smith 225 Task: insert in Product all prodNames from Purchase Product Product(name, listPrice, category) Purchase(prodName, buyerName, price) Purchase
  • 59. Insertion: an Example INSERT INTO Product(name) SELECT DISTINCT prodName FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera - -
  • 60. Insertion: an Example INSERT INTO Product(name, listPrice) SELECT DISTINCT prodName, price FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera 200 - camera ?? 225 ?? - Depends on the implementation
  • 61. Deletions DELETE FROM PURCHASE WHERE seller = ‘Joe’ AND product = ‘Brooklyn Bridge’ Factoid about SQL: there is no way to delete only a single occurrence of a tuple that appears twice in a relation. Example:
  • 62. Updates UPDATE PRODUCT SET price = price/2 WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’); Example:
  • 63. Database Management System Advanced Training Practices in 2017 Prepared by: Moutasm Tamimi Using SQL language Microsoft SQL Server Management Studio Versions (2008-2010-2012-2014)