SlideShare a Scribd company logo
Dramatically increase your database's
performance using hierarchical and
recursive queries
Dani Monteiro
@DaniMonteiroDBA
Rodrigo Moutinho
@rcmoutinho
• Hacking your query
• Know about the available resources
• Hierarchical queries
• Recursive queries
Agenda
• Tables and relationships
• Available indexes
• Data volume on each queried table
Hacking your query
Hacking your query
• ERP TOTVS
• Sports T-shirt Factory
• What do I have to release in my stock?
• Daily process of more than two hours (after one click)
Real Example
• Subqueries
• Views
• Materialized Views
• Functions
Available Resources
• Request any database process
• To create a query
• To create and use a database feature (views, functions, ...)
Permission Levels
SELECT
SC5.C5_NUM AS PED,
SC5.C5_VEND1 AS REPRES,
SA1.A1_NOME AS NOME,
(SELECT SUM((C6_QTDVEN - C6_QTDENT))
FROM SC6010 C6, SC9010 C9 WHERE ... [10 condições] ) AS QTDFAL,
(SELECT SUM((C6_QTDVEN - C6_QTDENT) * C6_PRCVEN)
FROM SC6010 C6, SC9010 C9 WHERE ... [10 condições] ) AS VALFAL,
(SELECT SUM (((C6_QTDVEN - C6_QTDENT) * C6_PRCVEN) - (C6_XQTD05 * C6_PRCVEN))
FROM SC6010 C6, SC9010 C9 WHERE ... [10 condições] ) AS VALOR,
SE4.E4_COND AS COND,
SC5.C5_OBSPED AS OBS,
SC5.C5_PREVIST as PREV,
SC5.C5_XST05 AS ST,
SC5.C5_XFRET AS FRET,
(SELECT SUM(C6_VALOR)
FROM SC6010 C6, SC9010 C9 WHERE ... [9 condições] ) AS TOT
FROM SC5010 SC5, SC6010 SC6, SC9010 SC9, SA1010 SA1, SF4010 SF4, SE4010 SE4
WHERE ... [29 condições]
GROUP BY SC5.C5_NUM, SC5.C5_VEND1, SA1.A1_NOME, SE4.E4_COND,
SC5.C5_OBSPED, SC5.C5_PREVIST, SC5.C5_XST05, SC5.C5_XFRET
ORDER BY SA1.A1_NOME
Subqueries
Subqueries
Quantidade
Faltante
SC6 - Item
Pedido Venda
SC9 - Item
Pedido Venda
Liberado
SUM SELECT
Subqueries
QTDFAL
SC6
SC9
SUM
VALFAL
SC6
SC9
VALOR
SC6
SC9
TOTAL
SC6
SC9
SUM
SUM
SUM
SELECT
SELECT
SELECT
SELECT
SELECT
Common Table Expression
WITH NICKNAME_1 AS (
SELECT ... FROM TABLE_1 ...
), NICKNAME_2 AS (
SELECT ... FROM NICKNAME_1 INNER JOIN TABLE_2 ...
)
SELECT ... FROM NICKNAME_1 INNER JOIN NICKNAME_2 ...
WHERE ...
GROUP BY ...
ORDER BY ...
Hierarchical Queries
• Reuse queries as a temporary result
WITH TABLE_PEDIDO AS (
SELECT ...
), TABLE_QUANTIDADE AS (
SELECT ...
), TABLE_ITENS_C6 AS (
SELECT ... FROM TABLE_QUANTIDADE ...
)
SELECT ...
FROM TABLE_PEDIDO AS T_PEDIDO, TABLE_ITENS_C6 AS T_ITENS_C6, ...
WHERE ...
ORDER BY ...
Better Performance
), TABLE_QUANTIDADE AS (
SELECT
C6_NUM AS C6NUM, C6_QTDVEN AS C6QTDVEN, C6_QTDENT AS C6QTDENT,
C6_PRCVEN AS C6PRCVEN, C6_XQTD05 AS C6XQTD05, C6_VALOR AS C6VALOR,
C6_XFLAG AS C6XFLAG, C6_LOCAL AS C6LOCAL, C6_TES AS C6TES
FROM SC6010 C6, SC9010 C9
WHERE ... [11 condições]
), TABLE_ITENS_C6 AS (
SELECT
C6NUM AS NUM,
C6TES AS C6TES,
SUM( (C6QTDVEN-C6QTDENT) ) AS QTDFAL,
SUM( (C6QTDVEN-C6QTDENT) * C6PRCVEN ) AS VALFAL,
SUM( ( (C6QTDVEN-C6QTDENT) * C6PRCVEN) - (C6XQTD05 * C6PRCVEN) ) AS VALOR,
SUM(C6VALOR) AS TOT
FROM TABLE_QUANTIDADE
GROUP BY C6NUM, C6TES
)
Better Performance
Resultado
Pedidos de
Venda
Somatório
Quantidades
Quantidades
Item Pedidos de
Venda
Readability
WITH TABLE_PEDIDO AS (
SELECT ... FROM SC5010 SC5 WHERE ...
), TABLE_QUANTIDADE AS (
SELECT ... FROM SC6010 C6, SC9010 C9 WHERE ...
), TABLE_ITENS_C6 AS (
SELECT ... FROM TABLE_QUANTIDADE ...
)
SELECT DISTINCT T_PEDIDO.PED AS PED, T_PEDIDO.REPRES AS REPRES,
SA1.A1_NOME AS NOME, T_ITENS_C6.QTDFAL AS QTDFAL, ...
FROM TABLE_PEDIDO AS T_PEDIDO, TABLE_ITENS_C6 AS T_ITENS_C6, ...
WHERE T_ITENS_C6.NUM = T_PEDIDO.PED
AND SA1.A1_FILIAL = ' '
...
Readability
WITH TABLE_PEDIDO AS (
SELECT
SC5.C5_NUM AS PED,
SC5.C5_VEND1 AS REPRES,
SC5.C5_OBSPED AS OBS,
...
FROM SC5010 SC5
WHERE ... [6 condições]
), TABLE_QUANTIDADE AS (
Readability
), TABLE_QUANTIDADE AS (
SELECT
C6_NUM AS C6NUM,
C6_QTDVEN AS C6QTDVEN,
C6_QTDENT AS C6QTDENT,
...
FROM SC6010 C6, SC9010 C9
WHERE ... [11 condições]
), TABLE_ITENS_C6 AS (
Readability
), TABLE_ITENS_C6 AS (
SELECT
C6NUM AS NUM,
C6TES AS C6TES,
SUM( (C6QTDVEN-C6QTDENT) ) AS QTDFAL,
SUM( (C6QTDVEN-C6QTDENT) * C6PRCVEN ) AS VALFAL,
SUM( ( (C6QTDVEN-C6QTDENT) * C6PRCVEN) - (C6XQTD05 * C6PRCVEN) ) AS VALOR,
SUM(C6VALOR) AS TOT
FROM TABLE_QUANTIDADE
GROUP BY C6NUM, C6TES
)
Readability
SELECT DISTINCT
T_PEDIDO.PED AS PED,
T_PEDIDO.REPRES AS REPRES,
SA1.A1_NOME AS NOME,
T_ITENS_C6.QTDFAL AS QTDFAL,
...
FROM
TABLE_PEDIDO AS T_PEDIDO,
TABLE_ITENS_C6 AS T_ITENS_C6,
SA1010 AS SA1,
SF4010 AS SF4,
SE4010 AS SE4
WHERE ... [11 condições]
ORDER BY SA1.A1_NOME
• Reuse query result
• Hierarchical structures
Recursive Queries
• Shows the result by levels
• What are the "root" records
• Then the "children"
• Then, "children" of the "children”...
Recursive Queries
Example... A menu
Fonte das imagens: https://blogs.msdn.microsoft.com/fcatae/2010/11/10/query-recursiva/
What about the code?
WITH RECURSIVE cteMenuNivel(id,Nome,Nivel,NomeCompleto)
AS (-- Ancora
SELECT id,Nome,1 AS 'Nivel',CAST(Nome AS VARCHAR(255)) AS 'NomeCompleto'
FROM tbMenu WHERE idPai IS NULL
UNION ALL
-- Parte RECURSIVA
SELECT
m.id,m.Nome,c.Nivel + 1 AS 'Nivel',
CAST((c.NomeCompleto + '/' + m.Nome) AS VARCHAR(255)) 'NomeCompleto'
FROM tbMenu m INNER JOIN cteMenuNivel c ON m.idPai = c.id)
SELECT Nivel,NomeCompleto FROM cteMenuNivel;
• Easier
• Depending on the number of levels
the performance is better
Why CTE?
Rodrigo Moutinho
@rcmoutinho
Dani Monteiro
@DaniMonteiroDBA
http://bit.ly/cte-example

More Related Content

Similar to Dramatically increase your database's performance using hierarchical and recursive queries

Advanced SQL For Data Scientists
Advanced SQL For Data ScientistsAdvanced SQL For Data Scientists
Advanced SQL For Data Scientists
Databricks
 
What's New in MariaDB Server 10.3
What's New in MariaDB Server 10.3What's New in MariaDB Server 10.3
What's New in MariaDB Server 10.3
MariaDB plc
 
MariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
MariaDB Server 10.3 - Temporale Daten und neues zur DB-KompatibilitätMariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
MariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
MariaDB plc
 
MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions
oysteing
 
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
 
MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table ExpressionsMySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions
oysteing
 
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
Mark Wong
 
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
Command Prompt., Inc
 
Ctes percona live_2017
Ctes percona live_2017Ctes percona live_2017
Ctes percona live_2017
Guilhem Bichot
 
Optimizer Trace Walkthrough
Optimizer Trace WalkthroughOptimizer Trace Walkthrough
Optimizer Trace Walkthrough
Sergey Petrunya
 
Wellington APAC Groundbreakers tour - SQL Pattern Matching
Wellington APAC Groundbreakers tour - SQL Pattern MatchingWellington APAC Groundbreakers tour - SQL Pattern Matching
Wellington APAC Groundbreakers tour - SQL Pattern Matching
Connor McDonald
 
Results cache
Results cacheResults cache
wuqiSpank.org -- The First "Table Centric" Approach to Solving SQL Performan...
wuqiSpank.org --  The First "Table Centric" Approach to Solving SQL Performan...wuqiSpank.org --  The First "Table Centric" Approach to Solving SQL Performan...
wuqiSpank.org -- The First "Table Centric" Approach to Solving SQL Performan...
Erik Ostermueller
 
MariaDB Temporal Tables
MariaDB Temporal TablesMariaDB Temporal Tables
MariaDB Temporal Tables
Federico Razzoli
 
Sql
SqlSql
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sql
McNamaraChiwaye
 
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
Mark Wong
 
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
 
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
Connor McDonald
 
Row patternmatching12ctech14
Row patternmatching12ctech14Row patternmatching12ctech14
Row patternmatching12ctech14
stewashton
 

Similar to Dramatically increase your database's performance using hierarchical and recursive queries (20)

Advanced SQL For Data Scientists
Advanced SQL For Data ScientistsAdvanced SQL For Data Scientists
Advanced SQL For Data Scientists
 
What's New in MariaDB Server 10.3
What's New in MariaDB Server 10.3What's New in MariaDB Server 10.3
What's New in MariaDB Server 10.3
 
MariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
MariaDB Server 10.3 - Temporale Daten und neues zur DB-KompatibilitätMariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
MariaDB Server 10.3 - Temporale Daten und neues zur DB-Kompatibilität
 
MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions
 
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
 
MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table ExpressionsMySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions
 
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
 
Ctes percona live_2017
Ctes percona live_2017Ctes percona live_2017
Ctes percona live_2017
 
Optimizer Trace Walkthrough
Optimizer Trace WalkthroughOptimizer Trace Walkthrough
Optimizer Trace Walkthrough
 
Wellington APAC Groundbreakers tour - SQL Pattern Matching
Wellington APAC Groundbreakers tour - SQL Pattern MatchingWellington APAC Groundbreakers tour - SQL Pattern Matching
Wellington APAC Groundbreakers tour - SQL Pattern Matching
 
Results cache
Results cacheResults cache
Results cache
 
wuqiSpank.org -- The First "Table Centric" Approach to Solving SQL Performan...
wuqiSpank.org --  The First "Table Centric" Approach to Solving SQL Performan...wuqiSpank.org --  The First "Table Centric" Approach to Solving SQL Performan...
wuqiSpank.org -- The First "Table Centric" Approach to Solving SQL Performan...
 
MariaDB Temporal Tables
MariaDB Temporal TablesMariaDB Temporal Tables
MariaDB Temporal Tables
 
Sql
SqlSql
Sql
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sql
 
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
 
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
 
Row patternmatching12ctech14
Row patternmatching12ctech14Row patternmatching12ctech14
Row patternmatching12ctech14
 

Recently uploaded

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 

Dramatically increase your database's performance using hierarchical and recursive queries

  • 1. Dramatically increase your database's performance using hierarchical and recursive queries Dani Monteiro @DaniMonteiroDBA Rodrigo Moutinho @rcmoutinho
  • 2. • Hacking your query • Know about the available resources • Hierarchical queries • Recursive queries Agenda
  • 3. • Tables and relationships • Available indexes • Data volume on each queried table Hacking your query
  • 5. • ERP TOTVS • Sports T-shirt Factory • What do I have to release in my stock? • Daily process of more than two hours (after one click) Real Example
  • 6. • Subqueries • Views • Materialized Views • Functions Available Resources
  • 7. • Request any database process • To create a query • To create and use a database feature (views, functions, ...) Permission Levels
  • 8. SELECT SC5.C5_NUM AS PED, SC5.C5_VEND1 AS REPRES, SA1.A1_NOME AS NOME, (SELECT SUM((C6_QTDVEN - C6_QTDENT)) FROM SC6010 C6, SC9010 C9 WHERE ... [10 condições] ) AS QTDFAL, (SELECT SUM((C6_QTDVEN - C6_QTDENT) * C6_PRCVEN) FROM SC6010 C6, SC9010 C9 WHERE ... [10 condições] ) AS VALFAL, (SELECT SUM (((C6_QTDVEN - C6_QTDENT) * C6_PRCVEN) - (C6_XQTD05 * C6_PRCVEN)) FROM SC6010 C6, SC9010 C9 WHERE ... [10 condições] ) AS VALOR, SE4.E4_COND AS COND, SC5.C5_OBSPED AS OBS, SC5.C5_PREVIST as PREV, SC5.C5_XST05 AS ST, SC5.C5_XFRET AS FRET, (SELECT SUM(C6_VALOR) FROM SC6010 C6, SC9010 C9 WHERE ... [9 condições] ) AS TOT FROM SC5010 SC5, SC6010 SC6, SC9010 SC9, SA1010 SA1, SF4010 SF4, SE4010 SE4 WHERE ... [29 condições] GROUP BY SC5.C5_NUM, SC5.C5_VEND1, SA1.A1_NOME, SE4.E4_COND, SC5.C5_OBSPED, SC5.C5_PREVIST, SC5.C5_XST05, SC5.C5_XFRET ORDER BY SA1.A1_NOME Subqueries
  • 9. Subqueries Quantidade Faltante SC6 - Item Pedido Venda SC9 - Item Pedido Venda Liberado SUM SELECT
  • 11. Common Table Expression WITH NICKNAME_1 AS ( SELECT ... FROM TABLE_1 ... ), NICKNAME_2 AS ( SELECT ... FROM NICKNAME_1 INNER JOIN TABLE_2 ... ) SELECT ... FROM NICKNAME_1 INNER JOIN NICKNAME_2 ... WHERE ... GROUP BY ... ORDER BY ...
  • 12. Hierarchical Queries • Reuse queries as a temporary result WITH TABLE_PEDIDO AS ( SELECT ... ), TABLE_QUANTIDADE AS ( SELECT ... ), TABLE_ITENS_C6 AS ( SELECT ... FROM TABLE_QUANTIDADE ... ) SELECT ... FROM TABLE_PEDIDO AS T_PEDIDO, TABLE_ITENS_C6 AS T_ITENS_C6, ... WHERE ... ORDER BY ...
  • 13. Better Performance ), TABLE_QUANTIDADE AS ( SELECT C6_NUM AS C6NUM, C6_QTDVEN AS C6QTDVEN, C6_QTDENT AS C6QTDENT, C6_PRCVEN AS C6PRCVEN, C6_XQTD05 AS C6XQTD05, C6_VALOR AS C6VALOR, C6_XFLAG AS C6XFLAG, C6_LOCAL AS C6LOCAL, C6_TES AS C6TES FROM SC6010 C6, SC9010 C9 WHERE ... [11 condições] ), TABLE_ITENS_C6 AS ( SELECT C6NUM AS NUM, C6TES AS C6TES, SUM( (C6QTDVEN-C6QTDENT) ) AS QTDFAL, SUM( (C6QTDVEN-C6QTDENT) * C6PRCVEN ) AS VALFAL, SUM( ( (C6QTDVEN-C6QTDENT) * C6PRCVEN) - (C6XQTD05 * C6PRCVEN) ) AS VALOR, SUM(C6VALOR) AS TOT FROM TABLE_QUANTIDADE GROUP BY C6NUM, C6TES )
  • 15. Readability WITH TABLE_PEDIDO AS ( SELECT ... FROM SC5010 SC5 WHERE ... ), TABLE_QUANTIDADE AS ( SELECT ... FROM SC6010 C6, SC9010 C9 WHERE ... ), TABLE_ITENS_C6 AS ( SELECT ... FROM TABLE_QUANTIDADE ... ) SELECT DISTINCT T_PEDIDO.PED AS PED, T_PEDIDO.REPRES AS REPRES, SA1.A1_NOME AS NOME, T_ITENS_C6.QTDFAL AS QTDFAL, ... FROM TABLE_PEDIDO AS T_PEDIDO, TABLE_ITENS_C6 AS T_ITENS_C6, ... WHERE T_ITENS_C6.NUM = T_PEDIDO.PED AND SA1.A1_FILIAL = ' ' ...
  • 16. Readability WITH TABLE_PEDIDO AS ( SELECT SC5.C5_NUM AS PED, SC5.C5_VEND1 AS REPRES, SC5.C5_OBSPED AS OBS, ... FROM SC5010 SC5 WHERE ... [6 condições] ), TABLE_QUANTIDADE AS (
  • 17. Readability ), TABLE_QUANTIDADE AS ( SELECT C6_NUM AS C6NUM, C6_QTDVEN AS C6QTDVEN, C6_QTDENT AS C6QTDENT, ... FROM SC6010 C6, SC9010 C9 WHERE ... [11 condições] ), TABLE_ITENS_C6 AS (
  • 18. Readability ), TABLE_ITENS_C6 AS ( SELECT C6NUM AS NUM, C6TES AS C6TES, SUM( (C6QTDVEN-C6QTDENT) ) AS QTDFAL, SUM( (C6QTDVEN-C6QTDENT) * C6PRCVEN ) AS VALFAL, SUM( ( (C6QTDVEN-C6QTDENT) * C6PRCVEN) - (C6XQTD05 * C6PRCVEN) ) AS VALOR, SUM(C6VALOR) AS TOT FROM TABLE_QUANTIDADE GROUP BY C6NUM, C6TES )
  • 19. Readability SELECT DISTINCT T_PEDIDO.PED AS PED, T_PEDIDO.REPRES AS REPRES, SA1.A1_NOME AS NOME, T_ITENS_C6.QTDFAL AS QTDFAL, ... FROM TABLE_PEDIDO AS T_PEDIDO, TABLE_ITENS_C6 AS T_ITENS_C6, SA1010 AS SA1, SF4010 AS SF4, SE4010 AS SE4 WHERE ... [11 condições] ORDER BY SA1.A1_NOME
  • 20. • Reuse query result • Hierarchical structures Recursive Queries
  • 21. • Shows the result by levels • What are the "root" records • Then the "children" • Then, "children" of the "children”... Recursive Queries
  • 22. Example... A menu Fonte das imagens: https://blogs.msdn.microsoft.com/fcatae/2010/11/10/query-recursiva/
  • 23. What about the code? WITH RECURSIVE cteMenuNivel(id,Nome,Nivel,NomeCompleto) AS (-- Ancora SELECT id,Nome,1 AS 'Nivel',CAST(Nome AS VARCHAR(255)) AS 'NomeCompleto' FROM tbMenu WHERE idPai IS NULL UNION ALL -- Parte RECURSIVA SELECT m.id,m.Nome,c.Nivel + 1 AS 'Nivel', CAST((c.NomeCompleto + '/' + m.Nome) AS VARCHAR(255)) 'NomeCompleto' FROM tbMenu m INNER JOIN cteMenuNivel c ON m.idPai = c.id) SELECT Nivel,NomeCompleto FROM cteMenuNivel;
  • 24. • Easier • Depending on the number of levels the performance is better Why CTE?