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.

TSQL Advanced Query Techniques

  • 1.
  • 2.
  • 3.
  • 4.
    T-SQL ADVANCED QUERY TECHNIQUES GianlucaSartori SQL408 sqlconsulting.it, owner gianluca.sartori@sqlconsulting.it
  • 5.
    GIANLUCA SARTORI • ConsulenteFreelance • 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 codiceperformante • Misurare le prestazioni • APPLY • OVER • Tally Tables • Set-based iteration • String Concatenation
  • 7.
  • 8.
    La piramide delperformance tuning
  • 9.
    RBAR Row By AgonizingRow • 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
  • 12.
  • 13.
    Come misurare leprestazioni • 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
  • 14.
  • 15.
  • 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
  • 19.
  • 20.
  • 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 SQLServer 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!
  • 23.
  • 24.
  • 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)
  • 28.
  • 29.
  • 30.
    Set-based Iteration • Ripeteblocchi di codice set-based in un ciclo • Compromesso tra codice procedurale e set-based • Può applicare approssimazioni successive a un problema complesso
  • 31.
  • 32.
  • 33.
    String Concatenation • UsoFOR XML PATH(‘’) • Concatena tutte le righe usando un path vuoto • Attenzione all’entitizzazione dei caratteri • <  &lt;
  • 34.
  • 35.
    Links APPLY • Understanding andusing 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
  • 38.
  • 39.
    Grazie.Non dimenticare diriempire il modulo di feedback SQL408
  • 40.
  • 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.