SlideShare una empresa de Scribd logo
1 de 91
Advanced SQL Queries
Stef CTO & Futurist
Disclaimer
DB Structure
batches batch_executions
id
name
id
batch_id
start_date
end_date
duration
Simple stuff
NVL
-- Execution time is
-- (end_date – start_date) if the batch is executed
-- (current time - start_date) if the batch is still
running
-- Execution time is
-- (end_date – start_date) if the batch is executed
-- (current time - start_date) if the batch is still
running
SELECT
(NVL(end_date, sysdate) – start_date) as duration
FROM batch_executions
DECODE
-- Fetch batch status
-- If end_date is not set, the batch is in progress
-- If end_date is set, the batch has finished
-- Fetch batch status
-- If end_date is not set, the batch is in progress
-- If end_date is set, the batch has finished
SELECT
DECODE(end_date, NULL, ‘IN PROGRESS’, ‘DONE’)
FROM batch_executions
Aggregation function
over
Aggregation function
-- Find the batch with longest average execution time
-- Find the batch with longest average execution time
SELECT MAX(avg_duration)
FROM (SELECT AVG(duration) as avg_duration
FROM batch_executions
GROUP BY batch_id)
-- Find the batch with longest average execution time
SELECT MAX(avg_duration)
FROM (SELECT AVG(duration) as avg_duration
FROM batch_executions
GROUP BY batch_id)
-- Find the batch with longest average execution time
SELECT MAX(avg_duration)
FROM (SELECT AVG(duration) as avg_duration
FROM batch_executions
GROUP BY batch_id)
SELECT MAX(AVG(duration))
FROM batch_executions
GROUP BY batch_id
WHERE’s my stuff
Handle missing parameters
WHERE (:name IS NULL
OR name LIKE :name )
IN
ANY, ALL
X > ANY (SELECT y FROM … )
X > ALL (SELECT y FROM … )
-- List batches with duration longer than the longest
average duration
-- List batches with duration longer than the longest
average duration
SELECT * FROM batch_executions
WHERE duration > ALL(SELECT AVG(duration)
FROM batch_executions
GROUP BY batch_id)
-- List batches with duration longer than the longest
average duration
SELECT * FROM batch_executions
WHERE duration > ALL(SELECT AVG(duration)
FROM batch_executions
GROUP BY batch_id)
SELECT * FROM batch_executions
WHERE duration > (SELECT MAX(AVG(duration))
FROM batch_executions
GROUP BY batch_id)
FROM stuff
UNION [ALL]
INTERSECT
-- Batches executed both today and yesterday
-- Batches executed both today and yesterday
SELECT batch_id FROM batch_executions
WHERE trunc(start_date) = trunc(sysdate - 1)
INTERSECT
SELECT batch_id FROM batch_executions
WHERE trunc(start_date) = trunc(sysdate)
MINUS
-- Batches which are never executed
-- Batches which are never executed
SELECT id FROM batches
MINUS
SELECT batch_id FROM batch_executions
GROUP BY stuff
ROLLUP
-- count of executions per day, month and year
-- count of executions per day, month and year
SELECT
to_char(start_date, 'YYYY') year,
to_char(start_date, 'mm') month,
COUNT(*)
FROM batch_executions
GROUP BY
to_char(start_date, 'YYYY'),
to_char(start_date, 'mm’)
UNION ALL
SELECT
to_char(start_date, 'YYYY') year,
NULL as month,
COUNT(*)
FROM batch_executions
GROUP BY
to_char(start_date, 'YYYY’)
-- count of executions per day, month and year
SELECT
to_char(start_date, 'YYYY') year,
to_char(start_date, 'mm') month,
to_char(start_date, 'dd') day,
COUNT(*)
FROM batch_executions
GROUP BY ROLLUP (
to_char(start_date, 'YYYY'),
to_char(start_date, 'mm'),
to_char(start_date, 'dd')
)
-- count of executions per day, month and year
SELECT
to_char(start_date, 'YYYY') year,
to_char(start_date, 'mm') month,
to_char(start_date, 'dd') day,
COUNT(*)
FROM batch_executions
GROUP BY ROLLUP (
to_char(start_date, 'YYYY'),
to_char(start_date, 'mm'),
to_char(start_date, 'dd')
)
GROUP BY
(year, month, day)
(year, month)
(year)
CUBE
-- count of executions per day, month and year
SELECT
to_char(start_date, 'YYYY') year,
to_char(start_date, 'mm') month
COUNT(*)
FROM batch_executions
GROUP BY CUBE (
to_char(start_date, 'YYYY'),
to_char(start_date, 'mm’)
)
-- count of executions per day, month and year
SELECT
to_char(start_date, 'YYYY') year,
to_char(start_date, 'mm') month
COUNT(*)
FROM batch_executions
GROUP BY CUBE (
to_char(start_date, 'YYYY'),
to_char(start_date, 'mm’)
)
GROUP BY
(year, month)
(year)
(month)
Analytic stuff
(Analytic Functions)
-- List batches and assigned them number based on
their start date
BATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30 1
1 21-MAR-15 07:09:17 2
1 22-MAR-15 07:09:50 3
1 22-MAR-15 07:10:10 4
2 22-MAR-15 07:46:51 5
Expected
-- List batches and assigned them number based on
their start date
SELECT rownum, batch_id
FROM batch_executions
ORDER BY start_date
BATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30 1
1 21-MAR-15 07:09:17 2
1 22-MAR-15 07:09:50 3
1 22-MAR-15 07:10:10 4
2 22-MAR-15 07:46:51 5
Expected
ActualBATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30 2
1 21-MAR-15 07:09:17 1
1 22-MAR-15 07:09:50 3
1 22-MAR-15 07:10:10 4
2 22-MAR-15 07:46:51 5
-- List batches and assigned them number based on
their start date
SELECT rownum, batch_id
FROM batch_executions
ORDER BY start_date
SELECT rownum, start_date, batch_id
FROM (SELECT start_date, batch_id
FROM batch_executions
ORDER BY start_date)
WRONG
CORRECT
ROW_NUMBER
-- List batches and assigned them number based on
their start date
SELECT rownum, start_date, batch_id
FROM (SELECT start_date, batch_id
FROM batch_executions
ORDER BY start_date)
-- List batches and assigned them number based on
their start date
SELECT rownum, start_date, batch_id
FROM (SELECT start_date, batch_id
FROM batch_executions
ORDER BY start_date)
SELECT
row_number OVER (ORDER BY start_date),
start_date,
batch_id
FROM batch_executions
Function(arg1,..., argn) OVER ( [PARTITION BY <...>]
[ORDER BY <....>] [<window_clause>] )
Function(arg1,..., argn) OVER ( [PARTITION BY <...>]
[ORDER BY <....>] [<window_clause>] )
Function(arg1,..., argn) OVER ( [PARTITION BY <...>]
[ORDER BY <....>] [<window_clause>] )
-- List batches and assigned them number based on
their start date but only for the batch group
BATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30 1
1 21-MAR-15 07:09:17 2
1 22-MAR-15 07:09:50 3
1 22-MAR-15 07:10:10 4
2 22-MAR-15 07:46:51 1
Expected
-- List batches and assigned them number based on
their start date but only for the batch group
SELECT rownum, start_date, batch_id
FROM (SELECT start_date, batch_id
FROM batch_executions
ORDER BY start_date)
-- List batches and assigned them number based on
their start date but only for the batch group
SELECT rownum, start_date, batch_id
FROM (SELECT start_date, batch_id
FROM batch_executions
ORDER BY start_date)
WRONG
-- List batches and assigned them number based on
their start date but only for the batch group
SELECT rownum, start_date, batch_id
FROM (SELECT start_date, batch_id
FROM batch_executions
ORDER BY start_date)
SELECT
row_number() OVER
(PARTITION BY batch_id ORDER BY
start_date),
start_date,
batch_id
FROM batch_executions
WRONG
BATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30
1 21-MAR-15 07:09:17
1 22-MAR-15 07:09:50
1 22-MAR-15 07:10:10
2 22-MAR-15 07:46:51
BATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30
1 21-MAR-15 07:09:17
1 22-MAR-15 07:09:50
1 22-MAR-15 07:10:10
2 22-MAR-15 07:46:51
BATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30
1 21-MAR-15 07:09:17
1 22-MAR-15 07:09:50
1 22-MAR-15 07:10:10
2 22-MAR-15 07:46:51
BATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30
1 21-MAR-15 07:09:17
1 22-MAR-15 07:09:50
1 22-MAR-15 07:10:10
2 22-MAR-15 07:46:51
BATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30 1
1 21-MAR-15 07:09:17 2
1 22-MAR-15 07:09:50 3
1 22-MAR-15 07:10:10 4
2 22-MAR-15 07:46:51 1
BATCH_ID START_DATE NUM
1 12-DEC-14 07:09:30
1 21-MAR-15 07:09:17
1 22-MAR-15 07:09:50
1 22-MAR-15 07:10:10
2 22-MAR-15 07:46:51
-- List batches and assigned them number based on
their start date but only for the batch group
SELECT
row_number() OVER
(PARTITION BY batch_id ORDER BY
start_date),
start_date,
batch_id
FROM batch_executions
ROW_NUMBER | RANK | DENSE_RANK
SELECT
ROW_NUMBER() OVER (ORDER BY duration),
RANK() OVER (ORDER BY duration),
DENSE_RANK() OVER (ORDER BY duration),
DURATION
FROM batch_executions
SELECT
ROW_NUMBER() OVER (ORDER BY duration),
RANK() OVER (ORDER BY duration),
DENSE_RANK() OVER (ORDER BY duration),
DURATION
FROM batch_executions
RN RANK D_RANK DURATION
1 1 1 5
2 1 1 5
3 1 1 5
4 4 2 873
LEAD | LAG
-- List:
-- average duration and last run date for each batch
-- first previous and first following batch run dates
-- first previous and first following batch by average duration
SELECT
batch_id,
AVG(duration),
MAX(start_date),
LAG(batch_id) OVER (ORDER BY MAX(start_date)) prev_by_date,
LEAD(batch_id) OVER (ORDER BY MAX(start_date)) next_by_date,
LAG(batch_id) OVER (ORDER BY AVG(duration)) prev_by_duration,
LEAD(batch_id) OVER (ORDER BY AVG(duration)) next_by_duration
FROM batch_executions
GROUP BY batch_id
FIRST_VALUE | LAST_VALUE
MIN | MAX | COUNT | SUM | AVG
Window Clause
Function(arg1,..., argn) OVER ( [PARTITION BY <...>]
[ORDER BY <....>] [<window_clause>] )
ROW | RANGE
[ROW or RANGE] BETWEEN <start_expr> AND <end_expr>
<start_expr>
UNBOUNDED PRECEDING
CURRENT ROW
<sql_expr> PRECEDING or FOLLOWING.
<end_expr>
UNBOUNDED FOLLOWING or
CURRENT ROW or
<sql_expr> PRECEDING or FOLLOWING.
ROW vs RANGE
[ROW or RANGE] BETWEEN <start_expr> AND <end_expr>
<start_expr>
UNBOUNDED PECEDING
CURRENT ROW
<sql_expr> PRECEDING or FOLLOWING.
<end_expr>
UNBOUNDED FOLLOWING or
CURRENT ROW or
<sql_expr> PRECEDING or FOLLOWING.
Case Study
I2C Statistics
The Problem
The Problem
system status today
The Problem
system status today
system status by day
The Problem
system status today
system status by day
system status by month
Introducing
INV_TRANSITIONS
(inv, transition_date, old_status, new_status)
Data Aggregation
We define:
Initial State =
(available amount, financed amount, potential amount)
Transition change vector for each transition
e.g. Not Eligible -> Eligible (+500, 0, +500)
We define:
Initial State =
(available amount, financed amount, potential amount)
Transition change vector for each transition
e.g. Not Eligible -> Eligible (+500, 0, +500)
Note: We need only first and last day transitions
Example
The query
Thanks for watching
Questions
Resources
Analytic functions by Example:
http://www.orafaq.com/node/55
Oracle Base:
http://www.oracle-base.com/articles/misc/analytic-functions.php
http://www.oracle-base.com/articles/misc/lag-lead-analytic-
functions.php
http://www.oracle-base.com/articles/misc/first-value-and-last-value-
analytic-functions.php

Más contenido relacionado

Destacado

Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testerstlvd
 
15 questions sql advance
15 questions sql   advance15 questions sql   advance
15 questions sql advanceNaviSoft
 
Sql queries questions and answers
Sql queries questions and answersSql queries questions and answers
Sql queries questions and answersMichael Belete
 
CSC 433 Sample normalization SQL Question
CSC 433 Sample normalization SQL QuestionCSC 433 Sample normalization SQL Question
CSC 433 Sample normalization SQL QuestionShakila Mahjabin
 
Entity Relationship Diagram presentation
Entity Relationship Diagram presentationEntity Relationship Diagram presentation
Entity Relationship Diagram presentationSopov Chan
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship DiagramShakila Mahjabin
 

Destacado (7)

Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testers
 
Sql Queries
Sql QueriesSql Queries
Sql Queries
 
15 questions sql advance
15 questions sql   advance15 questions sql   advance
15 questions sql advance
 
Sql queries questions and answers
Sql queries questions and answersSql queries questions and answers
Sql queries questions and answers
 
CSC 433 Sample normalization SQL Question
CSC 433 Sample normalization SQL QuestionCSC 433 Sample normalization SQL Question
CSC 433 Sample normalization SQL Question
 
Entity Relationship Diagram presentation
Entity Relationship Diagram presentationEntity Relationship Diagram presentation
Entity Relationship Diagram presentation
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship Diagram
 

Similar a Advanced SQL Queries

T sql denali code Day of .Net
T sql denali code Day of .NetT sql denali code Day of .Net
T sql denali code Day of .NetKathiK58
 
Basic Query Tuning Primer - Pg West 2009
Basic Query Tuning Primer - Pg West 2009Basic Query Tuning Primer - Pg West 2009
Basic Query Tuning Primer - Pg West 2009mattsmiley
 
John Melesky - Federating Queries Using Postgres FDW @ Postgres Open
John Melesky - Federating Queries Using Postgres FDW @ Postgres OpenJohn Melesky - Federating Queries Using Postgres FDW @ Postgres Open
John Melesky - Federating Queries Using Postgres FDW @ Postgres OpenPostgresOpen
 
Tests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTapTests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTapRodolphe Quiédeville
 
Extreme querying with_analytics
Extreme querying with_analyticsExtreme querying with_analytics
Extreme querying with_analyticsGary Myers
 
Simplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsSimplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsClayton Groom
 
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxgilpinleeanna
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricksYanli Liu
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLCommand Prompt., Inc
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLMark Wong
 
A few things about the Oracle optimizer - 2013
A few things about the Oracle optimizer - 2013A few things about the Oracle optimizer - 2013
A few things about the Oracle optimizer - 2013Connor McDonald
 
Dok Talks #115 - What More Can I Learn From My OpenTelemetry Traces?
Dok Talks #115 - What More Can I Learn From My OpenTelemetry Traces?Dok Talks #115 - What More Can I Learn From My OpenTelemetry Traces?
Dok Talks #115 - What More Can I Learn From My OpenTelemetry Traces?DoKC
 
Common Performance Pitfalls in Odoo apps
Common Performance Pitfalls in Odoo appsCommon Performance Pitfalls in Odoo apps
Common Performance Pitfalls in Odoo appsOdoo
 
zen and the art of SQL optimization
zen and the art of SQL optimizationzen and the art of SQL optimization
zen and the art of SQL optimizationKaren Morton
 
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxcarliotwaycave
 
How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012Connor McDonald
 
JKJ_T SQL project code samples
JKJ_T SQL project code samplesJKJ_T SQL project code samples
JKJ_T SQL project code samplesJeff Jacob
 
ClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei MilovidovClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei MilovidovAltinity Ltd
 

Similar a Advanced SQL Queries (20)

T sql denali code Day of .Net
T sql denali code Day of .NetT sql denali code Day of .Net
T sql denali code Day of .Net
 
Basic Query Tuning Primer - Pg West 2009
Basic Query Tuning Primer - Pg West 2009Basic Query Tuning Primer - Pg West 2009
Basic Query Tuning Primer - Pg West 2009
 
Basic Query Tuning Primer
Basic Query Tuning PrimerBasic Query Tuning Primer
Basic Query Tuning Primer
 
John Melesky - Federating Queries Using Postgres FDW @ Postgres Open
John Melesky - Federating Queries Using Postgres FDW @ Postgres OpenJohn Melesky - Federating Queries Using Postgres FDW @ Postgres Open
John Melesky - Federating Queries Using Postgres FDW @ Postgres Open
 
Tests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTapTests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTap
 
Extreme querying with_analytics
Extreme querying with_analyticsExtreme querying with_analytics
Extreme querying with_analytics
 
Simplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsSimplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functions
 
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
New tsql features
New tsql featuresNew tsql features
New tsql features
 
A few things about the Oracle optimizer - 2013
A few things about the Oracle optimizer - 2013A few things about the Oracle optimizer - 2013
A few things about the Oracle optimizer - 2013
 
Dok Talks #115 - What More Can I Learn From My OpenTelemetry Traces?
Dok Talks #115 - What More Can I Learn From My OpenTelemetry Traces?Dok Talks #115 - What More Can I Learn From My OpenTelemetry Traces?
Dok Talks #115 - What More Can I Learn From My OpenTelemetry Traces?
 
Common Performance Pitfalls in Odoo apps
Common Performance Pitfalls in Odoo appsCommon Performance Pitfalls in Odoo apps
Common Performance Pitfalls in Odoo apps
 
zen and the art of SQL optimization
zen and the art of SQL optimizationzen and the art of SQL optimization
zen and the art of SQL optimization
 
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
 
How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012
 
JKJ_T SQL project code samples
JKJ_T SQL project code samplesJKJ_T SQL project code samples
JKJ_T SQL project code samples
 
ClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei MilovidovClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei Milovidov
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 

Advanced SQL Queries

  • 1.
  • 2. Advanced SQL Queries Stef CTO & Futurist
  • 4.
  • 8. NVL
  • 9. -- Execution time is -- (end_date – start_date) if the batch is executed -- (current time - start_date) if the batch is still running
  • 10. -- Execution time is -- (end_date – start_date) if the batch is executed -- (current time - start_date) if the batch is still running SELECT (NVL(end_date, sysdate) – start_date) as duration FROM batch_executions
  • 12. -- Fetch batch status -- If end_date is not set, the batch is in progress -- If end_date is set, the batch has finished
  • 13. -- Fetch batch status -- If end_date is not set, the batch is in progress -- If end_date is set, the batch has finished SELECT DECODE(end_date, NULL, ‘IN PROGRESS’, ‘DONE’) FROM batch_executions
  • 15. -- Find the batch with longest average execution time
  • 16. -- Find the batch with longest average execution time SELECT MAX(avg_duration) FROM (SELECT AVG(duration) as avg_duration FROM batch_executions GROUP BY batch_id)
  • 17. -- Find the batch with longest average execution time SELECT MAX(avg_duration) FROM (SELECT AVG(duration) as avg_duration FROM batch_executions GROUP BY batch_id)
  • 18. -- Find the batch with longest average execution time SELECT MAX(avg_duration) FROM (SELECT AVG(duration) as avg_duration FROM batch_executions GROUP BY batch_id) SELECT MAX(AVG(duration)) FROM batch_executions GROUP BY batch_id
  • 21. WHERE (:name IS NULL OR name LIKE :name )
  • 22. IN
  • 24. X > ANY (SELECT y FROM … ) X > ALL (SELECT y FROM … )
  • 25. -- List batches with duration longer than the longest average duration
  • 26. -- List batches with duration longer than the longest average duration SELECT * FROM batch_executions WHERE duration > ALL(SELECT AVG(duration) FROM batch_executions GROUP BY batch_id)
  • 27. -- List batches with duration longer than the longest average duration SELECT * FROM batch_executions WHERE duration > ALL(SELECT AVG(duration) FROM batch_executions GROUP BY batch_id) SELECT * FROM batch_executions WHERE duration > (SELECT MAX(AVG(duration)) FROM batch_executions GROUP BY batch_id)
  • 31. -- Batches executed both today and yesterday
  • 32. -- Batches executed both today and yesterday SELECT batch_id FROM batch_executions WHERE trunc(start_date) = trunc(sysdate - 1) INTERSECT SELECT batch_id FROM batch_executions WHERE trunc(start_date) = trunc(sysdate)
  • 33. MINUS
  • 34. -- Batches which are never executed
  • 35. -- Batches which are never executed SELECT id FROM batches MINUS SELECT batch_id FROM batch_executions
  • 38. -- count of executions per day, month and year
  • 39. -- count of executions per day, month and year SELECT to_char(start_date, 'YYYY') year, to_char(start_date, 'mm') month, COUNT(*) FROM batch_executions GROUP BY to_char(start_date, 'YYYY'), to_char(start_date, 'mm’) UNION ALL SELECT to_char(start_date, 'YYYY') year, NULL as month, COUNT(*) FROM batch_executions GROUP BY to_char(start_date, 'YYYY’)
  • 40. -- count of executions per day, month and year SELECT to_char(start_date, 'YYYY') year, to_char(start_date, 'mm') month, to_char(start_date, 'dd') day, COUNT(*) FROM batch_executions GROUP BY ROLLUP ( to_char(start_date, 'YYYY'), to_char(start_date, 'mm'), to_char(start_date, 'dd') )
  • 41. -- count of executions per day, month and year SELECT to_char(start_date, 'YYYY') year, to_char(start_date, 'mm') month, to_char(start_date, 'dd') day, COUNT(*) FROM batch_executions GROUP BY ROLLUP ( to_char(start_date, 'YYYY'), to_char(start_date, 'mm'), to_char(start_date, 'dd') ) GROUP BY (year, month, day) (year, month) (year)
  • 42. CUBE
  • 43. -- count of executions per day, month and year SELECT to_char(start_date, 'YYYY') year, to_char(start_date, 'mm') month COUNT(*) FROM batch_executions GROUP BY CUBE ( to_char(start_date, 'YYYY'), to_char(start_date, 'mm’) )
  • 44. -- count of executions per day, month and year SELECT to_char(start_date, 'YYYY') year, to_char(start_date, 'mm') month COUNT(*) FROM batch_executions GROUP BY CUBE ( to_char(start_date, 'YYYY'), to_char(start_date, 'mm’) ) GROUP BY (year, month) (year) (month)
  • 46. -- List batches and assigned them number based on their start date BATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 1 1 21-MAR-15 07:09:17 2 1 22-MAR-15 07:09:50 3 1 22-MAR-15 07:10:10 4 2 22-MAR-15 07:46:51 5 Expected
  • 47. -- List batches and assigned them number based on their start date SELECT rownum, batch_id FROM batch_executions ORDER BY start_date
  • 48. BATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 1 1 21-MAR-15 07:09:17 2 1 22-MAR-15 07:09:50 3 1 22-MAR-15 07:10:10 4 2 22-MAR-15 07:46:51 5 Expected ActualBATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 2 1 21-MAR-15 07:09:17 1 1 22-MAR-15 07:09:50 3 1 22-MAR-15 07:10:10 4 2 22-MAR-15 07:46:51 5
  • 49. -- List batches and assigned them number based on their start date SELECT rownum, batch_id FROM batch_executions ORDER BY start_date SELECT rownum, start_date, batch_id FROM (SELECT start_date, batch_id FROM batch_executions ORDER BY start_date) WRONG CORRECT
  • 51. -- List batches and assigned them number based on their start date SELECT rownum, start_date, batch_id FROM (SELECT start_date, batch_id FROM batch_executions ORDER BY start_date)
  • 52. -- List batches and assigned them number based on their start date SELECT rownum, start_date, batch_id FROM (SELECT start_date, batch_id FROM batch_executions ORDER BY start_date) SELECT row_number OVER (ORDER BY start_date), start_date, batch_id FROM batch_executions
  • 53. Function(arg1,..., argn) OVER ( [PARTITION BY <...>] [ORDER BY <....>] [<window_clause>] )
  • 54. Function(arg1,..., argn) OVER ( [PARTITION BY <...>] [ORDER BY <....>] [<window_clause>] )
  • 55. Function(arg1,..., argn) OVER ( [PARTITION BY <...>] [ORDER BY <....>] [<window_clause>] )
  • 56. -- List batches and assigned them number based on their start date but only for the batch group BATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 1 1 21-MAR-15 07:09:17 2 1 22-MAR-15 07:09:50 3 1 22-MAR-15 07:10:10 4 2 22-MAR-15 07:46:51 1 Expected
  • 57. -- List batches and assigned them number based on their start date but only for the batch group SELECT rownum, start_date, batch_id FROM (SELECT start_date, batch_id FROM batch_executions ORDER BY start_date)
  • 58. -- List batches and assigned them number based on their start date but only for the batch group SELECT rownum, start_date, batch_id FROM (SELECT start_date, batch_id FROM batch_executions ORDER BY start_date) WRONG
  • 59. -- List batches and assigned them number based on their start date but only for the batch group SELECT rownum, start_date, batch_id FROM (SELECT start_date, batch_id FROM batch_executions ORDER BY start_date) SELECT row_number() OVER (PARTITION BY batch_id ORDER BY start_date), start_date, batch_id FROM batch_executions WRONG
  • 60. BATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 1 21-MAR-15 07:09:17 1 22-MAR-15 07:09:50 1 22-MAR-15 07:10:10 2 22-MAR-15 07:46:51
  • 61. BATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 1 21-MAR-15 07:09:17 1 22-MAR-15 07:09:50 1 22-MAR-15 07:10:10 2 22-MAR-15 07:46:51 BATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 1 21-MAR-15 07:09:17 1 22-MAR-15 07:09:50 1 22-MAR-15 07:10:10 2 22-MAR-15 07:46:51
  • 62. BATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 1 21-MAR-15 07:09:17 1 22-MAR-15 07:09:50 1 22-MAR-15 07:10:10 2 22-MAR-15 07:46:51 BATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 1 1 21-MAR-15 07:09:17 2 1 22-MAR-15 07:09:50 3 1 22-MAR-15 07:10:10 4 2 22-MAR-15 07:46:51 1 BATCH_ID START_DATE NUM 1 12-DEC-14 07:09:30 1 21-MAR-15 07:09:17 1 22-MAR-15 07:09:50 1 22-MAR-15 07:10:10 2 22-MAR-15 07:46:51
  • 63. -- List batches and assigned them number based on their start date but only for the batch group SELECT row_number() OVER (PARTITION BY batch_id ORDER BY start_date), start_date, batch_id FROM batch_executions
  • 64. ROW_NUMBER | RANK | DENSE_RANK
  • 65. SELECT ROW_NUMBER() OVER (ORDER BY duration), RANK() OVER (ORDER BY duration), DENSE_RANK() OVER (ORDER BY duration), DURATION FROM batch_executions
  • 66. SELECT ROW_NUMBER() OVER (ORDER BY duration), RANK() OVER (ORDER BY duration), DENSE_RANK() OVER (ORDER BY duration), DURATION FROM batch_executions RN RANK D_RANK DURATION 1 1 1 5 2 1 1 5 3 1 1 5 4 4 2 873
  • 68. -- List: -- average duration and last run date for each batch -- first previous and first following batch run dates -- first previous and first following batch by average duration SELECT batch_id, AVG(duration), MAX(start_date), LAG(batch_id) OVER (ORDER BY MAX(start_date)) prev_by_date, LEAD(batch_id) OVER (ORDER BY MAX(start_date)) next_by_date, LAG(batch_id) OVER (ORDER BY AVG(duration)) prev_by_duration, LEAD(batch_id) OVER (ORDER BY AVG(duration)) next_by_duration FROM batch_executions GROUP BY batch_id
  • 70. MIN | MAX | COUNT | SUM | AVG
  • 72. Function(arg1,..., argn) OVER ( [PARTITION BY <...>] [ORDER BY <....>] [<window_clause>] )
  • 74. [ROW or RANGE] BETWEEN <start_expr> AND <end_expr> <start_expr> UNBOUNDED PRECEDING CURRENT ROW <sql_expr> PRECEDING or FOLLOWING. <end_expr> UNBOUNDED FOLLOWING or CURRENT ROW or <sql_expr> PRECEDING or FOLLOWING.
  • 76. [ROW or RANGE] BETWEEN <start_expr> AND <end_expr> <start_expr> UNBOUNDED PECEDING CURRENT ROW <sql_expr> PRECEDING or FOLLOWING. <end_expr> UNBOUNDED FOLLOWING or CURRENT ROW or <sql_expr> PRECEDING or FOLLOWING.
  • 81. The Problem system status today system status by day
  • 82. The Problem system status today system status by day system status by month
  • 85. We define: Initial State = (available amount, financed amount, potential amount) Transition change vector for each transition e.g. Not Eligible -> Eligible (+500, 0, +500)
  • 86. We define: Initial State = (available amount, financed amount, potential amount) Transition change vector for each transition e.g. Not Eligible -> Eligible (+500, 0, +500) Note: We need only first and last day transitions
  • 91. Resources Analytic functions by Example: http://www.orafaq.com/node/55 Oracle Base: http://www.oracle-base.com/articles/misc/analytic-functions.php http://www.oracle-base.com/articles/misc/lag-lead-analytic- functions.php http://www.oracle-base.com/articles/misc/first-value-and-last-value- analytic-functions.php