0
Quick & Easy SQL Tips<br />Ike Ellis<br />http://www.ellisteam.net<br />ike@ellisteam.net<br />Twitter: @ike_ellis<br />1<...
Assumptions @ You<br />You are a new DBA<br />You don’t want to rewrite your entire application with a new schema, new DAL...
Tip #1 – Performance Problem: Check the low-hanging fruit <br />Long-running jobs<br />Long-running transactions<br />DBCC...
Tip #2:  Prettify!<br />4<br />http://extras.sqlservercentral.com/prettifier/prettifier.aspx<br />
Tip #3 – Performance Problem : Identify hardware performance bottlenecks.<br />Memory<br />Disk*<br />Processor<br />Netwo...
Tip #4: The right way to find hardware problems<br />Merging PerfMon and Tracing<br />Get the Batch and Completed Events O...
Tip #5: Files, Files Everywhere<br />All need their own physical drive for space management and performance<br />Master Da...
Tip #6: The Log File<br />Fills sequentially, so no need for striping, mirror is fine.<br />Don’t let it get filled up: Si...
Tip #7 - Good memory management<br />Check for other applications running on the SQL Server<br />Move anti-virus (or at le...
Tip #8 - Quick Indexing Tricks.<br />check for clustered indexes<br />SELECT t.[Name] FROM sys.Indexes i <br />	JOIN sys.T...
Tip #9 - Run the Index Tuning Wizard (DB Tuning Advisor)<br />Run it a really long time, it is more accurate the longer it...
Tip #10 – I don’t really know the symptoms, but SQL Doctor will find the cure.<br />Idera<br />Red Gate<br />DB Artison<br...
Tip #11– Baseline the right way<br />Idera Diagnostics Manager & RedGate<br />13<br />
Tip #12 – Enforce Business Rules in the DB<br />Foreign Keys<br />Unique Constraints<br />Check Constraints<br />14<br />
Tip #13 - Eliminate Cursors<br />Cursors focus on how, not why or what<br />Cursors are expensive<br />Cursors take up mem...
Easy Tip #14 - Avoid Deadlocking, Blocking<br />Index Tune<br />Keep transactions short<br />Don’t lock when you don’t hav...
Tip #15: CTE’s<br />A named temporary result set based on a SELECT query<br />Common Table Expression<br /><ul><li>Result ...
Advantages of common table expressions:
Queries with derived tables become more readable
Provide traversal of recursive hierarchies</li></ul>WITH TopSales (SalesPersonID, NumSales) AS<br />( SELECT SalesPersonID...
Tip #16: apply operator<br />right parameter can be a table, but meant for tvf<br />cross apply does inner join<br />no ou...
Tip #17: temptables vs. table variables<br /><ul><li>table variables
private to batch
avoids transaction affects
designed for smaller number of rows where scans are cheaper than seeks
Upcoming SlideShare
Loading in...5
×

Quick & Easy SQL Tips

929

Published on

SQL Tips for the YouTube generation. 20 unrelated and independant tips, one right after another to speed up your database application without a ton of work.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
929
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
14
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • 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
  • Case Statements, bad code, etc.
  • 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;
  • 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
  • Transcript of "Quick & Easy SQL Tips"

    1. 1. Quick & Easy SQL Tips<br />Ike Ellis<br />http://www.ellisteam.net<br />ike@ellisteam.net<br />Twitter: @ike_ellis<br />1<br />
    2. 2. Assumptions @ You<br />You are a new DBA<br />You don’t want to rewrite your entire application with a new schema, new DAL, or new queries<br />You want to learn just enough so that your SQL apps are fast and maintainable<br />2<br />
    3. 3. Tip #1 – Performance Problem: Check the low-hanging fruit <br />Long-running jobs<br />Long-running transactions<br />DBCC OPENTRAN<br />Check for long-running queries/both in amount and in duration<br />3<br />
    4. 4. Tip #2: Prettify!<br />4<br />http://extras.sqlservercentral.com/prettifier/prettifier.aspx<br />
    5. 5. Tip #3 – Performance Problem : Identify hardware performance bottlenecks.<br />Memory<br />Disk*<br />Processor<br />Network I/O<br />*Most common bottleneck. It’s the Disk I/O, Stupid. (But it could be memory that’s causing it.)<br />5<br />
    6. 6. Tip #4: The right way to find hardware problems<br />Merging PerfMon and Tracing<br />Get the Batch and Completed Events Only<br />Never trace from the computer you are monitoring<br />Always trace to a file and then load in a table after.<br />6<br />
    7. 7. Tip #5: Files, Files Everywhere<br />All need their own physical drive for space management and performance<br />Master Data File (MDF)<br />Log Files (LDF)<br />TempDB Files<br />O/S/SQL Files<br />BAK Files<br />7<br />
    8. 8. Tip #6: The Log File<br />Fills sequentially, so no need for striping, mirror is fine.<br />Don’t let it get filled up: Simple Mode or Backup.<br />8<br />
    9. 9. Tip #7 - Good memory management<br />Check for other applications running on the SQL Server<br />Move anti-virus (or at least make sure it wasn't scanning the SQL ports or the SQL files)<br />Move Exchange and F&P services (cluster)<br />Turn off unneeded services<br />SQL is I/O bound, so I would turn off any network/disk intensive services (DHCP, DNS, etc)<br />9<br />
    10. 10. Tip #8 - Quick Indexing Tricks.<br />check for clustered indexes<br />SELECT t.[Name] FROM sys.Indexes i <br /> JOIN sys.Tables t <br /> ON t.Object_ID = i.Object_id<br /> WHERE i.type_desc = 'HEAP'<br /> ORDER BY t.[Name]<br />check for nonclustered indexes on foreign key columns (ID Columns)<br />select * from sys.columns c <br /> where c.name like '%id%'<br /> and c.object_id not in <br /> (<br /> select object_id from sys.index_columns<br /> )<br />check for non-clustered covering indexes<br />reads outnumber inserts/updates 5 to 10 to 1<br />10<br />
    11. 11. Tip #9 - Run the Index Tuning Wizard (DB Tuning Advisor)<br />Run it a really long time, it is more accurate the longer it runs<br />Don’t drop existing objects<br />It’s OK to over-index<br />11<br />
    12. 12. Tip #10 – I don’t really know the symptoms, but SQL Doctor will find the cure.<br />Idera<br />Red Gate<br />DB Artison<br />Quest<br />12<br />
    13. 13. Tip #11– Baseline the right way<br />Idera Diagnostics Manager & RedGate<br />13<br />
    14. 14. Tip #12 – Enforce Business Rules in the DB<br />Foreign Keys<br />Unique Constraints<br />Check Constraints<br />14<br />
    15. 15. Tip #13 - Eliminate Cursors<br />Cursors focus on how, not why or what<br />Cursors are expensive<br />Cursors take up memory, which is usually a problem already<br />Cursors can often be written using a set-based method<br />15<br />
    16. 16. Easy Tip #14 - Avoid Deadlocking, Blocking<br />Index Tune<br />Keep transactions short<br />Don’t lock when you don’t have to<br />Hit the tables in the same order (create a table order document)<br />Minimize the use of triggers<br />16<br />
    17. 17. Tip #15: CTE’s<br />A named temporary result set based on a SELECT query<br />Common Table Expression<br /><ul><li>Result set can be used in SELECT, INSERT, UPDATE, or DELETE
    18. 18. Advantages of common table expressions:
    19. 19. Queries with derived tables become more readable
    20. 20. Provide traversal of recursive hierarchies</li></ul>WITH TopSales (SalesPersonID, NumSales) AS<br />( SELECT SalesPersonID, Count(*) <br /> FROM Sales.SalesOrderHeader GROUP BY SalesPersonId )<br />SELECT * FROM TopSales <br />WHERE SalesPersonID IS NOT NULL<br />ORDER BY NumSales DESC<br />
    21. 21. Tip #16: apply operator<br />right parameter can be a table, but meant for tvf<br />cross apply does inner join<br />no output for row when udf produces no output<br />udf can get its parameters from left input<br />outer apply does left outer join<br />all rows from left input returned<br />may have nulls for columns returned by udf<br />
    22. 22. Tip #17: temptables vs. table variables<br /><ul><li>table variables
    23. 23. private to batch
    24. 24. avoids transaction affects
    25. 25. designed for smaller number of rows where scans are cheaper than seeks
    26. 26. limited indexing
    27. 27. static nature reduces recompiles
    28. 28. prefer to use with small number of rows
    29. 29. temporary tables
    30. 30. persists for session
    31. 31. can be shared over sessions and scopes
    32. 32. can participate in transactions
    33. 33. can be indexed
    34. 34. can trigger frequent recompiles
    35. 35. get statistics
    36. 36. prefer to use when you have more rows
    37. 37. buffering data locally</li></li></ul><li>Tip #18: where exists vs. where in<br />prior to sql server 2000, exists was preferred over in<br />now they generate the same query plan<br />select salesPersonID<br />from sales.salesPerson s<br />where exists(<br />select managerID<br />from humanresources.employee e<br />where e.managerID = s.salesPersonID)<br />select salesPersonID<br />from sales.salesPerson<br />where salesPersonID in<br />(select managerID<br />from humanresources.employee)<br />
    38. 38. where not exists vs. where not in<br />the possible presence of a null generates different plans for not exists and not in<br />select salesPersonID<br />from sales.salesPersons<br />where not exists(<br />select managerID from<br />humanresources.employee e<br />where e.managerID =<br />s.salesPersonID)<br />select salesPersonID<br />from sales.salesPerson<br />where salesPersonID not in<br />(select managerID from<br />humanresources.employee)<br />
    39. 39. Tip #19: Statistics Update<br />22<br />From 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.<br />Run sp_updatestats to rectify it.<br />
    40. 40. Tip #20: Big Rows from Query Plan<br />When troubleshooting, thick rows means lots of data, thin rows mean not much data. You’re probably better off following the thick rows.<br />23<br />
    41. 41. Tip #21: Missing Index Details<br />Just copy that, name the index something unique, and then run it. <br />Remember, it doesn’t look for overlapping indexes, so check that before you run.<br />24<br />
    42. 42. Conclusion<br />Have a great code camp!<br />Ike Ellis<br />ike@ellisteam.net<br />619.922.9801<br />Twitter: @ike_ellis<br />www.ellisteam.net<br />25<br />
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×