Factsheet SQL Server
Factsheet SQL Server
com
SQL Server developers factsheet
C
Data types String Functions (T-SQL) Date and Time functions (T-SQL)
type Size Range (from/to) ASCII (character) : Returns the ASCII code value of the leftmost character of character DATEADD (datepart , number, date): Returns a new datetime value based on adding an
CHAR (int) : Converts the integer ASCII code int to a character interval to the specified date.
Exact numerics CHARINDEX (search, expression, [start]) : Returns starting position (int) of first occurrence of the string search DATEDIFF (datepart , number, date): Returns the number of date and time boundaries
within table or string expression starting from position start crossed between two specified dates.
N
bigint 8 bytes -9,223,372,036,854,775,808 DATENAME (datepart , date): Returns a character string representing the specified datepart
9,223,372,036,854,775,807 DIFFERENCE (expression1, expression2) : Returns the difference between the SOUNDEX values of the two
character expressions as an integer of the specified date.
bit 1 bit 0 to 1
LEFT (expression, int): Returns part of character string expression starting at int characters from the left. DATEPART (datepart , date): Returns an integer that represents the specified datepart of the
decimal -10^38 +1 to 10^38 –1 LEN (expression) : Returns the number of characters of the string expression, excluding trailing blanks. specified date.
LOWER (expression) : Returns character expression after converting uppercase string to lowercase DAY (date): Returns an integer representing the day datepart of the specified date.
int 4 bytes -2,147,483,648 to
LTRIM (expression) : Returns a character string after removing all leading blanks. GETDATE : Returns the current system date and time.
2,147,483,647
NCHAR (int) : Returns the Unicode character with the given integer code. MONTH (date): Returns an integer that represents the month part of a specified date.
money 8 bytes -922,337,203,685,477.5808 YEAR (date): Returns an integer that represents the year part of a specified date.
+922,337,203,685,477.5807 PATINDEX ('%pattern%', expression) : Returns starting position of the first occurrence of a pattern in a specified
numeric 19 bytes -10^38 +1 to 10^38 –1 expression, or zeros if the pattern is not found, on all valid text and character data types.
CO
REPLACE (expression1,expression2,expression3) : Replaces all occurrences of the second given string
smallint 2 bytes -32,768 to 32,767 expression in the first string expression with a third expression. Dateparts Cursor Functions (T-SQL)
QUOTENAME (character_string[, quote_character]) : Returns a Unicode string with the delimiters added to make
smallmoney 4 bytes -214,748.3648 to
+214,748.3647
the input string a valid Microsoft® SQL Server™ delimited identifier. Datepart Abbreviations @@CURSOR_ROWS
tinyint 1 byte 0 to 255 REPLICATE (expression, int) : Repeats a character expression a specified number of times Returns the number of qualifying rows currently
REVERSE (expression) : Returns the reverse of a character expression. year yy, yyyy in the last cursor opened on the connection.
Approximate numerics RIGHT (expression, int): Returns part of character string expression starting at int characters from the right. quarter qq, q
month mm, m @@FETCH_STATUS
RTRIM (expression) : Returns a character string after removing all trailing blanks. Returns the status of the last cursor FETCH
float 8 bytes -1.79E + 308 to dayofyear dy, y
SOUNDEX (expression) : Returns a four-character (SOUNDEX) code. day dd, d statement issued against any cursor currently
1.79E + 308 SPACE (int) : Returns a string of int spaces.
real 4 bytes -3.40E + 38 to week wk, ww opened by the connection.
3.40E + 38
STR (float_expression[, length[, decimal]]) : Returns character data converted from numeric data. weekday dd CURSOR_STATUS
Dates STUFF (expression1, start, length, expression2 ) : Deletes a specified length (length) of characters from hour hh A scalar function that allows the caller of a
expression1 and inserts another set (expression2) at a specified starting point (start) of expression1. minute mi, n
second ss, s stored procedure to determine whether or not
datetime 8 bytes Jan 1, 1753 to Dec 31, 9999 SUBSTRING (expression, start, length) : Returns part of character, binary, text expression or image expression the procedure has returned a cursor and result
millisecond ms
starting from position start with length length set for a given parameter.
smalldatetime 4 bytes Jan 1, 1900 to Jun 6, 2079 UNICODE (char) : Returns the Unicode int value for the first character of char.
UPPER (expression) : Returns a character expression after converting lowercase string to uppercase.
C
Execution Plan Icons (2005)
SELECT (T-SQL) ALTER TABLE (T-SQL) Checklist for fast queries
The full syntax of the SELECT statement is complex, but the Modifies a table definition by altering, adding or dropping columns and
main clauses can be summarized as: constraints, or by disabling or enabling constraints and triggers. The full syntax Avoid non-sargable WHERE-clauses. If possible rewrite them to sargable Arithmetic Nonclustered
is complex, but the main clauses can be summarized as: ones Expression Index Scan
SELECT [DISTINCT] [{TOP int | TOP int PERCENT}]
columns ALTER TABLE table In the WHERE-clause use the least likely true AND expression first Assert
Nonclustered
N
[INTO new_table] {[ALTER COLUMN column_name {new_data_type Avoid using OR in the WHERE-clause if not all colums have an index Index Seek
FROM table_source [(precision[, scale] )][NULL | NOT NULL] Avoid using UNION if UNION ALL also does the trick Bitmap
Nonclustered
Avoid using UNION of two subsets from the same table. Instead use OR in Index Spool
[[INNER |{{ LEFT | RIGHT | FULL }[ OUTER ]}] JOIN | {ADD | DROP} ROWGUIDCOL}] | ADD
the WHERE-clause Bookmark Nonclustered
table_source2 ON table_source.primairy_key = {[ <column_definition> ]| column_name AS Lookup Index Update
table_source2.foreign_key][,...n] computed_column_expression}[,...n] Avoid using SELECT * FROM when only a few columns are needed. Try
Clustered Online Index
[WHERE search_condition] | [WITH CHECK | WITH NOCHECK] ADD to specify each column Index Delete Insert
[GROUP BY group_by_expression] { <table_constraint> }[,...n] | DROP {[CONSTRAINT] Avoid using COUNT(*) to check the existence of a record. Instead use
Clustered Parameter Table
[HAVING search_condition] constraint_name EXIST Index Insert Scan
[ORDER BY order_expression [ASC | DESC]] | COLUMN column}[,...n] | {CHECK | NOCHECK} Always try to use a WHERE-clause in your query to narrow the results Clustered
Try to use the best performing operator as possible Remote Delete
CO
CONSTRAINT Index Scan
DISTINCT : Specifies that only unique rows can appear in {ALL | constraint_name[,...n]} | {ENABLE | DISABLE} Avoid using NOT IN. Instead use EXIST, NOT EXIST, IN or LEFT OUTER Clustered
JOIN with a check for a NULL condition Remote Insert
the result set. Null values are considered equal for the TRIGGER {ALL | trigger_name[,...n]}} Index Seek
purposes of the DISTINCT keyword Avoid using IN when EXISTS is also possible Clustered
Remote Query
TOP n [PERCENT] : Specifies that the first n rows are to Avoid using IN when BETWEEN is also possible Index Update
be output from the query result set. If PERCENT is also In case using IN try to order the list of values so that the most frequently
specified, the first n percent are output. Creating / Altering other objects found values are placed first
Collapse Remote Scan
INTO new_table: Creates a new table and inserts the Avoid using SUBSTRING in the WHERE-clause. If possible use LIKE Compute
Remote Update
resulting rows from the query into it Stored procedures: instead Scalar
CREATE PROCEDURE <name> AS <sql_statement> Sometimes consider rewriting a query using a OR to multiple queries Concatenatio
GROUP BY : Specifies the groups into which output rows ALTER PROCEDURE <name> AS <sql_statement> n
RID Lookup
are to be placed and, if aggregate functions are included in combined with a UNION ALL
DROP PROCEDURE <name> Don't use ORDER BY if you don't really need it Constant Row Count
the SELECT clause <select list>, calculates a summary Scan Spool
value for each group. Keep the width and/or number of sorted columns to the minimum
Indexes: Keep the number of rows to be sorted to a minimum Delete Segment
HAVING : Specifies a search condition for a group or an CREATE INDEX <name> ON <table> (<column>)
aggregate When sorting a specific column often conside making that column a
CREATE UNIQUE CLUSTERED INDEX <name> ON <table>.<column> Deleted Scan Sequence
clustered index
DROP INDEX <table>.<name>
In case of using HAVING try to minimize the amount of rows using a Sequence
WHERE clause Eager Spool
Project
UPDATE (T-SQL) Views:
CREATE VIEW <name> [(<Column1>,…)] AS <SELECT_statement> In case using LIKE on CHAR of VARCHAR colums quite often consider
Filter Sort
The full syntax of the UPDATE statement is complex, but the ALTER VIEW <name> [(<Column1>,…)] AS <SELECT_statement> using the full-text search option
main clauses can be summarized as: DROP VIEW <name> In case using GROUP BY without an aggregate function try using
Hash Match Split
DISTINCT instead
UPDATE table_name Avoid using variables in a WHERE clause in case the query is located in a Hash Match
SET column_name = {expression | DEFAULT | NULL} Triggers: Spool
batch-file Root
[,...n] CREATE TRIGGER <name> ON <table> FOR INSERT, UPDATE, Hash Match Stream
[WHERE <search_condition>] DELETE AS <sql_statement> Team Aggregate
ALTER TRIGGER <name> ON <table> FOR UPDATE, DELETE AS
<sql_statement> Checklist for creating indexes Insert Switch
DROP TRIGGER <name> Inserted
DELETE (T-SQL) Create indexes on the highly selective colums that are used in the Scan
Table Delete
The full syntax of the DELETE statement is complex, but the Functions: WHERE-clause Iterator
main clauses can be summarized as: Table Insert
CREATE FUNCTION <name> RETURNS <data_type> AS Create indexes on all columns that are used in the WHERE clause in case Catchall
RETURN <sql_expression> OR is used
DELETE [FROM] table_name Lazy Spool Table Scan
CREATE FUNCTION <name> RETURNS <data_type> AS BEGIN Create at least a clustered index on every table. Generally use the column
[WHERE <search_condition>] <sql_statement> RETURN <sql_expression> END Log Row
that monotonically increases Scan
Table Spool
ALTER FUNCTION <name> RETURNS <data_type> AS Create indexes columns that are frequently accessed by WHERE,
RETURN <sql_expression> Merge
ORDER BY, GROUP BY, TOP and DISTINCT Interval
Table Update
DROP FUNCTION <name>
INSERT (T-SQL) Only add indexes that will be used frquently
Merge Join
Table-valued
INSERT adds a new row to an existing table or a view. Avoid adding too much indexes on dynamic tables (subject to many Function
The full syntax of the INSERT statement is complex, but the INSERTs, UPDATEs or DELETEs) Nested
Sargability For static tables use a FILLFACTOR and PAD_INDEX of 100. For Loops
Top
main clauses can be summarized as: SQL Server only uses indexes for colums used in sargable dynamic tables use a lower FILLFACTOR Nonclustered
expressions. Green = fastest expression. To identify additional indexes use the SS Profiler Create Trace Wizard and UDX
INSERT [INTO] table_name Index Delete
[(column_list)] Sargable Non-sargable trace "Identify Scans of Large Tables" Nonclustered
VALUES ({ DEFAULT | NULL | expression }[,...n]) = IS NULL Avoid adding indexes twice Index Insert
Update
> <>
Factsheet by Red: Temporary tables/spools
< != Xander Zelders
CREATE TABLE (T-SQL) Try rewriting the query
>= !> http://www.dotnet4all.com Red: Index or table scans
Creates a new table. The full syntax is complex, but the main <= !< Create additional or better indexes
clauses can be summarized as:
EXIST NOT Connectionstring Orange: Bookmark lookups
CREATE TABLE IS NOT EXIST Consider changing the clustered index
[{database_name.[owner].| owner.}] table_name SQL Server, Standard security: Consider using a covering index
IN NOT IN Provider=sqloledb;Data Source=myServerAddress; Initial
({<column_definition> | column_name AS Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Consider limiting the number of
BETWEEN NOT LIKE columns in the SELECT statement.
computed_column_expression | <table_constraint>} SQL Server, Trusted connection: Provider=sqloledb;Data Source=myServerAddress; Initial
[,...n]) LIKE 'abc%' LIKE '%abc'
Catalog=myDataBase;Integrated Security=SSPI;
Yellow: Filter and/or sort
LIKE '%abc%' SQL Server 2005, Standard security: Driver={SQL Native Client};
Consider removing any functions in the
function on column Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
WHERE clause
Consider not using views in your code
column1 = column1 SQL Server 2005, Trusted connection: Driver={SQL Native Client}; Consider using additional indexes
column1 = column2 Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes; Consider not to sort