Quick & Easy SQL TipsIke Ellisike@ellisteam.net@ellisteam11
Assumptions @ YouYou aren’t a DBAYou don’t want to be a 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
PDF
Tibco-Exception Handling
PPTX
Top 10 tips for software development management
PDF
Taxand Netherlands may grant 30% expatriate rulings
PPT
GPS/GPRS SIGAL presentation by Endri DHASKALI
PDF
Artpark impuls
PPT
PDF
Supply of labour in the netherlands
Quick & Easy SQL Tips
Tibco-Exception Handling
Top 10 tips for software development management
Taxand Netherlands may grant 30% expatriate rulings
GPS/GPRS SIGAL presentation by Endri DHASKALI
Artpark impuls
Supply of labour in the netherlands

Viewers also liked (10)

PDF
Eloqua Benchmark Report
PPT
2e data models
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
PPTX
11 Goals of High Functioning SQL Developers
PDF
Employment law & Employee tax in the Netherlands
Eloqua Benchmark Report
2e data models
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
11 Goals of High Functioning SQL Developers
Employment law & Employee tax in the Netherlands
Ad

Similar to Quick & Easy SQL Tips (20)

PPTX
SQL Server Tips & Tricks
PPTX
Tips & Tricks SQL in the City Seattle 2014
PPTX
SQL Pass Architecture SQL Tips & Tricks
PDF
Tips for Database Performance
PPTX
02 database oprimization - improving sql performance - ent-db
PPTX
T sql performance guidelines for better db stress powers
PPTX
T sql performance guidelines for better db stress powers
PDF
Execution Plans in practice - how to make SQL Server queries faster - Damian ...
PPTX
T sql performance guidelines for better db stress powers
PPTX
My Database Skills Killed the Server
PDF
10 sql tips
PDF
Sql db optimization
PDF
SQL Database Performance Tuning for Developers
PPTX
Tuning Slow Running SQLs in PostgreSQL
PPTX
Database Performance Tuning
PPTX
SQL Server 2012 Best Practices
PPTX
05_DP_300T00A_Optimize.pptx
PPT
Top 10 Oracle SQL tuning tips
PPTX
My Query is slow, now what?
PPTX
Sql server infernals
SQL Server Tips & Tricks
Tips & Tricks SQL in the City Seattle 2014
SQL Pass Architecture SQL Tips & Tricks
Tips for Database Performance
02 database oprimization - improving sql performance - ent-db
T sql performance guidelines for better db stress powers
T sql performance guidelines for better db stress powers
Execution Plans in practice - how to make SQL Server queries faster - Damian ...
T sql performance guidelines for better db stress powers
My Database Skills Killed the Server
10 sql tips
Sql db optimization
SQL Database Performance Tuning for Developers
Tuning Slow Running SQLs in PostgreSQL
Database Performance Tuning
SQL Server 2012 Best Practices
05_DP_300T00A_Optimize.pptx
Top 10 Oracle SQL tuning tips
My Query is slow, now what?
Sql server infernals
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)

PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PDF
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PPTX
The various Industrial Revolutions .pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
STKI Israel Market Study 2025 version august
PPT
What is a Computer? Input Devices /output devices
PPTX
Benefits of Physical activity for teenagers.pptx
PPTX
2018-HIPAA-Renewal-Training for executives
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
Architecture types and enterprise applications.pdf
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Hindi spoken digit analysis for native and non-native speakers
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Consumable AI The What, Why & How for Small Teams.pdf
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
The various Industrial Revolutions .pptx
Enhancing emotion recognition model for a student engagement use case through...
STKI Israel Market Study 2025 version august
What is a Computer? Input Devices /output devices
Benefits of Physical activity for teenagers.pptx
2018-HIPAA-Renewal-Training for executives
sustainability-14-14877-v2.pddhzftheheeeee
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
Architecture types and enterprise applications.pdf
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Final SEM Unit 1 for mit wpu at pune .pptx
The influence of sentiment analysis in enhancing early warning system model f...
Developing a website for English-speaking practice to English as a foreign la...
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...

Quick & Easy SQL Tips

  • 1. Quick & Easy SQL TipsIke Ellisike@ellisteam.net@ellisteam11
  • 2. Assumptions @ YouYou aren’t a DBAYou don’t want to be a 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.9801@ellisteam1www.ellisteam.netEllisteam.blogspot.comDevelopMentor SQL Course is coming!25

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