Thursday, March 5, 2015

SQL Server 2012 Data types

DATATYPEMINMAXSTORAGETYPENOTES
Bigint-2^632^63-18 bytesExact
Int-2,147,483,6482,147,483,6474 bytesExact
Smallint-32,76832,7672 bytesExact
Tinyint02551 bytesExact
Bit011 to 8 bit columns in the same table requires a total of 1 byte, 9 to 16 bits = 2 bytes, etc...Exact
Decimal-10^38+110^38–1Precision 1-9 = 5 bytes, precision 10-19 = 9 bytes, precision 20-28 = 13 bytes, precision 29-38 = 17 bytesExactThe Decimal and the Numeric data type is exactly the same. Precision is the total number of digits. Scale is the number of decimals. For both the minimum is 1 and the maximum is 38.
Numericsame as Decimalsame as Decimalsame as DecimalExact
Money-2^63 / 100002^63-1 / 100008 bytesExact
Smallmoney-214,748.3648214,748.36474 bytesExact
Float-1.79E + 3081.79E + 3084 bytes when precision is less than 25 and 8 bytes when precision is 25 through 53ApproxPrecision is specified from 1 to 53.
Real-3.40E + 383.40E + 384 bytesApproxPrecision is fixed to 7.
Datetime1753-01-01 00:00:00.0009999-12-31 23:59:59.9978 bytesDatetimeIf you are running SQL Server 2008 or later and need milliseconds precision, use datetime2(3) instead to save 1 byte.
Smalldatetime1900-01-01 00:002079-06-06 23:59Datetime
Date0001-01-019999-12-313 bytesDatetime
Time00:00:00.000000023:59:59.9999999DatetimeSpecifying the precision is possible. TIME(3) will have milliseconds precision. TIME(7) is the highest and the default precision. Casting values to a lower precision will round the value.
Datetime20001-01-01 00:00:00.00000009999-12-31 23:59:59.9999999Presicion 1-2 = 6 bytes precision 3-4 = 7 bytes precision 5-7 = 8 bytesDatetimeCombines the date datatype and the time datatype into one. The precision logic is the same as for the time datatype.
Datetimeoffset0001-01-01 00:00:00.0000000 -14:009999-12-31 23:59:59.9999999 +14:00Presicion 1-2 = 8 bytes precision 3-4 = 9 bytes precision 5-7 = 10 bytesDatetimeIs a datetime2 datatype with the UTC offset appended.
Char0 chars8000 charsDefined widthStringFixed width
Varchar0 chars8000 chars2 bytes + number of charsStringVariable width
Varchar(max)0 chars2^31 chars2 bytes + number of charsStringVariable width
Text0 chars2,147,483,647 chars4 bytes + number of charsStringVariable width
Nchar0 chars4000 charsDefined width x 2UnicodeFixed width
Nvarchar0 chars4000 charsUnicodeVariable width
Nvarchar(max)0 chars2^30 charsUnicodeVariable width
Ntext0 chars1,073,741,823 charsUnicodeVariable width
Binary0 bytes8000 bytesBinaryFixed width
Varbinary0 bytes8000 bytesBinaryVariable width
Varbinary(max)0 bytes2^31 bytesBinaryVariable width
Image0 bytes2,147,483,647 bytesBinaryVariable width. Prefer to use the varbinary(max) type as the image type will be removed in future versions.
Sql_variantOtherStores values of various SQL Server-supported data types, except text, ntext, and timestamp.
TimestampOtherStores a database-wide unique number that gets updated every time a row gets updated.
UniqueidentifierOtherStores a globally unique identifier (GUID).
XmlOtherStores XML data. You can store xml instances in a column or a variable.
CursorOtherA reference to a cursor.
TableOtherStores a result set for later processing.

SQL Server Architecture - in brief

The major components of SQL Server are:
1.       Relational Engine
2.       Storage Engine
3.       SQL OS
Now we will discuss and understand each one of them.
1) Relational Engine: Also called as the query processor, Relational Engine includes the components of SQL Server that determine what your query exactly needs to do and the best way to do it. It manages the execution of queries as it requests data from the storage engine and processes the results returned.
Different Tasks of Relational Engine:
1.       Query Processing
2.       Memory Management
3.       Thread and Task Management
4.       Buffer Management
5.       Distributed Query Processing
2) Storage Engine: Storage Engine is responsible for storage and retrieval of the data on to the storage system (Disk, SAN etc.). to understand more, let’s focus on the concepts. When we talk about any database in SQL server, there are 2 types of files that are created at the disk level – Data file and Log file. Data file physically stores the data in data pages. Log files that are also known as write ahead logs, are used for storing transactions performed on the database.

Let’s understand data file and log file in more details:
Data File: Data File stores data in the form of Data Page (8KB) and these data pages are logically organized in extents.
Extents: Extents are logical units in the database. They are a combination of 8 data pages i.e. 64 KB forms an extent. Extents can be of two types, Mixed and Uniform. Mixed extents hold different types of pages like index, system, data etc (multiple objects). On the other hand, Uniform extents are dedicated to only one type (object).
Pages: As we should know what type of data pages can be stored in SQL Server, below mentioned are some of them:
  • Data Page: It holds the data entered by the user but not the data which is of type text, ntext, nvarchar(max), varchar(max), varbinary(max), image and xml data.
  • Index: It stores the index entries.
  • Text/Image: It stores LOB ( Large Object data) like text, ntext, varchar(max), nvarchar(max),  varbinary(max), image and xml data.
  • GAM & SGAM (Global Allocation Map & Shared Global Allocation Map): They are used for saving information related to the allocation of extents.
  • PFS (Page Free Space): Information related to page allocation and unused space available on pages.
  • IAM (Index Allocation Map): Information pertaining to extents that are used by a table or index per allocation unit.
  • BCM (Bulk Changed Map): Keeps information about the extents changed in a Bulk Operation.
  • DCM (Differential Change Map): This is the information of extents that have modified since the last BACKUP DATABASE statement as per allocation unit.
Log File: It also known as write ahead log. It stores modification to the database (DML and DDL).
·         Sufficient information is logged to be able to:
o    Roll back transactions if requested
o    Recover the database in case of failure
o    Write Ahead Logging is used to create log entries
§  Transaction logs are written in chronological order in a circular way
§  Truncation policy for logs is based on the recovery model

3) SQL OS: This lies between the host machine (Windows OS) and SQL Server. All the activities performed on database engine are taken care of by SQL OS. It is a highly configurable operating system with powerful API (application programming interface), enabling automatic locality and advanced parallelism. SQL OS provides various operating system services, such as memory management deals with buffer pool, log buffer and deadlock detection using the blocking and locking structure. Other services include exception handling, hosting for external components like Common Language Runtime, CLR etc.

Tuesday, March 25, 2014

Select into - restrictions

  • You cannot specify a table variable or table-valued parameter as the new table.
  • You cannot use SELECT…INTO to create a partitioned table, even when the source table is partitioned. SELECT...INTO does not use the partition scheme of the source table; instead, the new table is created in the default filegroup. To insert rows into a partitioned table, you must first create the partitioned table and then use the INSERT INTO...SELECT FROM statement.
  • Indexes, constraints, and triggers defined in the source table are not transferred to the new table, nor can they be specified in the SELECT...INTO statement. If these objects are required, you can create them after executing the SELECT...INTO statement.
  • Specifying an ORDER BY clause does not guarantee the rows are inserted in the specified order.
  • When a sparse column is included in the select list, the sparse column property does not transfer to the column in the new table. If this property is required in the new table, alter the column definition after executing the SELECT...INTO statement to include this property.
  • When a computed column is included in the select list, the corresponding column in the new table is not a computed column. The values in the new column are the values that were computed at the time SELECT...INTO was executed. 
When an existing identity column is selected into a new table, the new column inherits the IDENTITY property, unless one of the following conditions is true:
  • The SELECT statement contains a join, GROUP BY clause, or aggregate function.
  • Multiple SELECT statements are joined by using UNION.
  • The identity column is listed more than one time in the select list.
  • The identity column is part of an expression.
  • The identity column is from a remote data source.
 

Logical Processing Order of the SELECT statement

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

Cursors

A cursor is a memory resident set of pointers -- meaning it occupies memory from your system that may be available for other processes. Microsoft SQL Server implements cursors by creating a temporary table and populating it with the query's result set. If a cursor is not properly closed (deallocated), the resources will not be freed until the SQL session (connection) itself is closed. This wasting of resources on the server can lead to performance degradations and failures.

The types of cursors used are very important in terms of performance.
1.       FORWARD_ONLY - Specifies that the cursor can only be scrolled from the first to the last row. FETCH NEXT is the only supported fetch option. If FORWARD_ONLY is specified without the STATIC, KEYSET, or DYNAMIC keywords, the cursor operates as a DYNAMIC cursor.
2.       STATIC - Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor.
3.       READ_ONLY - Prevents updates made through this cursor. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides the default capability of a cursor to be updated.

4.       FAST_FORWARD - Specifies a FORWARD_ONLY, READ_ONLY cursor with performance optimizations enabled. FAST_FORWARD cannot be specified if SCROLL or FOR_UPDATE is also specified.

Cursors can be faster than a while loop but they do have more overhead. If your cursor will not be updating the base tables, use a FAST_FORWARD cursor for optimal performance.

Disadvantages
1.       Fetching a row from the cursor may result in a network round trip each time. This uses much more network bandwidth than would ordinarily be needed for the execution of a single SQL statement like DELETE. Repeated network round trips can severely impact the speed of the operation using the cursor.
2.       Also, a majority of cursor operations occur in tempdb, so a heavily used tempdb will be even more overloaded with the use of cursors.      

Sunday, March 23, 2014

Collation

A collation encodes the rules governing the proper use of characters for either a language, such as Greek or Polish, or an alphabet, such as Latin1_General (the Latin alphabet used by western European languages).
Each SQL Server collation specifies three properties:
  • The sort order to use for Unicode data types (nchar, nvarchar, and ntext). A sort order defines the sequence in which characters are sorted, and the way characters are evaluated in comparison operations.
  • The sort order to use for non-Unicode character data types (char, varchar, and text).
  • The code page used to store non-Unicode character data.
If the users of your instance of SQL Server speak multiple languages, you should pick a collation that best supports the requirements of the various languages. For example, if the users generally speak western European languages, choose the Latin1_General collation.
Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case-sensitivity, accent marks, kana character types and character width.

Case sensitivity
If A and a, B and b, etc. are treated in the same way then it is case-insensitive. A computer treats A and a differently because it uses ASCII code to differentiate the input. The ASCII value of A is 65, while a is 97. The ASCII value of B is 66 and b is 98.

Accent sensitivity
If a and á, o and ó are treated in the same way, then it is accent-insensitive. A computer treats a and á differently because it uses ASCII code for differentiating the input. The ASCII value of a is 97 and áis 225. The ASCII value of o is 111 and ó is 243.

Kana Sensitivity
When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive. 

Width sensitivity
When a single-byte character (half-width) and the same character when represented as a double-byte character (full-width) are treated differently than it is width sensitive.

You can use the COLLATE keyword in various ways and at several levels:
COLLATE on database creation You can use the COLLATE clause of the CREATE DATABASE or ALTER DATABASE statement to specify the default collation of the database. You can also specify a collation when you create a database using SQL Server Management Studio. If you do not specify a collation, the database is assigned the default collation of the instance of SQL Server.
COLLATE on table creation You can specify collations for each varchar or char column using the COLLATE clause in the CREATE TABLE or ALTER TABLE statement. You can also specify a collation when you create a table using SQL Server Management Studio. If you do not specify a collation, the column is assigned the default collation of the database.
COLLATE by casting or expression You can use the COLLATE clause to cast an expression to a certain collation. You can assign the COLLATE clause to any ORDER BY or comparison statement.
SQL Server 2005 supports more than 1,000 collation types.

Alter Column - Rules to remember

The modified column cannot be any one of the following:
·         A column with a timestamp data type.
·         The ROWGUIDCOL for the table.
·         A computed column or used in a computed column.
·         Used in a PRIMARY KEY or [FOREIGN KEY] REFERENCES constraint.
·         Used in a CHECK or UNIQUE constraint. However, changing the length of a variable-length column used in a CHECK or UNIQUE constraint is allowed.
·         Associated with a default definition. However, the length, precision, or scale of a column can be changed if the data type is not changed. 
·         The data type of a column of a partitioned table cannot be changed.
·         The data type of columns included in an index cannot be changed unless the column is a varchar, nvarchar, or varbinary data type, and the new size is equal to or larger than the old size.
·         A columns included in a primary key constraint, cannot be changed from NOT NULL to NULL.
Some data type changes may cause a change in the data. For example, changing an nchar or nvarchar column to char or varchar may cause the conversion of extended characters. Reducing the precision or scale of a column may cause data truncation.  
The following are criteria for type_name of an altered column:
·         The previous data type must be implicitly convertible to the new data type.
  • type_name cannot be timestamp.
  • ANSI_NULL defaults are always on for ALTER COLUMN; if not specified, the column is nullable.
  • ANSI_PADDING padding is always ON for ALTER COLUMN.
  •  If the modified column is an identity column, new_data_type must be a data type that supports the identity property.