Categories of Data Types
- Exact numerics
- Approximate numerics
- Date and Time
- Character Strings
- Unicode Character Strings
- Binary Strings
- Other data types
Exact Numerics
- Whole Numbers
- smallint
- tinyint
- int
- bigint
- Decimal Numbers
- numeric
- decimal
- money
- smallmoney
- Whole Numbers
Exact numerics - integers
Numbers without a decimal point
Data Type Storage bigint 8 Bytes int 4 Bytes smallint 2 Bytes tinyint 1 Byte Exact numerics - decimals
Approximate numerics
- Float
- Real
- Store approximate numeric values
Date and Time Data Types
Data Type Format Accuracy time hh:mm:ss[.nnnnnnn] 100 nanoseconds date YYYY-MM-DD 1 day smalldatetime YYYY-MM-DD hh:mm:ss 1 minute datetime YYYY-MM-DD hh:mm:ss[.nnn] 0.00333 second datetime2 YYYY-MM-DD hh:mm:ss[.nnnnnnn] 100 nanoseconds Character and Unicode Character Data Types
- Character data types store character strings (ASCII)
- char
- varchar
- text
- Unicode data types are used for storing Unicode data (non-ASCII)
- nchar
- nvarchar
- ntext
- Character data types store character strings (ASCII)
Other data types
- binary
- image
- cursor
- rowversino
- uniqueidentifier
- xml
- Spatial Geometry / Geography Types
Implicit Conversion
Data Comparison
Keep in mind : for comparing two values, they need to be of the same type.
Otherwise:- SQL Server converts from one type to another (IMPLICIT)
- The developer explicitly converts the data (EXPLICIT)
Data Type Precedence
- user-defined data types (highest)
- datetime
- date
- float
- decimal
- int
- bit
- nvarchar (including nvarchar(max))
- varchar (including varchar(max))
- binary (lowest)
Implicit conversion between data types
Performance impact of implicit conversion
- Implicit conversion is done for each row of the query
- Implicit conversion can be prevended with a good database schema design.
Explicit Conversion
Implicit and Explicit Conversion
- IMPLICIT : performed automatically, behind the scenes
- EXPLICIT : performed with functions
CAST()
andCONVERT()
CAST()
andCONVERT()
are used to convert from one data type to another
CAST()
Syntax: CAST(expression AS data_type [(length)])
1 2 3 4 5
SELECT CAST(3.14 AS INT) AS DECIMAL_TO_INT, CAST('3.14' AS DECIMAL(3,2)) AS STRING_TO_DECIMAL, CAST(GETDATE() AS NVARCHAR(20)) AS DATE_TO_STRING, CAST(GETDATE() AS FLOAT) AS DATE_TO_FLOAT;
CONVERT()
Syntax: CONVERT(data_type [(length)], expression, [,style])
1 2 3 4 5
SELECT CONVERT(INT, 3.14) AS DECIMAL_TO_INT, CONVERT(DECIMAL(3,2), '3.14') AS STRING_TO_DECIMAL, CONVERT(NVARCHAR(20), GETDATE(), 104) AS DATE_TO_STRING, CONVERT(FLOAT, GETDATE()) AS DATE_TO_FLOAT;
CAST() vs CONVERT()
CAST()
comes from the SQL standard andCONVERT()
is SQL Server specificCAST()
is available in most database productsCONVERT()
performs slightly better in SQL Server