Apply code analysis rules
You SHOULD: -
-
Specify column names when using
INSERT, even when inserting data into all columns. -
Expand the asterisk wildcard to explicitly define all columns.
-
Qualify object names. Prefix each reference to a table with its schema (but not the database name) and each column to its parent table (or alias) in
SELECTstatements. -
Terminate all statements with a semi-colon and with no leading whitespace.
-
Favour
EXISTSor table joins overINorCOUNTwhere it's sensible to do so. -
Include an
ELSEblock with eachCASEexpression. -
Prefer the use of
SCOPE_IDENTITY()to@@IDENTITY. -
Use Common Table Expressions (CTEs) instead of non-correlated subqueries. A
CTEis easier to read than a subquery and offers the same performance. -
Use functions like
ISNULL,IS NULL,ISNUMERIC,TRY_CONVERT,COALESCEand**CASTcorrectly.
You SHOULD NOT:-
-
Use
INSERT INTO<table> with anORDER BYclause. The order depends on the clustered index if one is defined. -
Use
DELETEwithout aWHEREorINNER JOINclause -
Use
UPDATEwithout aWHEREorINNER JOINclause -
Use correlated sub-queries. (The exception to this is the use of
EXISTS.) -
Define
JOINconditions in theWHEREclause. Include theJOINcondition in theONclause. -
Include
WHEREclauses inSELECTstatements1 to prevent defining Cartesian joins. -
Use
ISNULLin aWHEREorJOINclause. Expressions need to useIS NOT NULLand theCOALESCEfunction to handleNULLvalues appropriately. -
Use comparison operators against a
NULLvalue. -
Use
DISTINCTwhere it is not required. Use aGROUP BYclause where possible and checkJOINconditions to eliminate duplicate rows. -
Use wildcards (such as %) at the start of
LIKEinWHEREclauses. Indexes cannot support wildcard queries at the start of aLIKEexpression. -
Reference columns that do not have indexes in a
WHERE,JOINorORDER BYclause. -
Use system or user-defined scalar functions in a
WHEREorJOINclause. Functions are evaluated for each row in the result set. Any indexes cannot be used on the column the function is being performed on. -
Use the
NOLOCKhint. It's safer to specify the correct isolation level instead.
Practical tips
Use Redgate SQL Prompt to help you implement code analysis rules. See Follow our code layout rules
Further reading and information
Code Analysis - Product Documentation (re d-gate.com)
How to Get NULLs Horribly Wrong in SQL Server - Simple Talk (red-gate.com)
SQL Server Common Table Expression (CTE) Basics - Simple Talk (red -gate.com)
-
If you need to perform a Cartesian join, use the newer syntax
CROSS APPLY-- most likely when shredding XML/JSON data. ↩