SlideShare a Scribd company logo
DoItWithSQL
JourneytotheCenterof
DatabaseWorld
PHPID COMMUNITY ONLINE MEETUP #20 – 08/05/2020
BERSAMA: NUR HIDAYAT - DATABASE SPECIALIST
KebanyakanProgrammer,lebihsuka....
MENINGKATKAN SKILL
BAHASA PEMROGRAMAN
TERBARU,
MEMBUAT USER INTERFACE
YANG ATRAKTIF DAN USER-
FRIENDLY,
MEMBUAT APLIKASI YANG
BISA BERJALAN DI
DATABASE APAPUN
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
Akibatnya.....
o Kurang piawai meracik perintah SQL
o Tidak memanfaatkan fitur canggih yang ada di Database
o Membawa gaya pemrograman prosedural saat memproses data
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
JourneytotheCenterofDatabaseWorld
oDon’t treat databases as a black box
olearn what it can do for us
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
RuleofThumbs
Use single SQL
statement
whenever
possible
1
Use Stored
Procedure
(PL/SQL, T-SQL,
PL/pgSQL)
2
Use Java (or other
programming
language, such as
PHP, Go, etc.)
3
Rethink why you
want to do it
(refine your
approach)
4
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
SQLAnatomy
o Statement/Query
o Clause
o Predicate
o Expression
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
SELECTStatementBasics
SELECT b,d,e,h
FROM some_table ;
SELECT *
FROM some_table
WHERE x IN (3,5,6,8) ;
SELECT b,d,e,h
FROM some_table
WHERE x IN (3,5,6,8) ;
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
SQLJOINBasics
oSTANDARDJOIN
◦ INNER JOIN (JOIN)
◦ LEFT OUTER JOIN (LEFT JOIN)
◦ RIGHT OUTER JOIN (RIGHTJOIN)
◦ FULL OUTER JOIN (FULLJOIN)
oADVANCEDJOIN
◦ LEFT EXCLUDING JOIN
◦ LEFTJOINEXCLUDINGINNER JOIN
◦ RIGHT EXCLUDING JOIN
◦ RIGHTJOINEXCLUDINGINNER JOIN
◦ FULL EXCLUDING JOIN
◦ FULLJOIN EXCLUDING INNER JOIN
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
Representasi
VisualSQLJoin
o Diagram Venn
o Red Color is the result
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
JOINvsUNION
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
ChangeYour
Mindset!
o Tampilkan angka 1 sampai dengan 100,
dengan persyaratan sebagai berikut,
◦ setiap kelipatan3 ubah angkanya menjadi
kata ”PHP",
◦ setiap kelipatan 5 ubah angkanya menjadi
kata ”Indonesia", dan
◦ setiap kelipatan 15 ubah angkanya menjadi
kata ”PHP Indonesia".
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
Discussion D O I T W I T H S Q L
CaseStudies LET DATABASE SOLVE
OUR PROBLEMS
CaseStudies
oComputed column in query
oGenerated column in table
oJoin and Union
oAggregation
oSubqueries
oCommon Table Expression
oPivot/Crosstab Query
oCalculating Running Totals
oAnalytical Query
oHierarchical Query
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
ComputedColumn(Query)
o Most common problem
◦ I want field amount amount
automatically filled with value =
quantity * unit_price
o Solution
◦ Don’t create field amount
◦ Calculate value using query or view
o Sample data available here
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
ComputedColumn(Table)
o Use Generated Column
◦ Available in MySQL 5.7
◦ Built in since PostgreSQL 12
o Included in DDL
◦ In CREATE or ALTER TABLE
◦ Can be VIRTUAL or STORED
o Sample data available here
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
Join
o Display all students and their
courses for 1st semester
o Display all students who doesn’t
take any courses for 1st semester
o Display all courses which nobody
take for 1st semester
o Sample data available here
o Inner Join
o Left Outer Join
o Right Outer Join
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
Aggregation
o Display all students and total
course for each students
◦ If any students doesn’t take any
courses, display 0 (zero) instead
o Sample data available here
o Left Join
o Count()
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
Subqueries
o Nested query
◦ Query within query
o Derived Tables
o Do’s
◦ Subquery in FROM clause
◦ Subquery in WHERE clause
o Don’t’s
◦ Subquery in SELECT clause
o Sample data available here
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
Discussion D O I T W I T H S Q L
AdvancedQueries LET DATABASE SOLVE
OUR PROBLEMS
AdvanceQueries
oComputed column in query
oGenerated column in table
oJoin and Union
oAggregation
oSubqueries
oCommon Table Expression
oPivot/Crosstab Query
oCalculating Running Totals
oAnalytical Query
oHierarchical Query
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
CommonTableExpression
o Available in MySQL 8.0+ and PostgreSQL 8.4+
o Temporary result set that exists only within execution scope
o Advantages compared to derived tables
◦ Can be referenced multiple times
◦ Can be self-referencing/recursive
◦ Better readability and performance
o Basic syntax
◦ WITH cte_name (column_list) AS ( query ) SELECT * FROM cte_name;
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
Pivot/CrosstabQuery
o Convert rows into columns
◦ Simple crosstab, where columns count are known before hand
◦ Dynamic crosstab, where columns dynamically generated in query
o MySQL
◦ Use combination of min/max/sum and group by
◦ Dynamically generate coloumn using group_concat()
o PostgreSQL
◦ You’re lucky.... crosstab() function is already built-in
o Sample data available here.
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
CalculatingRunningTotals
o Running total
◦ Running balance
◦ Cumulative sum
o Introduce variable to
store total calculation
(MySQL 5.7 and earlier)
o More complex example
available here
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
AnalyticalQuery
o Revisit running total query
◦ Works on MySQL 8.0 and
PostgreSQL 8.4+
o Windowing function
◦ SUM() OVER()
◦ MIN() OVER()
◦ MAX OVER()
◦ COUNT() OVER()
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
HierarchicalQuery
o Using recursive (CTE) is a CTE that has a subquery which refers to the CTE
name itself.
o Basic syntax of a recursive CTE
◦ WITH RECURSIVE cte_name AS (
initial_query -- anchor member
UNION ALL recursive_query -- recursive member that references to the CTE name
)
SELECT * FROM cte_name;
08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
Discussion DO IT WITH SQL
References
o PHPID Online Meetup #01
◦ Slide di
https://www.slideshare.net/hidayat365/how-to-
design-a-good-database
◦ Sesi materi di https://youtu.be/pACuwalpQpk
◦ Sesi tanya jawab di https://youtu.be/_OMuPT0-Gv4
o Konsep Database Relasional dan Bahasa SQL
◦ https://pojokprogrammer.net/content/konsep-
database-relasional-dan-bahasa-sql
PHPIDONLINEMEETUP–CODEFACTORY 08/05/2020
ThankYou

More Related Content

PPTX
How to Design a Good Database
PDF
How to Design a Good Database for Your Application
PDF
Database basics for new-ish developers -- All Things Open October 18th 2021
PDF
Columnstore indexes in sql server 2014
PPT
Star schema my sql
PPTX
ADL/U-SQL Introduction (SQLBits 2016)
PPT
Making MySQL Great For Business Intelligence
PPTX
Build a modern data platform.pptx
How to Design a Good Database
How to Design a Good Database for Your Application
Database basics for new-ish developers -- All Things Open October 18th 2021
Columnstore indexes in sql server 2014
Star schema my sql
ADL/U-SQL Introduction (SQLBits 2016)
Making MySQL Great For Business Intelligence
Build a modern data platform.pptx

What's hot (20)

PPTX
Normalizing Data for Migrations
PDF
Oslo baksia2014
PPTX
PPTX
SQL Server Index and Partition Strategy
PDF
Native JSON Support in SQL2016
PPT
No sql or Not only SQL
PPTX
U-SQL Intro (SQLBits 2016)
PPTX
U-SQL Learning Resources (SQLBits 2016)
PPTX
Data Warehouse Best Practices
PPTX
U-SQL Federated Distributed Queries (SQLBits 2016)
PPTX
U-SQL Meta Data Catalog (SQLBits 2016)
PDF
Harnessing The Semantic Web
PDF
Grails And The Semantic Web
PPT
Sql Server Basics
PPTX
Taming the Data Science Monster with A New ‘Sword’ – U-SQL
PDF
Multi-Model Data Query Languages and Processing Paradigms
PPTX
A Step by Step Introduction to the MySQL Document Store
PPTX
Introducing U-SQL (SQLPASS 2016)
PPTX
Columnstore Customer Stories 2016 by Sunil Agarwal
PPTX
Do IT with SQL
Normalizing Data for Migrations
Oslo baksia2014
SQL Server Index and Partition Strategy
Native JSON Support in SQL2016
No sql or Not only SQL
U-SQL Intro (SQLBits 2016)
U-SQL Learning Resources (SQLBits 2016)
Data Warehouse Best Practices
U-SQL Federated Distributed Queries (SQLBits 2016)
U-SQL Meta Data Catalog (SQLBits 2016)
Harnessing The Semantic Web
Grails And The Semantic Web
Sql Server Basics
Taming the Data Science Monster with A New ‘Sword’ – U-SQL
Multi-Model Data Query Languages and Processing Paradigms
A Step by Step Introduction to the MySQL Document Store
Introducing U-SQL (SQLPASS 2016)
Columnstore Customer Stories 2016 by Sunil Agarwal
Do IT with SQL
Ad

Similar to Do It With SQL - Journey to the Center of Database Worlds (20)

PPTX
Server Query Language – Getting Started.pptx
PDF
Practical Sql A Beginners Guide To Storytelling With Data 2nd Edition 2 Conve...
PPTX
unit01-Activity-SQL-Query-Review-1.pptx
PDF
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
PDF
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
PDF
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
PPTX
Modern sql
PDF
Assignment#05
PDF
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
PDF
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
PDF
CS121Lec05.pdf
PDF
SQL Queries .pdf
PPT
mysql.ppt
PDF
Learning SQL
PDF
Learning SQL
PDF
DBMS Notes selection projection aggregate
PDF
Tech Jam 01 - Database Querying
PDF
Practical SQL: A Beginner's Guide to Storytelling with Data, 2nd Edition Anth...
PDF
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
Server Query Language – Getting Started.pptx
Practical Sql A Beginners Guide To Storytelling With Data 2nd Edition 2 Conve...
unit01-Activity-SQL-Query-Review-1.pptx
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
Modern sql
Assignment#05
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
CS121Lec05.pdf
SQL Queries .pdf
mysql.ppt
Learning SQL
Learning SQL
DBMS Notes selection projection aggregate
Tech Jam 01 - Database Querying
Practical SQL: A Beginner's Guide to Storytelling with Data, 2nd Edition Anth...
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthon...
Ad

More from Nur Hidayat (6)

PDF
Develop a Software, Where to Start?
PDF
PostgreSQL Advanced Queries
PPTX
Seminar Android - Pengenalan PhoneGap
PPTX
How to Become Great Programmer
PPTX
PHP Oracle
PPTX
MRI Presentation
Develop a Software, Where to Start?
PostgreSQL Advanced Queries
Seminar Android - Pengenalan PhoneGap
How to Become Great Programmer
PHP Oracle
MRI Presentation

Recently uploaded (20)

PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
L1 - Introduction to python Backend.pptx
PDF
System and Network Administraation Chapter 3
PPT
Introduction Database Management System for Course Database
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Digital Strategies for Manufacturing Companies
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Digital Systems & Binary Numbers (comprehensive )
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Computer Software and OS of computer science of grade 11.pptx
Design an Analysis of Algorithms I-SECS-1021-03
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
L1 - Introduction to python Backend.pptx
System and Network Administraation Chapter 3
Introduction Database Management System for Course Database
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Digital Strategies for Manufacturing Companies
Odoo Companies in India – Driving Business Transformation.pdf
ai tools demonstartion for schools and inter college
How to Migrate SBCGlobal Email to Yahoo Easily
Adobe Illustrator 28.6 Crack My Vision of Vector Design
How to Choose the Right IT Partner for Your Business in Malaysia
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Digital Systems & Binary Numbers (comprehensive )
Operating system designcfffgfgggggggvggggggggg
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool

Do It With SQL - Journey to the Center of Database Worlds

  • 1. DoItWithSQL JourneytotheCenterof DatabaseWorld PHPID COMMUNITY ONLINE MEETUP #20 – 08/05/2020 BERSAMA: NUR HIDAYAT - DATABASE SPECIALIST
  • 2. KebanyakanProgrammer,lebihsuka.... MENINGKATKAN SKILL BAHASA PEMROGRAMAN TERBARU, MEMBUAT USER INTERFACE YANG ATRAKTIF DAN USER- FRIENDLY, MEMBUAT APLIKASI YANG BISA BERJALAN DI DATABASE APAPUN 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 3. Akibatnya..... o Kurang piawai meracik perintah SQL o Tidak memanfaatkan fitur canggih yang ada di Database o Membawa gaya pemrograman prosedural saat memproses data 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 4. JourneytotheCenterofDatabaseWorld oDon’t treat databases as a black box olearn what it can do for us 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 5. RuleofThumbs Use single SQL statement whenever possible 1 Use Stored Procedure (PL/SQL, T-SQL, PL/pgSQL) 2 Use Java (or other programming language, such as PHP, Go, etc.) 3 Rethink why you want to do it (refine your approach) 4 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 6. SQLAnatomy o Statement/Query o Clause o Predicate o Expression 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 7. SELECTStatementBasics SELECT b,d,e,h FROM some_table ; SELECT * FROM some_table WHERE x IN (3,5,6,8) ; SELECT b,d,e,h FROM some_table WHERE x IN (3,5,6,8) ; 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 8. SQLJOINBasics oSTANDARDJOIN ◦ INNER JOIN (JOIN) ◦ LEFT OUTER JOIN (LEFT JOIN) ◦ RIGHT OUTER JOIN (RIGHTJOIN) ◦ FULL OUTER JOIN (FULLJOIN) oADVANCEDJOIN ◦ LEFT EXCLUDING JOIN ◦ LEFTJOINEXCLUDINGINNER JOIN ◦ RIGHT EXCLUDING JOIN ◦ RIGHTJOINEXCLUDINGINNER JOIN ◦ FULL EXCLUDING JOIN ◦ FULLJOIN EXCLUDING INNER JOIN 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 9. Representasi VisualSQLJoin o Diagram Venn o Red Color is the result 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 11. ChangeYour Mindset! o Tampilkan angka 1 sampai dengan 100, dengan persyaratan sebagai berikut, ◦ setiap kelipatan3 ubah angkanya menjadi kata ”PHP", ◦ setiap kelipatan 5 ubah angkanya menjadi kata ”Indonesia", dan ◦ setiap kelipatan 15 ubah angkanya menjadi kata ”PHP Indonesia". 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 12. Discussion D O I T W I T H S Q L
  • 13. CaseStudies LET DATABASE SOLVE OUR PROBLEMS
  • 14. CaseStudies oComputed column in query oGenerated column in table oJoin and Union oAggregation oSubqueries oCommon Table Expression oPivot/Crosstab Query oCalculating Running Totals oAnalytical Query oHierarchical Query 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 15. ComputedColumn(Query) o Most common problem ◦ I want field amount amount automatically filled with value = quantity * unit_price o Solution ◦ Don’t create field amount ◦ Calculate value using query or view o Sample data available here 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 16. ComputedColumn(Table) o Use Generated Column ◦ Available in MySQL 5.7 ◦ Built in since PostgreSQL 12 o Included in DDL ◦ In CREATE or ALTER TABLE ◦ Can be VIRTUAL or STORED o Sample data available here 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 17. Join o Display all students and their courses for 1st semester o Display all students who doesn’t take any courses for 1st semester o Display all courses which nobody take for 1st semester o Sample data available here o Inner Join o Left Outer Join o Right Outer Join 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 18. Aggregation o Display all students and total course for each students ◦ If any students doesn’t take any courses, display 0 (zero) instead o Sample data available here o Left Join o Count() 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 19. Subqueries o Nested query ◦ Query within query o Derived Tables o Do’s ◦ Subquery in FROM clause ◦ Subquery in WHERE clause o Don’t’s ◦ Subquery in SELECT clause o Sample data available here 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 20. Discussion D O I T W I T H S Q L
  • 21. AdvancedQueries LET DATABASE SOLVE OUR PROBLEMS
  • 22. AdvanceQueries oComputed column in query oGenerated column in table oJoin and Union oAggregation oSubqueries oCommon Table Expression oPivot/Crosstab Query oCalculating Running Totals oAnalytical Query oHierarchical Query 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 23. CommonTableExpression o Available in MySQL 8.0+ and PostgreSQL 8.4+ o Temporary result set that exists only within execution scope o Advantages compared to derived tables ◦ Can be referenced multiple times ◦ Can be self-referencing/recursive ◦ Better readability and performance o Basic syntax ◦ WITH cte_name (column_list) AS ( query ) SELECT * FROM cte_name; 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 24. Pivot/CrosstabQuery o Convert rows into columns ◦ Simple crosstab, where columns count are known before hand ◦ Dynamic crosstab, where columns dynamically generated in query o MySQL ◦ Use combination of min/max/sum and group by ◦ Dynamically generate coloumn using group_concat() o PostgreSQL ◦ You’re lucky.... crosstab() function is already built-in o Sample data available here. 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 25. CalculatingRunningTotals o Running total ◦ Running balance ◦ Cumulative sum o Introduce variable to store total calculation (MySQL 5.7 and earlier) o More complex example available here 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 26. AnalyticalQuery o Revisit running total query ◦ Works on MySQL 8.0 and PostgreSQL 8.4+ o Windowing function ◦ SUM() OVER() ◦ MIN() OVER() ◦ MAX OVER() ◦ COUNT() OVER() 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 27. HierarchicalQuery o Using recursive (CTE) is a CTE that has a subquery which refers to the CTE name itself. o Basic syntax of a recursive CTE ◦ WITH RECURSIVE cte_name AS ( initial_query -- anchor member UNION ALL recursive_query -- recursive member that references to the CTE name ) SELECT * FROM cte_name; 08/05/2020PHPIDONLINEMEETUP–CODEFACTORY
  • 28. Discussion DO IT WITH SQL
  • 29. References o PHPID Online Meetup #01 ◦ Slide di https://www.slideshare.net/hidayat365/how-to- design-a-good-database ◦ Sesi materi di https://youtu.be/pACuwalpQpk ◦ Sesi tanya jawab di https://youtu.be/_OMuPT0-Gv4 o Konsep Database Relasional dan Bahasa SQL ◦ https://pojokprogrammer.net/content/konsep- database-relasional-dan-bahasa-sql PHPIDONLINEMEETUP–CODEFACTORY 08/05/2020