Quick & Easy SQL TipsIke Ellishttp://www.ellisteam.netike@ellisteam.netTwitter: @ike_ellis1
Assumptions @ YouYou are a new DBAYou don’t want to rewrite your entire application with a new schema, new DAL, or new queriesYou want to learn just enough so that your SQL apps are fast and maintainable2
Tip #1 – Performance Problem: Check the low-hanging fruit Long-running jobsLong-running transactionsDBCC OPENTRANCheck for long-running queries/both in amount and in duration3
Tip #2:  Prettify!4http://extras.sqlservercentral.com/prettifier/prettifier.aspx
Tip #3 – Performance Problem : Identify hardware performance bottlenecks.MemoryDisk*ProcessorNetwork I/O*Most common bottleneck.  It’s the Disk I/O, Stupid.  (But it could be memory that’s causing it.)5
Tip #4: The right way to find hardware problemsMerging PerfMon and TracingGet the Batch and Completed Events OnlyNever trace from the computer you are monitoringAlways trace to a file and then load in a table after.6
Tip #5: Files, Files EverywhereAll need their own physical drive for space management and performanceMaster Data File (MDF)Log Files (LDF)TempDB FilesO/S/SQL FilesBAK Files7
Tip #6: The Log FileFills sequentially, so no need for striping, mirror is fine.Don’t let it get filled up: Simple Mode or Backup.8
Tip #7 - Good memory managementCheck for other applications running on the SQL ServerMove anti-virus (or at least make sure it wasn't scanning the SQL ports or the SQL files)Move Exchange and F&P services (cluster)Turn off unneeded servicesSQL is I/O bound, so I would turn off any network/disk intensive services (DHCP, DNS, etc)9
Tip #8 - Quick Indexing Tricks.check for clustered indexesSELECT t.[Name] FROM sys.Indexes i 	JOIN sys.Tables t 	ON t.Object_ID = i.Object_id	WHERE i.type_desc = 'HEAP'	ORDER BY t.[Name]check for nonclustered indexes on foreign key columns (ID Columns)select * from sys.columns c 	where c.name like '%id%'		and c.object_id not in 			(			select object_id from sys.index_columns			)check for non-clustered covering indexesreads outnumber inserts/updates 5 to 10 to 110
Tip #9 - Run the Index Tuning Wizard (DB Tuning Advisor)Run it a really long time, it is more accurate the longer it runsDon’t drop existing objectsIt’s OK to over-index11
Tip #10 – I don’t really know the symptoms, but SQL Doctor will find the cure.IderaRed GateDB ArtisonQuest12
Tip #11– Baseline the right wayIdera Diagnostics Manager & RedGate13
Tip #12 – Enforce Business Rules in the DBForeign KeysUnique ConstraintsCheck Constraints14
Tip #13 - Eliminate CursorsCursors focus on how, not why or whatCursors are expensiveCursors take up memory, which is usually a problem alreadyCursors can often be written using a set-based method15
Easy Tip #14 - Avoid Deadlocking, BlockingIndex TuneKeep transactions shortDon’t lock when you don’t have toHit the tables in the same order (create a table order document)Minimize the use of triggers16
Tip #15: CTE’sA named temporary result set based on a SELECT queryCommon Table ExpressionResult set can be used in SELECT, INSERT, UPDATE, or DELETE
Advantages of common table expressions:
Queries with derived tables become more readable
Provide traversal of recursive hierarchiesWITH TopSales (SalesPersonID, NumSales) AS( SELECT SalesPersonID, Count(*)   FROM Sales.SalesOrderHeader GROUP BY SalesPersonId )SELECT * FROM TopSales WHERE SalesPersonID IS NOT NULLORDER BY NumSales DESC
Tip #16: apply operatorright parameter can be a table, but meant for tvfcross apply does inner joinno output for row when udf produces no outputudf can get its parameters from left inputouter apply does left outer joinall rows from left input returnedmay have nulls for columns returned by udf
Tip #17: temptables vs. table variablestable variables
private to batch
avoids transaction affects
designed for smaller number of rows where scans are cheaper than seeks

More Related Content

PPTX
Quick & Easy SQL Tips
PPTX
Top 10 tips for software development management
PDF
Supply of labour in the netherlands
PPT
GPS/GPRS SIGAL presentation by Endri DHASKALI
PPT
2e data models
PDF
Taxand Netherlands may grant 30% expatriate rulings
PDF
Artpark impuls
PDF
Eloqua Benchmark Report
Quick & Easy SQL Tips
Top 10 tips for software development management
Supply of labour in the netherlands
GPS/GPRS SIGAL presentation by Endri DHASKALI
2e data models
Taxand Netherlands may grant 30% expatriate rulings
Artpark impuls
Eloqua Benchmark Report

Viewers also liked (9)

PPT
PPTX
Azure DocumentDB 101
PDF
Key Lessons Learned Building Recommender Systems for Large-Scale Social Netw...
PPTX
Introduction to Azure DocumentDB
PPTX
Hadoop for the Absolute Beginner
PPTX
SQL PASS BAC - 60 reporting tips in 60 minutes
PPTX
Top 10 sql server reporting services tips
PDF
Employment law & Employee tax in the Netherlands
PPTX
11 Goals of High Functioning SQL Developers
Azure DocumentDB 101
Key Lessons Learned Building Recommender Systems for Large-Scale Social Netw...
Introduction to Azure DocumentDB
Hadoop for the Absolute Beginner
SQL PASS BAC - 60 reporting tips in 60 minutes
Top 10 sql server reporting services tips
Employment law & Employee tax in the Netherlands
11 Goals of High Functioning SQL Developers
Ad

Similar to Quick & Easy SQL Tips (20)

PPTX
SQL Pass Architecture SQL Tips & Tricks
PPTX
SQL Server Tips & Tricks
PPTX
Tips & Tricks SQL in the City Seattle 2014
ODP
Performance tuning
PPTX
7 Database Mistakes YOU Are Making -- Linuxfest Northwest 2019
PPTX
Building scalable application with sql server
PDF
Dev buchan 30 proven tips
PPTX
Golden Hammer - Shawn Oden
PPTX
Boosting the Performance of your Rails Apps
PDF
Rails Tips and Best Practices
PPTX
Hidden Gems of Performance Tuning: Hierarchical Profiler and DML Trigger Opti...
PDF
The View - The top 30 Development tips
PDF
Lotusphere 2007 AD505 DevBlast 30 LotusScript Tips
PPTX
Top 10 Developer Mistakes That Won't Scale with SQL Server
PPTX
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
PPTX
SQL Server Performance Tuning with DMVs
PDF
Ad505 dev blast
PPTX
Top 10 tips for Oracle performance (Updated April 2015)
PDF
Architecting a Large Software Project - Lessons Learned
PPT
Ebook8
SQL Pass Architecture SQL Tips & Tricks
SQL Server Tips & Tricks
Tips & Tricks SQL in the City Seattle 2014
Performance tuning
7 Database Mistakes YOU Are Making -- Linuxfest Northwest 2019
Building scalable application with sql server
Dev buchan 30 proven tips
Golden Hammer - Shawn Oden
Boosting the Performance of your Rails Apps
Rails Tips and Best Practices
Hidden Gems of Performance Tuning: Hierarchical Profiler and DML Trigger Opti...
The View - The top 30 Development tips
Lotusphere 2007 AD505 DevBlast 30 LotusScript Tips
Top 10 Developer Mistakes That Won't Scale with SQL Server
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
SQL Server Performance Tuning with DMVs
Ad505 dev blast
Top 10 tips for Oracle performance (Updated April 2015)
Architecting a Large Software Project - Lessons Learned
Ebook8
Ad

More from Ike Ellis (20)

PPTX
Storytelling with Data with Power BI
PPTX
Storytelling with Data with Power BI.pptx
PPTX
Build a modern data platform.pptx
PPTX
Data Modeling on Azure for Analytics
PPTX
Migrate a successful transactional database to azure
PPTX
Data modeling trends for analytics
PPTX
Data modeling trends for Analytics
PPTX
Relational data modeling trends for transactional applications
PPTX
Power bi premium
PPTX
Move a successful onpremise oltp application to the cloud
PPTX
Azure Databricks is Easier Than You Think
PPTX
Pass 2018 introduction to dax
PPTX
Pass the Power BI Exam
PPTX
Slides for PUG 2018 - DAX CALCULATE
PPTX
Introduction to DAX
PPTX
60 reporting tips in 60 minutes - SQLBits 2018
PPTX
14 Habits of Great SQL Developers
PPTX
14 Habits of Great SQL Developers
PPTX
Dive Into Azure Data Lake - PASS 2017
PPTX
A lap around microsofts business intelligence platform
Storytelling with Data with Power BI
Storytelling with Data with Power BI.pptx
Build a modern data platform.pptx
Data Modeling on Azure for Analytics
Migrate a successful transactional database to azure
Data modeling trends for analytics
Data modeling trends for Analytics
Relational data modeling trends for transactional applications
Power bi premium
Move a successful onpremise oltp application to the cloud
Azure Databricks is Easier Than You Think
Pass 2018 introduction to dax
Pass the Power BI Exam
Slides for PUG 2018 - DAX CALCULATE
Introduction to DAX
60 reporting tips in 60 minutes - SQLBits 2018
14 Habits of Great SQL Developers
14 Habits of Great SQL Developers
Dive Into Azure Data Lake - PASS 2017
A lap around microsofts business intelligence platform

Recently uploaded (20)

PDF
Getting started with AI Agents and Multi-Agent Systems
PPTX
Benefits of Physical activity for teenagers.pptx
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PPTX
Modernising the Digital Integration Hub
PDF
Hybrid model detection and classification of lung cancer
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
The various Industrial Revolutions .pptx
PDF
Architecture types and enterprise applications.pdf
PDF
1 - Historical Antecedents, Social Consideration.pdf
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPT
Geologic Time for studying geology for geologist
PDF
CloudStack 4.21: First Look Webinar slides
DOCX
search engine optimization ppt fir known well about this
PPTX
Chapter 5: Probability Theory and Statistics
Getting started with AI Agents and Multi-Agent Systems
Benefits of Physical activity for teenagers.pptx
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Taming the Chaos: How to Turn Unstructured Data into Decisions
A novel scalable deep ensemble learning framework for big data classification...
Final SEM Unit 1 for mit wpu at pune .pptx
Modernising the Digital Integration Hub
Hybrid model detection and classification of lung cancer
Group 1 Presentation -Planning and Decision Making .pptx
The various Industrial Revolutions .pptx
Architecture types and enterprise applications.pdf
1 - Historical Antecedents, Social Consideration.pdf
observCloud-Native Containerability and monitoring.pptx
sustainability-14-14877-v2.pddhzftheheeeee
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Assigned Numbers - 2025 - Bluetooth® Document
Geologic Time for studying geology for geologist
CloudStack 4.21: First Look Webinar slides
search engine optimization ppt fir known well about this
Chapter 5: Probability Theory and Statistics

Quick & Easy SQL Tips

  • 1. Quick & Easy SQL TipsIke Ellishttp://www.ellisteam.netike@ellisteam.netTwitter: @ike_ellis1
  • 2. Assumptions @ YouYou are a new DBAYou don’t want to rewrite your entire application with a new schema, new DAL, or new queriesYou want to learn just enough so that your SQL apps are fast and maintainable2
  • 3. Tip #1 – Performance Problem: Check the low-hanging fruit Long-running jobsLong-running transactionsDBCC OPENTRANCheck for long-running queries/both in amount and in duration3
  • 4. Tip #2: Prettify!4http://extras.sqlservercentral.com/prettifier/prettifier.aspx
  • 5. Tip #3 – Performance Problem : Identify hardware performance bottlenecks.MemoryDisk*ProcessorNetwork I/O*Most common bottleneck. It’s the Disk I/O, Stupid. (But it could be memory that’s causing it.)5
  • 6. Tip #4: The right way to find hardware problemsMerging PerfMon and TracingGet the Batch and Completed Events OnlyNever trace from the computer you are monitoringAlways trace to a file and then load in a table after.6
  • 7. Tip #5: Files, Files EverywhereAll need their own physical drive for space management and performanceMaster Data File (MDF)Log Files (LDF)TempDB FilesO/S/SQL FilesBAK Files7
  • 8. Tip #6: The Log FileFills sequentially, so no need for striping, mirror is fine.Don’t let it get filled up: Simple Mode or Backup.8
  • 9. Tip #7 - Good memory managementCheck for other applications running on the SQL ServerMove anti-virus (or at least make sure it wasn't scanning the SQL ports or the SQL files)Move Exchange and F&P services (cluster)Turn off unneeded servicesSQL is I/O bound, so I would turn off any network/disk intensive services (DHCP, DNS, etc)9
  • 10. Tip #8 - Quick Indexing Tricks.check for clustered indexesSELECT t.[Name] FROM sys.Indexes i JOIN sys.Tables t ON t.Object_ID = i.Object_id WHERE i.type_desc = 'HEAP' ORDER BY t.[Name]check for nonclustered indexes on foreign key columns (ID Columns)select * from sys.columns c where c.name like '%id%' and c.object_id not in ( select object_id from sys.index_columns )check for non-clustered covering indexesreads outnumber inserts/updates 5 to 10 to 110
  • 11. Tip #9 - Run the Index Tuning Wizard (DB Tuning Advisor)Run it a really long time, it is more accurate the longer it runsDon’t drop existing objectsIt’s OK to over-index11
  • 12. Tip #10 – I don’t really know the symptoms, but SQL Doctor will find the cure.IderaRed GateDB ArtisonQuest12
  • 13. Tip #11– Baseline the right wayIdera Diagnostics Manager & RedGate13
  • 14. Tip #12 – Enforce Business Rules in the DBForeign KeysUnique ConstraintsCheck Constraints14
  • 15. Tip #13 - Eliminate CursorsCursors focus on how, not why or whatCursors are expensiveCursors take up memory, which is usually a problem alreadyCursors can often be written using a set-based method15
  • 16. Easy Tip #14 - Avoid Deadlocking, BlockingIndex TuneKeep transactions shortDon’t lock when you don’t have toHit the tables in the same order (create a table order document)Minimize the use of triggers16
  • 17. Tip #15: CTE’sA named temporary result set based on a SELECT queryCommon Table ExpressionResult set can be used in SELECT, INSERT, UPDATE, or DELETE
  • 18. Advantages of common table expressions:
  • 19. Queries with derived tables become more readable
  • 20. Provide traversal of recursive hierarchiesWITH TopSales (SalesPersonID, NumSales) AS( SELECT SalesPersonID, Count(*) FROM Sales.SalesOrderHeader GROUP BY SalesPersonId )SELECT * FROM TopSales WHERE SalesPersonID IS NOT NULLORDER BY NumSales DESC
  • 21. Tip #16: apply operatorright parameter can be a table, but meant for tvfcross apply does inner joinno output for row when udf produces no outputudf can get its parameters from left inputouter apply does left outer joinall rows from left input returnedmay have nulls for columns returned by udf
  • 22. Tip #17: temptables vs. table variablestable variables
  • 25. designed for smaller number of rows where scans are cheaper than seeks
  • 28. prefer to use with small number of rows
  • 31. can be shared over sessions and scopes
  • 32. can participate in transactions
  • 34. can trigger frequent recompiles
  • 36. prefer to use when you have more rows
  • 37. buffering data locallyTip #18: where exists vs. where inprior to sql server 2000, exists was preferred over innow they generate the same query planselect salesPersonIDfrom sales.salesPerson swhere exists(select managerIDfrom humanresources.employee ewhere e.managerID = s.salesPersonID)select salesPersonIDfrom sales.salesPersonwhere salesPersonID in(select managerIDfrom humanresources.employee)
  • 38. where not exists vs. where not inthe possible presence of a null generates different plans for not exists and not inselect salesPersonIDfrom sales.salesPersonswhere not exists(select managerID fromhumanresources.employee ewhere e.managerID =s.salesPersonID)select salesPersonIDfrom sales.salesPersonwhere salesPersonID not in(select managerID fromhumanresources.employee)
  • 39. Tip #19: Statistics Update22From the query plan, estimated number of rows and the actual number of rows need to equal each other. If they don’t, you might have a statistics issue.Run sp_updatestats to rectify it.
  • 40. Tip #20: Big Rows from Query PlanWhen troubleshooting, thick rows means lots of data, thin rows mean not much data. You’re probably better off following the thick rows.23
  • 41. Tip #21: Missing Index DetailsJust copy that, name the index something unique, and then run it. Remember, it doesn’t look for overlapping indexes, so check that before you run.24
  • 42. ConclusionHave a great code camp!Ike Ellisike@ellisteam.net619.922.9801Twitter: @ike_elliswww.ellisteam.net25

Editor's Notes

  • #4: DBCC OPENTRANselect s.plan_handle , t.text , sum(s.execution_count) as totalExecutionCount , sum(s.total_elapsed_time) as totalElapsedTime , sum(s.total_worker_time) as totalWorkerTime , sum(s.total_logical_reads) as totalLogicalReads , sum(s.total_logical_writes) as totalLogicalWrites from sys.dm_exec_query_stats s cross apply sys.dm_exec_sql_text(s.plan_handle) t group by s.plan_handle, t.text order by sum(s.execution_count) desc
  • #5: Case Statements, bad code, etc.
  • #15: Watch the actual execution plan for these statements:drop table dbo.t1drop table dbo.t2--create two test tablescreate table dbo.t1(c1 int, c2 int check(c2 between 10 and 20));insert into dbo.t1values (11,12);create table dbo.t2(c1 int, c2 int);goinsert into dbo.t2values(101, 102);go select t1.c1 , t2.c2 , t2.c2 from dbo.t1 join dbo.t2 on t1.c1 = t2.c2 and t1.c2 = 20;select t1.c1 , t1.c2 , t2.c2 from dbo.t1 join dbo.t2 on t1.c1 = t2.c2 and t1.c2 = 30;
  • #18: A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query.A CTE is made up of an expression name representing the CTE, an optional column list, and a query defining the CTE. After a CTE is defined, it can be referenced like a table or view can in a SELECT, INSERT, UPDATE, or DELETE statement. A CTE can also be used in a CREATE VIEW statement as part of its defining SELECT statement. A CTE can be used to: Create a recursive query.Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.Enable grouping by a column that is derived from a scalar subselect, or a function that is either not deterministic or has external access.Reference the resulting table multiple times in the same statement.ReferencesUsing Common Table Expressions: http://go.microsoft.com/fwlink/?LinkID=127330