T-SQL : Bad Habits to Kick Aaron Bertrand SQL Sentry, Inc.

Slides:



Advertisements
Similar presentations
Ashley Ohmann June 20, * What is Custom SQL? * What can I do with it? * Join conditions * Unions and Self Joins * Ranks * Derived Tables.
Advertisements

Displaying Data from Multiple Tables
Aaron Bertrand SQL Sentry, Senior Kevin Kline SQL Sentry, Dir of Engineering
Aaron Bertrand SQL Sentry, Senior Kevin Kline SQL Sentry, Dir of Engineering
Murach's MySQL, C3© 2012, Mike Murach & Associates, Inc.Slide 1.
Module 7 Designing Queries for Optimal Performance.
Computer Science 1620 Loops.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
Introduction to Structured Query Language (SQL)
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Introduction to SQL Structured Query Language Martin Egerhill.
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 8 Advanced SQL.
Version 1.0. MCAD MCSD MCPD Enterprise SQL MCTS MCT Software/Web Development Consultant Cryptography/Digital Signature Consultant SQL Server 2005/2008R2/2012.
Sofia, Bulgaria | 9-10 October TSQL Enhancements in SQL Server 2005 Stephen Forte CTO, Corzen Inc Microsoft Regional Director NY/NJ (USA) Stephen Forte.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Introduction to Databases Chapter 7: Data Access and Manipulation.
SQL Server 2008 for Developers John
Stored Procedures, Transactions, and Error-Handling
SQL Joins Oracle and ANSI Standard SQL Lecture 6.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
1 Definition of a subquery Nested subqueries Correlated subqueries The ISNULL function Derived tables The EXISTS operator Mixing data types: CAST & CONVERT.
For Loops (ProjFor1, ProjFor2, ProjFor3, ProjFor4, textbox, textbox1) Please use speaker notes for additional information!
04 | Grouping and Aggregating Data Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
劉 志 俊 (Chih-Chin Liu) 中華大學 資訊工程系 October 2001 Chap 9 SQL (III): Advanced Queries.
Joins, views, and subqueries CMSC 461 Michael Wilson.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
1 Chapter 10 Joins and Subqueries. 2 Joins & Subqueries Joins – Methods to combine data from multiple tables – Optimizer information can be limited based.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
1 PL\SQL Dev Templates. 2 TEMPLATE DEFINITION Whenever you create a new program unit, its initial contents are based upon a template which contains pre-defined.
SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc. Slide 1.
LINQ to DATABASE-2.  Creating the BooksDataContext  The code combines data from the three tables in the Books database and displays the relationships.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
DML Statements contd.. SQL Server CURSORS Cursor is used in handling results of select query for data calculations Cursors are used as buffered.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
1 CS 430 Database Theory Winter 2005 Lecture 13: SQL DML - Modifying Data.
Thinking in Sets and SQL Query Logical Processing.
6/13/2015 Visit the Sponsor tables to enter their end of day raffles. Turn in your completed Event Evaluation form at the end of the day in the Registration.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
Scott Fallen Sales Engineer, SQL Sentry Blog: scottfallen.blogspot.com.
Common SQL Programming Mistakes. Sponsors Who am I?? Kevin G. Boles SQL Server Consultant “The Wolf” for the Relational Engine Indicium Resources, Inc.
BTM 382 Database Management Chapter 8 Advanced SQL Chitu Okoli Associate Professor in Business Technology Management John Molson School of Business, Concordia.
High Performance Functions SQLBits VI. Going backwards is faster than going forwards.
T-SQL: Bad Habits… …and Best Practices Aaron Bertrand SQL Sentry,
IFS180 Intro. to Data Management Chapter 10 - Unions.
More SQL: Complex Queries,
Tuning Transact-SQL Queries
Query Optimization Techniques
392-"JOIN" us on DataServers Journey
Stored Procedures – Facts and Myths
02 | Advanced SELECT Statements
Database Systems: Design, Implementation, and Management Tenth Edition
Dynamic SQL Writing Efficient Queries on the Fly
David M. Kroenke and David J
TSQL Coding Techniques
The Killing Cursors Cyndi Johnson
Using Table Expressions
More SQL: Complex Queries, Triggers, Views, and Schema Modification
The Hidden Mysteries of Common Table Expressions
SQL Subquery.
Cyndi Johnson Senior Software Engineer at AdvancedMD Killing Cursors.
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Database Systems: Design, Implementation, and Management Tenth Edition
Cyndi Johnson Senior Software Engineer at AdvancedMD Killing Cursors.
Displaying Data from Multiple Tables
Manipulating Data Lesson 3.
Improving the Performance of Functions
Presentation transcript:

T-SQL : Bad Habits to Kick Aaron Bertrand SQL Sentry, Inc.

Who is Aaron Bertrand? Senior Consultant at SQL Sentry Microsoft MVP since Blog: Twitter: 2 AD-204 | T-SQL : Bad Habits to Kick

Agenda 12 simple slides with one common goal: Improving at least one bad habit. These are mostly just opinions; No right or wrong answer. 3 AD-204 | T-SQL : Bad Habits to Kick

1. SELECT * / omitting column list Needless lookups/scans, I/O, network load Predictability / change management Today’s tools negate carpal tunnel excuse AD-204 | T-SQL : Bad Habits to Kick 4

2. Declaring variables without length Guess the results: VARCHAR = 'foo'; SELECT CONVERT(VARCHAR, 'foo'); AD-204 | T-SQL : Bad Habits to Kick 5

3. Choosing the wrong data type Don’t choose: String/numeric types for date/time data TIME in place of an interval DATETIME if DATE/SMALLDATETIME will do NVARCHAR(MAX) for URL, zip, phone, e- mail VARCHAR for proper names AD-204 | T-SQL : Bad Habits to Kick 6

4. Not using schema prefix Being explicit prevents confusion or worse Object resolution works harder without it Leads to multiple cached plans for same query Even if all objects belong to dbo, specify Eventually, you or 3 rd party will use schemas AD-204 | T-SQL : Bad Habits to Kick 7

5. Using inconsistent naming conventions Examples I’ve seen in a single system: GetCustomerDetails Customer_Update Create_Customer Styles vary – even your own changes over time The convention you choose isn’t the point AD-204 | T-SQL : Bad Habits to Kick 8

6. Using loops to populate large tables WHILE…INSERT 1,000,000 times is log intensive Much better constructs: Numbers table Recursive CTEs Cross joins from catalog views If you must use a loop Batch by committing every rows AD-204 | T-SQL : Bad Habits to Kick 9

7. Mishandling date range queries Avoid non-sargeable clauses that come from: YEAR() and other functions against columns CONVERT() on both sides of clauses BETWEEN is ok for DATE but not DATETIME Do not try to calculate “end of today”: Use >= today AND < tomorrow AD-204 | T-SQL : Bad Habits to Kick 10

8. Using SELECT/RETURN vs. OUTPUT In general… SELECT is for multiple rows/columns OUTPUT is for limited number of scalar values RETURN is for status/error codes, NOT DATA! AD-204 | T-SQL : Bad Habits to Kick 11

9. Using old-style joins Do not use old-style inner joins (FROM x, y, z) Easy to accidentally derive Cartesian product Not deprecated, but not recommended either Do not use old-style outer joins (*= / =*) Deprecated syntax Unpredictable results AD-204 | T-SQL : Bad Habits to Kick 12

10. Using cursors with default options Cursors are often bad, but not evil Avoid heavy locking behavior - my syntax: DECLARE c CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR … AD-204 | T-SQL : Bad Habits to Kick 13

11. Using ORDER BY [ordinal] Underlying structure/query changes OK habit for ad hoc stuff, not production code Keystrokes are only downside to being explicit IntelliSense / 3 rd party tools negate this anyway AD-204 | T-SQL : Bad Habits to Kick 14

12. Assuming ORDER without ORDER BY Popular myth: “table has natural order” Without ORDER BY, there is no guaranteed order TOP unfortunately has two meanings: 1.Which rows to include 2.How to order them To separate, use a CTE or nested subquery AD-204 | T-SQL : Bad Habits to Kick 15

13 -> …plenty of others… Search for “bad habits to kick” at AD-204 | T-SQL : Bad Habits to Kick 16 ∞