SlideShare une entreprise Scribd logo
1  sur  29
Practice on
Practical SQL
Hideshi Ogoshi
YNS Philippines Inc.
SEP-22-2016
Misunderstanding of
Object-Relational Mapping
• We use ORM. That does not mean we can totally
rely on it, since it is not totally black boxed to the
developers.
ORM Pros & Cons
• Pros
• Transforms result set into a data structure, which can
be easily handled in the programs
• Handles many kinds of RDBMS transparently with same
code
• Cons
• Hard to control generating SQL
• Hard to use for the complicated requirements
Relational Database
• MySQL, PostgreSQL, Oracle Database, DB2,
MSSQL, SQLite, etc.
• Relational database is based on set theory.
Set Theory
• Set theory is the branch of mathematical logic
that studies sets, which are collections of objects.
Terms of Set Theory
• Member
• Subset
• Union
• Intersection
• Difference
• Tuple
• Selection
• Projection
Member
• A fundamental binary relation between an object o
and a set A.
• o is a member of A, denoted o ∈ A.
• Example: 2 ∈ {1, 2, 3}
1
2
3
Subset
• If all the members of set A are also members of set B.
• A is a subset of B, denoted A ⊆ B.
• Example: {1, 2} ⊆ {1, 2, 3, 4}
1 2
3
4
Union
• Union creates a new set, which contains all the members
of 2 sets.
• Union of the sets A and B, denoted A ∪ B.
• Example: {1, 2, 3} ∪ {2, 3, 4} = {1, 2, 3, 4}
2
31 4
Intersection
• Intersection creates a new set, which contains common
members between 2 sets.
• Intersection of the sets A and B, denoted A ∩ B.
• Example: {1, 2, 3} ∩ {2, 3, 4} = {2, 3}
2
31 4
Difference
• Difference creates a new set, which contains remaining
members in a set after subtracting the set from another set.
• Difference of the sets A and B, denoted A ー B.
• Example: {1, 2, 3} ー {2, 3, 4} = {1}
2
31 4
Tuple
• is a kind of data type, which represents finite
ordered list of elements
• Example: {(a, 1), (b,2), (c, 3)}
(b,2)
(c,3)
(a,1)
Selection
• Selecting all tuples from set T1 if a tuple matches
the conditions. Then creates T2 as new set.
• σ Age >= 34 ^ Weight <= 50 (Person)
(b,2)
(c,3)
(a,1)
(c,3)
(a,1)
T1 T2
Projection
• Picking a sub-set of all available columns
• Modifying an attribute’s value
• Π Age,Weight (Person)
(b,2)
(c,3)
(a,1)
f(x)
f(x)
f(x)
4
6
2
Correspondence
between set theory and RDB
• Table is a set of objects
• Record is a tuple
• SELECT is projection
• WHERE is selection
INNER JOIN
• is an expression, which joins two tables with conditions.
• returns records, which exactly match the conditions.
OUTER JOIN
• LEFT OUTER JOIN
• RIGHT OUTER JOIN
• FULL OUTER JOIN
LEFT OUTER JOIN
• is an expression, which joins two tables with conditions.
• If conditions are matched, it returns values on both side of the tables
• If not, it returns values in the left side of the table with NULL on the right side
RIGHT OUTER JOIN
• is an expression, which joins two tables with conditions.
• If conditions are matched, it returns values on both side of the tables
• If not, it returns values in the right side of the table with NULL on the left side
FULL OUTER JOIN
• is an expression, which joins two tables with conditions.
• If conditions are matched, it returns values on both side of the tables
• If not, it returns values in the either side of the table with NULL on the other side
UNION (ALL)
• is a kind of operator, which combines result of
two or more SELECT statements.
Question 1
• Try to write SQL, which realises following Venn
diagram.
• Use setA and setB tables.
Question 2
• Try to write SQL, which realises following Venn
diagram.
• Use setA and setB tables.
Question 3
• Try to fetch students, who belong to as same course as
Mike.
• Make sure to exclude Mike from the result.
CASE
SELECT
product_name
, amount
, CASE
WHEN amount = 0
THEN 'Nothing. You should order ASAP!'
WHEN amount > 0 AND amount <= 10
THEN 'You have enough stock.'
WHEN amount > 10
THEN 'Too much. It’ll be dead stock.'
WHEN amount IS NULL
THEN 'Something went wrong on the system..'
ELSE 'Amount is minus. Check the stock.'
END AS suggestion
FROM stock;
COUNT
SELECT COUNT(name) FROM students;
Question 4
• Try to count number of male and number of
female respectively.
gender number
male 4
female 2
number_of_male number_of_female
4 2
1)
2)
Question 5
• Try to show ranking of the students by their
scores ordered by score descending.
name score rank
Beth 95 1
Mike 90 2
Jack 80 3
John 80 3
Tina 80 3
Nick 75 6
Question 6
• Try to show ranking of the students by their
scores ordered by score descending.
name score rank
Beth 95 1
Mike 90 2
Jack 80 3
John 80 3
Tina 80 3
Nick 75 4

Contenu connexe

Tendances

Unit 2 linear data structures
Unit 2   linear data structuresUnit 2   linear data structures
Unit 2 linear data structuresSenthil Murugan
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURERohit Rai
 
Introduction To Data Structures.
Introduction To Data Structures.Introduction To Data Structures.
Introduction To Data Structures.Education Front
 
Data structure power point presentation
Data structure power point presentation Data structure power point presentation
Data structure power point presentation Anil Kumar Prajapati
 
Lecture 01 Intro to DSA
Lecture 01 Intro to DSALecture 01 Intro to DSA
Lecture 01 Intro to DSANurjahan Nipa
 
A simple algorithm for page segmentation
A simple algorithm for page segmentationA simple algorithm for page segmentation
A simple algorithm for page segmentationAlexey Shigarov
 
Ch.8.5 Matrix Operations
Ch.8.5 Matrix OperationsCh.8.5 Matrix Operations
Ch.8.5 Matrix Operationsmdicken
 
data structure
data structuredata structure
data structurehashim102
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyMalikireddy Bramhananda Reddy
 
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Hassan Ahmed
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structureZaid Shabbir
 

Tendances (20)

Unit 2 linear data structures
Unit 2   linear data structuresUnit 2   linear data structures
Unit 2 linear data structures
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Data structures
Data structuresData structures
Data structures
 
Fem in matlab
Fem in matlabFem in matlab
Fem in matlab
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURE
 
Linked list
Linked listLinked list
Linked list
 
Introduction To Data Structures.
Introduction To Data Structures.Introduction To Data Structures.
Introduction To Data Structures.
 
Data structure power point presentation
Data structure power point presentation Data structure power point presentation
Data structure power point presentation
 
Lecture 01 Intro to DSA
Lecture 01 Intro to DSALecture 01 Intro to DSA
Lecture 01 Intro to DSA
 
A simple algorithm for page segmentation
A simple algorithm for page segmentationA simple algorithm for page segmentation
A simple algorithm for page segmentation
 
searching
searchingsearching
searching
 
Data structure
Data structureData structure
Data structure
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
Matlab pt1
Matlab pt1Matlab pt1
Matlab pt1
 
Ch.8.5 Matrix Operations
Ch.8.5 Matrix OperationsCh.8.5 Matrix Operations
Ch.8.5 Matrix Operations
 
data structure
data structuredata structure
data structure
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
 
Linkedlists
LinkedlistsLinkedlists
Linkedlists
 
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 

Similaire à Practical SQL and ORM fundamentals

Similaire à Practical SQL and ORM fundamentals (20)

OracleSQLraining.pptx
OracleSQLraining.pptxOracleSQLraining.pptx
OracleSQLraining.pptx
 
Tech Jam 01 - Database Querying
Tech Jam 01 - Database QueryingTech Jam 01 - Database Querying
Tech Jam 01 - Database Querying
 
ADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASADADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASAD
 
PPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structuresPPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structures
 
19IS305_U2_LP4_LM4-22-23.pdf
19IS305_U2_LP4_LM4-22-23.pdf19IS305_U2_LP4_LM4-22-23.pdf
19IS305_U2_LP4_LM4-22-23.pdf
 
Data Mining Lecture_8(a).pptx
Data Mining Lecture_8(a).pptxData Mining Lecture_8(a).pptx
Data Mining Lecture_8(a).pptx
 
Relational model
Relational modelRelational model
Relational model
 
Normalization.pdf
Normalization.pdfNormalization.pdf
Normalization.pdf
 
ADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database SystemsADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database Systems
 
Sql server
Sql serverSql server
Sql server
 
2..basic queries.pptx
2..basic queries.pptx2..basic queries.pptx
2..basic queries.pptx
 
SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
 
2. Array in Data Structure
2. Array in Data Structure2. Array in Data Structure
2. Array in Data Structure
 
Oracle sql tutorial
Oracle sql tutorialOracle sql tutorial
Oracle sql tutorial
 
SQL
SQLSQL
SQL
 
Access 03
Access 03Access 03
Access 03
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
 
Introduction to the Relational Model and SQL
Introduction to the Relational Model and SQLIntroduction to the Relational Model and SQL
Introduction to the Relational Model and SQL
 
Data Structures 5
Data Structures 5Data Structures 5
Data Structures 5
 
MYSQL join
MYSQL joinMYSQL join
MYSQL join
 

Plus de Hideshi Ogoshi

How to create test data
How to create test dataHow to create test data
How to create test dataHideshi Ogoshi
 
Functional programming
Functional programmingFunctional programming
Functional programmingHideshi Ogoshi
 
Learning CakePHP2 from source code vol2
Learning CakePHP2 from source code vol2Learning CakePHP2 from source code vol2
Learning CakePHP2 from source code vol2Hideshi Ogoshi
 
Learning CakePHP from Source Code
Learning CakePHP from Source CodeLearning CakePHP from Source Code
Learning CakePHP from Source CodeHideshi Ogoshi
 
Introduction of Monaca
Introduction of MonacaIntroduction of Monaca
Introduction of MonacaHideshi Ogoshi
 
Falcon Full Text Search Engine
Falcon Full Text Search EngineFalcon Full Text Search Engine
Falcon Full Text Search EngineHideshi Ogoshi
 
MySQL対応全文検索システムMroonga(むるんが)
MySQL対応全文検索システムMroonga(むるんが)MySQL対応全文検索システムMroonga(むるんが)
MySQL対応全文検索システムMroonga(むるんが)Hideshi Ogoshi
 

Plus de Hideshi Ogoshi (7)

How to create test data
How to create test dataHow to create test data
How to create test data
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Learning CakePHP2 from source code vol2
Learning CakePHP2 from source code vol2Learning CakePHP2 from source code vol2
Learning CakePHP2 from source code vol2
 
Learning CakePHP from Source Code
Learning CakePHP from Source CodeLearning CakePHP from Source Code
Learning CakePHP from Source Code
 
Introduction of Monaca
Introduction of MonacaIntroduction of Monaca
Introduction of Monaca
 
Falcon Full Text Search Engine
Falcon Full Text Search EngineFalcon Full Text Search Engine
Falcon Full Text Search Engine
 
MySQL対応全文検索システムMroonga(むるんが)
MySQL対応全文検索システムMroonga(むるんが)MySQL対応全文検索システムMroonga(むるんが)
MySQL対応全文検索システムMroonga(むるんが)
 

Dernier

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
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
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
 
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
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
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
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
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
 
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
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
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
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive 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
 
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.
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 

Dernier (20)

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...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
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
 
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
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
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
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
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
 
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
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
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
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive 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
 
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 ...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 

Practical SQL and ORM fundamentals

  • 1. Practice on Practical SQL Hideshi Ogoshi YNS Philippines Inc. SEP-22-2016
  • 2. Misunderstanding of Object-Relational Mapping • We use ORM. That does not mean we can totally rely on it, since it is not totally black boxed to the developers.
  • 3. ORM Pros & Cons • Pros • Transforms result set into a data structure, which can be easily handled in the programs • Handles many kinds of RDBMS transparently with same code • Cons • Hard to control generating SQL • Hard to use for the complicated requirements
  • 4. Relational Database • MySQL, PostgreSQL, Oracle Database, DB2, MSSQL, SQLite, etc. • Relational database is based on set theory.
  • 5. Set Theory • Set theory is the branch of mathematical logic that studies sets, which are collections of objects.
  • 6. Terms of Set Theory • Member • Subset • Union • Intersection • Difference • Tuple • Selection • Projection
  • 7. Member • A fundamental binary relation between an object o and a set A. • o is a member of A, denoted o ∈ A. • Example: 2 ∈ {1, 2, 3} 1 2 3
  • 8. Subset • If all the members of set A are also members of set B. • A is a subset of B, denoted A ⊆ B. • Example: {1, 2} ⊆ {1, 2, 3, 4} 1 2 3 4
  • 9. Union • Union creates a new set, which contains all the members of 2 sets. • Union of the sets A and B, denoted A ∪ B. • Example: {1, 2, 3} ∪ {2, 3, 4} = {1, 2, 3, 4} 2 31 4
  • 10. Intersection • Intersection creates a new set, which contains common members between 2 sets. • Intersection of the sets A and B, denoted A ∩ B. • Example: {1, 2, 3} ∩ {2, 3, 4} = {2, 3} 2 31 4
  • 11. Difference • Difference creates a new set, which contains remaining members in a set after subtracting the set from another set. • Difference of the sets A and B, denoted A ー B. • Example: {1, 2, 3} ー {2, 3, 4} = {1} 2 31 4
  • 12. Tuple • is a kind of data type, which represents finite ordered list of elements • Example: {(a, 1), (b,2), (c, 3)} (b,2) (c,3) (a,1)
  • 13. Selection • Selecting all tuples from set T1 if a tuple matches the conditions. Then creates T2 as new set. • σ Age >= 34 ^ Weight <= 50 (Person) (b,2) (c,3) (a,1) (c,3) (a,1) T1 T2
  • 14. Projection • Picking a sub-set of all available columns • Modifying an attribute’s value • Π Age,Weight (Person) (b,2) (c,3) (a,1) f(x) f(x) f(x) 4 6 2
  • 15. Correspondence between set theory and RDB • Table is a set of objects • Record is a tuple • SELECT is projection • WHERE is selection
  • 16. INNER JOIN • is an expression, which joins two tables with conditions. • returns records, which exactly match the conditions.
  • 17. OUTER JOIN • LEFT OUTER JOIN • RIGHT OUTER JOIN • FULL OUTER JOIN
  • 18. LEFT OUTER JOIN • is an expression, which joins two tables with conditions. • If conditions are matched, it returns values on both side of the tables • If not, it returns values in the left side of the table with NULL on the right side
  • 19. RIGHT OUTER JOIN • is an expression, which joins two tables with conditions. • If conditions are matched, it returns values on both side of the tables • If not, it returns values in the right side of the table with NULL on the left side
  • 20. FULL OUTER JOIN • is an expression, which joins two tables with conditions. • If conditions are matched, it returns values on both side of the tables • If not, it returns values in the either side of the table with NULL on the other side
  • 21. UNION (ALL) • is a kind of operator, which combines result of two or more SELECT statements.
  • 22. Question 1 • Try to write SQL, which realises following Venn diagram. • Use setA and setB tables.
  • 23. Question 2 • Try to write SQL, which realises following Venn diagram. • Use setA and setB tables.
  • 24. Question 3 • Try to fetch students, who belong to as same course as Mike. • Make sure to exclude Mike from the result.
  • 25. CASE SELECT product_name , amount , CASE WHEN amount = 0 THEN 'Nothing. You should order ASAP!' WHEN amount > 0 AND amount <= 10 THEN 'You have enough stock.' WHEN amount > 10 THEN 'Too much. It’ll be dead stock.' WHEN amount IS NULL THEN 'Something went wrong on the system..' ELSE 'Amount is minus. Check the stock.' END AS suggestion FROM stock;
  • 27. Question 4 • Try to count number of male and number of female respectively. gender number male 4 female 2 number_of_male number_of_female 4 2 1) 2)
  • 28. Question 5 • Try to show ranking of the students by their scores ordered by score descending. name score rank Beth 95 1 Mike 90 2 Jack 80 3 John 80 3 Tina 80 3 Nick 75 6
  • 29. Question 6 • Try to show ranking of the students by their scores ordered by score descending. name score rank Beth 95 1 Mike 90 2 Jack 80 3 John 80 3 Tina 80 3 Nick 75 4

Notes de l'éditeur

  1. Oracle database MSSQL server
  2. SELECT a.name, b.name FROM setA AS a LEFT OUTER JOIN setB AS b ON b.name = a.name UNION SELECT a.name, b.name FROM setA AS a RIGHT OUTER JOIN setB AS b ON b.name = a.name ;
  3. SELECT a.name, b.name FROM setA AS a LEFT OUTER JOIN setB AS b ON b.name = a.name WHERE b.name IS NULL ;
  4. exclusive disjunction / exclusive or SELECT a.name, b.name FROM setA AS a LEFT OUTER JOIN setB AS b ON b.name = a.name WHERE b.name IS NULL UNION SELECT a.name, b.name FROM setA AS a RIGHT OUTER JOIN setB AS b ON b.name = a.name WHERE a.name IS NULL ;
  5. SELECT b.name FROM students AS a INNER JOIN students AS b ON a.course = b.course WHERE a.name <> b.name AND a.name = 'Mike' ;
  6. SELECT product_name , amount , CASE WHEN amount = 0 THEN 'Nothing. You should order ASAP!' WHEN amount > 0 AND amount < 10 THEN 'You have enough stock.' WHEN amount > 10 THEN 'Too much. You should sell it or it will be dead stock.' WHEN amount IS NULL THEN 'Something went wrong on the system..' ELSE 'Amount is minus. Check the stock.' END AS suggestion FROM stock;
  7. SELECT CASE WHEN gender = 1 THEN ‘male’ WHEN gender = 2 THEN ‘female' END AS gender, COUNT(gender) AS number FROM students GROUP BY gender; SELECT SUM(CASE WHEN gender = 1 THEN 1 ELSE 0 END) AS number_of_male , SUM(CASE WHEN gender = 2 THEN 1 ELSE 0 END) AS number_of_female FROM students;
  8. SELECT name , score , (SELECT COUNT(score) FROM students AS s2 WHERE s2.score > s1.score) + 1 AS rank FROM students AS s1 ORDER BY rank SELECT s1.name , s1.score , COUNT(s2.name) + 1 AS rank FROM students AS s1 LEFT OUTER JOIN students AS s2 ON s1.score < s2.score GROUP BY s1.name ORDER BY s1.score DESC
  9. SELECT name , score , (SELECT COUNT(DISTINCT score) FROM students AS s2 WHERE s2.score > s1.score) + 1 AS rank FROM students AS s1 ORDER BY rank SELECT s1.name , s1.score , COUNT(s2.name) + 1 AS rank FROM students AS s1 LEFT OUTER JOIN ( SELECT name , score FROM students GROUP BY score ) AS s2 ON s1.score < s2.score GROUP BY s1.name ORDER BY s1.score DESC