SlideShare a Scribd company logo
1 of 41
11-12 marzo 2014
Milano
GRAZIE AI NOSTRI SPONSOR
#sqlc2014
T-SQL ADVANCED QUERY
TECHNIQUES
Gianluca Sartori
SQL408
sqlconsulting.it, owner
gianluca.sartori@sqlconsulting.it
GIANLUCA SARTORI
• Consulente Freelance
• 15 anni di esperienza SQL Server, dalla v. 7
• Specializzato in performance tuning
• MCTS, MCITP, MCT
• DBA @ Scuderia Formula 1
• BLOG: http://spaghettidba.com/
• TWITTER: @spaghettidba
Agenda
• Scrivere codice performante
• Misurare le prestazioni
• APPLY
• OVER
• Tally Tables
• Set-based iteration
• String Concatenation
SCRIVERE CODICE
PERFORMANTE
La piramide del performance tuning
RBAR
Row By Agonizing Row
• Cursori
• Cicli WHILE
• Cursori lato applicativo
• Funzioni scalari e multi-statement
http://www.sqlservercentral.com/Authors/Articles/Jeff_Moden/80567/
Jeff Moden
Scrivere codice più efficiente
• Conoscere tutte le potenzialità del linguaggio
• Non mettere limiti alla fantasia
• Conoscere problemi noti e le possibili soluzioni
• Chiedere aiuto:
• Forums
• #sqlhelp
Ci vuole fantasia
• La stessa query può essere espressa in molti
modi diversi
• Anche i problemi più semplici possono essere
risolti in modi sorprendenti
• Non scartiamo nulla a priori
• Contiamo fino a 10
COME MISURARE LE
PRESTAZIONI
Come misurare le prestazioni
• Tempo di esecuzione in SSMS?
• Comprende il tempo di trasferimento e formattazione dei risultati
• Scartare i risultati
• SET STATISTICS TIME
• Trace
• XE Session
• Ripetere l’esecuzione un numero sufficiente di volte
• «Pre-riscaldare» la cache
• Saranno le condizioni in produzione
DEMOMisurare le prestazioni
APPLY
APPLY
• Operatore tabellare
• Applica una funzione tabellare ad un set di input
APPLY
• Uso comune: table valued functions
SELECT *
FROM SomeTable AS src
CROSS APPLY SomeFunction(src.SomeColumn);
• Consente di trasformare le funzioni UDF e
MSTVF in funzioni ITVF
APPLY
• Altre applicazioni: inline (correlated) subquery
SELECT *
FROM SomeTable AS A
CROSS APPLY (
SELECT *
FROM SomeOtherTable AS A
WHERE A.SomeColumn = B.SomeOtherColumn
) AS CA;
• Spesso può essere tradotto in un JOIN
DEMOAPPLY
OVER
OVER
• Definisce delle «finestre» di righe
• Applica a ciascuna finestra una funzione
• Ranking
• ROW_NUMBER(), RANK(), …
• Aggregate
• MIN(), MAX(), SUM(), …
• Analytic
• LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE(), …
OVER
• Da SQL Server 2012 supporta i nuovi costrutti ROWS
e RANGE
• Permettono di calcolare «running aggregates»
• Prima di SQL Server 2012
• Cursori
• Triangular Join
• Quirky Update*
• Quirky XML* *DANGER!
DEMOOVER
TALLY TABLE
TALLY TABLE
• E’ una semplice tabella di numeri
• «Coltellino Svizzero» T-SQL
• Utile per mille applicazioni
• String splitting
• Esplodere una riga per quantità
TALLY TABLE
• Può essere una tabella permanente
• Deve essere letta (logical reads)
• Può essere definita «al volo»
• Nessuna logical read
• CTE nella query
• ITVF salvata nel database
String splitting
WHERE SUBSTRING(@pString,t.N,1) = ','
SUBSTRING(@pString, l.N1, l.L1)
DEMOString splitting
SET-BASED ITERATION
Set-based Iteration
• Ripete blocchi di codice set-based in un ciclo
• Compromesso tra codice procedurale e set-based
• Può applicare approssimazioni successive a un
problema complesso
DEMOAssegnazione ordini a magazzino
STRING CONCATENATION
String Concatenation
• Uso FOR XML PATH(‘’)
• Concatena tutte le righe usando un path vuoto
• Attenzione all’entitizzazione dei caratteri
• <  &lt;
DEMOString concatenation
Links
APPLY
• Understanding and using APPLY
• Part 1 http://bit.ly/1jZqLy0
• Part 2 http://bit.ly/O1CPTY
• Boost Your T-SQL with the APPLY Operator http://bit.ly/1gXKf3d
OVER
• OVER clause enhancements http://bit.ly/1e9lKhB
• New analytic functions in SQL Server 2012 http://bit.ly/O9ATsF
Links
Tally Table
• The “Numbers” or “Tally” Table http://bit.ly/1fgTaz3
String Splitting
• Tally OH! An improved SQL 8K “CSV splitter” Function
http://bit.ly/1cHEtWz
Running Totals
• Best approaches for grouped running totals
http://bit.ly/1i2wuTs
Links
Islands and Gaps
• The SQL of Gaps and Islands in Sequences http://bit.ly/1firuKa
• Gap detection http://bit.ly/1kH53lf
Bin packing
• Hugo Kornelis’ Bin Packing blog series http://bit.ly/1gdF6WO
QUESTIONS&
ANSWERS
Grazie.Non dimenticare di riempire il modulo di feedback
SQL408
#sqlc2014
© EventHandler S.r.l. All rights reserved.
Microsoft, Windows and all other trademarks and copyrights are the property of their respective owners. EventHandler cannot
guarantee the accuracy of any information provided after the date of this presentation.
EVENTHANDLER MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

More Related Content

Similar to TSQL Advanced Query Techniques

Laboratorio Di Basi Di Dati 04 P L S Q L E P Lpg S Q L
Laboratorio Di  Basi Di  Dati 04  P L  S Q L E  P Lpg S Q LLaboratorio Di  Basi Di  Dati 04  P L  S Q L E  P Lpg S Q L
Laboratorio Di Basi Di Dati 04 P L S Q L E P Lpg S Q L
guestbe916c
 
Introduzione a TypeScript
Introduzione a TypeScriptIntroduzione a TypeScript
Introduzione a TypeScript
Sinergia Totale
 
DotNetToscana - Sessione TypeScript
DotNetToscana - Sessione TypeScriptDotNetToscana - Sessione TypeScript
DotNetToscana - Sessione TypeScript
Sinergia Totale
 
Implementare e mantenere un progetto azure sql database v.2
Implementare e mantenere un progetto azure sql database v.2Implementare e mantenere un progetto azure sql database v.2
Implementare e mantenere un progetto azure sql database v.2
Emanuele Zanchettin
 
Slide typescript - xe dotnet - Codemotion Rome 2015
Slide typescript - xe dotnet - Codemotion Rome 2015Slide typescript - xe dotnet - Codemotion Rome 2015
Slide typescript - xe dotnet - Codemotion Rome 2015
Codemotion
 
OCP-Architettura e caratteristiche della PaaS
OCP-Architettura e caratteristiche della PaaSOCP-Architettura e caratteristiche della PaaS
OCP-Architettura e caratteristiche della PaaS
opencityplatform
 

Similar to TSQL Advanced Query Techniques (20)

SQL Server Modern Query Processing
SQL Server Modern Query ProcessingSQL Server Modern Query Processing
SQL Server Modern Query Processing
 
SQL Server Modern Query Processing
SQL Server Modern Query ProcessingSQL Server Modern Query Processing
SQL Server Modern Query Processing
 
Novità di SQL Server 2017
Novità di SQL Server 2017Novità di SQL Server 2017
Novità di SQL Server 2017
 
Laboratorio Di Basi Di Dati 04 P L S Q L E P Lpg S Q L
Laboratorio Di  Basi Di  Dati 04  P L  S Q L E  P Lpg S Q LLaboratorio Di  Basi Di  Dati 04  P L  S Q L E  P Lpg S Q L
Laboratorio Di Basi Di Dati 04 P L S Q L E P Lpg S Q L
 
Introduzione a TypeScript
Introduzione a TypeScriptIntroduzione a TypeScript
Introduzione a TypeScript
 
SQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisSQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload Analysis
 
corso oracle plsql.ppt
corso oracle plsql.pptcorso oracle plsql.ppt
corso oracle plsql.ppt
 
DotNetToscana - Sessione TypeScript
DotNetToscana - Sessione TypeScriptDotNetToscana - Sessione TypeScript
DotNetToscana - Sessione TypeScript
 
Progetto MigrOS: progettazione e sviluppo degli strumenti di transcodifica de...
Progetto MigrOS: progettazione e sviluppo degli strumenti di transcodifica de...Progetto MigrOS: progettazione e sviluppo degli strumenti di transcodifica de...
Progetto MigrOS: progettazione e sviluppo degli strumenti di transcodifica de...
 
Implementare e mantenere un progetto azure sql database v.2
Implementare e mantenere un progetto azure sql database v.2Implementare e mantenere un progetto azure sql database v.2
Implementare e mantenere un progetto azure sql database v.2
 
Slide typescript - xe dotnet - Codemotion Rome 2015
Slide typescript - xe dotnet - Codemotion Rome 2015Slide typescript - xe dotnet - Codemotion Rome 2015
Slide typescript - xe dotnet - Codemotion Rome 2015
 
Metadata Driven Pipeline with Microsoft Fabric
Metadata Driven Pipeline  with Microsoft FabricMetadata Driven Pipeline  with Microsoft Fabric
Metadata Driven Pipeline with Microsoft Fabric
 
OCP Paas_ultima
OCP Paas_ultimaOCP Paas_ultima
OCP Paas_ultima
 
Swagger pertutti
Swagger pertuttiSwagger pertutti
Swagger pertutti
 
Web app slots and webapi versioning
Web app slots and webapi versioningWeb app slots and webapi versioning
Web app slots and webapi versioning
 
OCP-Architettura e caratteristiche della PaaS
OCP-Architettura e caratteristiche della PaaSOCP-Architettura e caratteristiche della PaaS
OCP-Architettura e caratteristiche della PaaS
 
ASP.NET MVC: Andare oltre il 100% (Web@work)
ASP.NET MVC: Andare oltre il 100% (Web@work)ASP.NET MVC: Andare oltre il 100% (Web@work)
ASP.NET MVC: Andare oltre il 100% (Web@work)
 
Open Source Day 2015 - DBaaS con Docker: un caso di studio
Open Source Day 2015 - DBaaS con Docker: un caso di studioOpen Source Day 2015 - DBaaS con Docker: un caso di studio
Open Source Day 2015 - DBaaS con Docker: un caso di studio
 
Rx - ReactiveX
Rx - ReactiveXRx - ReactiveX
Rx - ReactiveX
 
OrientDB & Big Data
OrientDB & Big DataOrientDB & Big Data
OrientDB & Big Data
 

More from Gianluca Sartori

More from Gianluca Sartori (9)

Benchmarking like a pro
Benchmarking like a proBenchmarking like a pro
Benchmarking like a pro
 
Sql server infernals
Sql server infernalsSql server infernals
Sql server infernals
 
SQL Server 2016 New Security Features
SQL Server 2016 New Security FeaturesSQL Server 2016 New Security Features
SQL Server 2016 New Security Features
 
Responding to extended events in near real time
Responding to extended events in near real timeResponding to extended events in near real time
Responding to extended events in near real time
 
Sql server security in an insecure world
Sql server security in an insecure worldSql server security in an insecure world
Sql server security in an insecure world
 
SQL Server Worst Practices - EN
SQL Server Worst Practices - ENSQL Server Worst Practices - EN
SQL Server Worst Practices - EN
 
My Query is slow, now what?
My Query is slow, now what?My Query is slow, now what?
My Query is slow, now what?
 
A performance tuning methodology
A performance tuning methodologyA performance tuning methodology
A performance tuning methodology
 
SQL Server Worst Practices
SQL Server Worst PracticesSQL Server Worst Practices
SQL Server Worst Practices
 

TSQL Advanced Query Techniques

  • 4. T-SQL ADVANCED QUERY TECHNIQUES Gianluca Sartori SQL408 sqlconsulting.it, owner gianluca.sartori@sqlconsulting.it
  • 5. GIANLUCA SARTORI • Consulente Freelance • 15 anni di esperienza SQL Server, dalla v. 7 • Specializzato in performance tuning • MCTS, MCITP, MCT • DBA @ Scuderia Formula 1 • BLOG: http://spaghettidba.com/ • TWITTER: @spaghettidba
  • 6. Agenda • Scrivere codice performante • Misurare le prestazioni • APPLY • OVER • Tally Tables • Set-based iteration • String Concatenation
  • 8. La piramide del performance tuning
  • 9. RBAR Row By Agonizing Row • Cursori • Cicli WHILE • Cursori lato applicativo • Funzioni scalari e multi-statement http://www.sqlservercentral.com/Authors/Articles/Jeff_Moden/80567/ Jeff Moden
  • 10. Scrivere codice più efficiente • Conoscere tutte le potenzialità del linguaggio • Non mettere limiti alla fantasia • Conoscere problemi noti e le possibili soluzioni • Chiedere aiuto: • Forums • #sqlhelp
  • 11. Ci vuole fantasia • La stessa query può essere espressa in molti modi diversi • Anche i problemi più semplici possono essere risolti in modi sorprendenti • Non scartiamo nulla a priori • Contiamo fino a 10
  • 13. Come misurare le prestazioni • Tempo di esecuzione in SSMS? • Comprende il tempo di trasferimento e formattazione dei risultati • Scartare i risultati • SET STATISTICS TIME • Trace • XE Session • Ripetere l’esecuzione un numero sufficiente di volte • «Pre-riscaldare» la cache • Saranno le condizioni in produzione
  • 15. APPLY
  • 16. APPLY • Operatore tabellare • Applica una funzione tabellare ad un set di input
  • 17. APPLY • Uso comune: table valued functions SELECT * FROM SomeTable AS src CROSS APPLY SomeFunction(src.SomeColumn); • Consente di trasformare le funzioni UDF e MSTVF in funzioni ITVF
  • 18. APPLY • Altre applicazioni: inline (correlated) subquery SELECT * FROM SomeTable AS A CROSS APPLY ( SELECT * FROM SomeOtherTable AS A WHERE A.SomeColumn = B.SomeOtherColumn ) AS CA; • Spesso può essere tradotto in un JOIN
  • 20. OVER
  • 21. OVER • Definisce delle «finestre» di righe • Applica a ciascuna finestra una funzione • Ranking • ROW_NUMBER(), RANK(), … • Aggregate • MIN(), MAX(), SUM(), … • Analytic • LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE(), …
  • 22. OVER • Da SQL Server 2012 supporta i nuovi costrutti ROWS e RANGE • Permettono di calcolare «running aggregates» • Prima di SQL Server 2012 • Cursori • Triangular Join • Quirky Update* • Quirky XML* *DANGER!
  • 25. TALLY TABLE • E’ una semplice tabella di numeri • «Coltellino Svizzero» T-SQL • Utile per mille applicazioni • String splitting • Esplodere una riga per quantità
  • 26. TALLY TABLE • Può essere una tabella permanente • Deve essere letta (logical reads) • Può essere definita «al volo» • Nessuna logical read • CTE nella query • ITVF salvata nel database
  • 27. String splitting WHERE SUBSTRING(@pString,t.N,1) = ',' SUBSTRING(@pString, l.N1, l.L1)
  • 30. Set-based Iteration • Ripete blocchi di codice set-based in un ciclo • Compromesso tra codice procedurale e set-based • Può applicare approssimazioni successive a un problema complesso
  • 33. String Concatenation • Uso FOR XML PATH(‘’) • Concatena tutte le righe usando un path vuoto • Attenzione all’entitizzazione dei caratteri • <  &lt;
  • 35. Links APPLY • Understanding and using APPLY • Part 1 http://bit.ly/1jZqLy0 • Part 2 http://bit.ly/O1CPTY • Boost Your T-SQL with the APPLY Operator http://bit.ly/1gXKf3d OVER • OVER clause enhancements http://bit.ly/1e9lKhB • New analytic functions in SQL Server 2012 http://bit.ly/O9ATsF
  • 36. Links Tally Table • The “Numbers” or “Tally” Table http://bit.ly/1fgTaz3 String Splitting • Tally OH! An improved SQL 8K “CSV splitter” Function http://bit.ly/1cHEtWz Running Totals • Best approaches for grouped running totals http://bit.ly/1i2wuTs
  • 37. Links Islands and Gaps • The SQL of Gaps and Islands in Sequences http://bit.ly/1firuKa • Gap detection http://bit.ly/1kH53lf Bin packing • Hugo Kornelis’ Bin Packing blog series http://bit.ly/1gdF6WO
  • 39. Grazie.Non dimenticare di riempire il modulo di feedback SQL408
  • 41. © EventHandler S.r.l. All rights reserved. Microsoft, Windows and all other trademarks and copyrights are the property of their respective owners. EventHandler cannot guarantee the accuracy of any information provided after the date of this presentation. EVENTHANDLER MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.