Working with MSSQL Server
Data Types
Ram Kedem
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Data Types Introduction
• Data types determine what can be stored
• Constrains the type of data that an object can hold
• Provides limits on the range of values
• Critical to choose appropriate data type
• It constrains the type of data an object can hold. This means that
you can't put text in a numeric object, etc.
• It rovides limits on the range of values. If you know it's an integer,
you can't try to put 2304892309232323423 in it.
• It Assists with query optimization. If SQL Server knows a column is
an integer, it can build a different query plan to one where the
value might also be a name.
• It provides a level of self-documentation. If all columns were
variant, you would need to separately document the type of data
stored in them to know how to work with them.
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Exact Numeric Data Types - Integer
DROP TABLE int_tab ;
CREATE TABLE int_tab
(c_tinyint tinyint, -- (0 to 255),
-- Cannot store negative numbers
c_smallint smallint, -- (-32768 to 32767)
c_int int, -- (-2147483648 to 2147483647)
c_bigint bigint -- (-2^63 to 2^63 – 1)
)
INSERT INTO int_tab
VALUES (1.5 , 1.6 , 1.7 , 1.8)
SELECT * FROM int_tab ;
DELETE FROM int_tab ;
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Exact Numeric Data Types -Decimal
• decimal and numeric are functionally equivalent.
• we normally write decimal(p,s)
• p (precision) is a value from 1 to 38 with a default of 18 and
• S (scale) is the number of decimal places and can be any value
from 0 up to the P value.
• The default scale is zero.
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Exact Numeric Data Types - Decimal
DROP TABLE dec_tab
CREATE TABLE dec_tab
(c_decimal_1 decimal, -- Default is decimal(18)
c_decimal_2 decimal (8,2),
-- c_decimal_3 decimal (8,9),
-- Error : The scale (9) for column 'c_decimal_3' must
-- be within the range 0 to 8.
c_numeric_1 numeric,
c_numeric_2 numeric (8,2))
INSERT INTO dec_tab
VALUES (1.5 , 1.6 , 1.7 , 1.8)
INSERT INTO dec_tab
VALUES (1, 1 ,123456789123456789 ,1)
SELECT * FROM dec_tab ;
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Exact Numeric Data Types -Currency
• Money and Smallmoney have a fixed scale of 4
• Typically decimal would be a better (and more standard)
choice
DROP TABLE curr_tab
CREATE TABLE curr_tab
(c_smallmoney smallmoney, -- Maximum precision is 6, fixed scale of 4.
c_money money, -- Maximum precision is 15, fixed scale of 4.
c_bit bit) -- values of 1, 0, or NULL
INSERT INTO curr_tab
VALUES (1.12345 , 1.12345 , 1)
SELECT * FROM curr_tab ;
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Approximate Numeric Data Types
• You should try to avoid the FLOAT datatype whenever
possible, and opt for the more versatile, and precise, DECIMAL
or NUMERIC datatypes instead
• float is from float(1) to float(53) and defaults to float(53)
• The ISO synonym for real is float(24).
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Approximate Numeric Data Types
DROP TABLE approx_tab
CREATE TABLE approx_tab
(c_real_1 real,
c_real_2 real,
-- c_real_3 real(4), -- Error - Cannot specify a column width on data type real.
c_float_1 float(3),
c_float_2 float)
INSERT INTO approx_tab
VALUES (54 , 3.1 , 1.3, 1.4)
SELECT * FROM approx_tab
SELECT (0 + c_real_2 + c_real_1) - c_real_1 - c_real_2
FROM approx_tab
DECLARE @Float1 float, @Float2 float, @Float3 float, @Float4 float;
SET @Float1 = 54;
SET @Float2 = 0.03;
SET @Float3 = 0 + @Float1 + @Float2;
SELECT @Float3 - @Float1 - @Float2 AS "Should be 0";
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Exact VS Approximate
• A grand choice for “exact” numeric data, is when dealing with
numbers that have a fixed number of decimal places and
represent an exact amount, such as monetary units.
• But if you are dealing with scientific data, that is usually
derived from some measurement and hence by definition an
approximation of reality (since there’s no way to measure with
unlimited precision) , floating point data is an excellent choice
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Dates
CREATE TABLE dates_tab
(c_date date,
-- 0001-01-01 to 9999-12-31
-- Accuracy of 1 day
c_datetime2 datetime2,
-- 0001-01-01 to 9999-12-31
-- Accuracy of 100 nanosecond
-- DateTime2 is the new Data Type introduced in Sql Server 2008
-- Microsoft Suggests to use this new Data Type for new work instead of DateTime
c_datetime datetime,
-- 1753-01-01 to 9999-12-31
-- Accuracy of 3.33 milliseconds
c_datetimeoffset datetimeoffset ,
-- 0001-01-01 to 9999-12-31
-- Accuracy of 100 nanosecond
-- Plus timezone
c_smalldatetime smalldatetime,
-- 1900-01-01 to 2079-06-06
-- Accuracy of 1 minute
c_time time
-- 00:00:00.0000000 to 23:59:59.9999999
-- Accuracy of 100 nanosecond
)
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Dates
INSERT INTO dates_tab
VALUES (GETDATE() , GETDATE() , GETDATE() ,
GETDATE() , GETDATE() , GETDATE() )
SELECT * FROM dates_tab
SELECT c_date AS 'Date' ,
DATALENGTH ( c_date ) AS 'Date Size',
c_datetime2 AS 'Datetime2' ,
DATALENGTH ( c_datetime2 ) AS 'Datetime2 Size',
c_datetime AS 'datetime',
DATALENGTH ( c_datetime ) AS 'datetime Size',
c_datetimeoffset AS 'datetimeoffset',
DATALENGTH ( c_datetimeoffset )AS 'datetimeoffset Size',
c_smalldatetime AS 'smalldatetime',
DATALENGTH ( c_smalldatetime ) AS 'smalldatetime Size',
c_time AS 'time',
DATALENGTH ( c_time ) AS 'time Size'
FROM dates_tab
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Working with Character Data
Unicode / Non Unicode
• Unicode
• Is a worldwide character-encoding standard
• Simplifies software localization
• Improves multilingual character processing
• Is implemented in SQL Server as double-byte for Unicode types
Requires N prefix on constants
• Uses LEN() to return number of characters, DATALENGTH() to
return the number of bytes
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Working with Character Data
Unicode / Non Unicode
DROP TABLE dbo.testcharacter ;
CREATE TABLE dbo.TestCharacter
(
id int NOT NULL IDENTITY(1,1),
NonUnicodeData varchar(10),
UnicodeData nvarchar(10)
);
INSERT dbo.TestCharacter (NonUnicodeData,UnicodeData)
VALUES ('Hello',N'Hello'),
('‫,'שלום‬N'‫)'שלום‬
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Working with Character Data
Unicode / Non Unicode
SELECT * FROM dbo.TestCharacter;
SELECT nonUnicodeData ,
LEN(nonUnicodeData) AS 'number of characters' ,
DATALENGTH(nonUnicodeData) AS 'number of bytes'
FROM dbo.TestCharacter
WHERE nonUnicodeData = 'hello' ;
SELECT UnicodeData ,
LEN(UnicodeData) AS 'number of characters' ,
DATALENGTH(UnicodeData) AS 'number of bytes'
FROM dbo.TestCharacter
WHERE UnicodeData = N'‫'שלום‬ ;
SELECT UnicodeData ,
LEN(UnicodeData) AS 'number of characters' ,
DATALENGTH(UnicodeData) AS 'number of bytes'
FROM dbo.TestCharacter
WHERE UnicodeData = 'hello' ;
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Character Data Types
DROP TABLE char_tab ;
CREATE TABLE char_tab
(c_char char(5), -- maximum 8000
c_nchar nchar(20), -- maximum 4000
c_varchar varchar, -- maximum 8000
c_nvarchar nvarchar, -- maximum 4000
c_varchar_max varchar(max), -- maximum 2G
c_nvarchar_max nvarchar(max), -- maximum 2G
c_text text, -- deprecated, use varchar(max)
c_ntext ntext) -- deprecated, use nvarchar(max)
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Understanding Collations
• 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.
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Understanding Collations
-- The CS and AS values mean "case-sensitive" and "accent-
sensitive".
DROP TABLE collate_tab
GO
CREATE TABLE Collate_tab
(person_id int identity (1,1),
person_name varchar(25));
GO
INSERT INTO Collate_tab
VALUES ('Ram') , ('ram') , ('RAM') , ('rAM');
SELECT * FROM Collate_tab ;
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Understanding Collations
-- By defualt not case sensitive
SELECT * FROM Collate_tab WHERE person_name = 'ram';
-- Change to case sensitive in the SQL Statement level
SELECT *
FROM Collate_tab
WHERE person_name COLLATE Latin1_General_CS_AS= 'ram';
-- Change to case sensitive in the Table column level
ALTER TABLE Collate_tab
ALTER COLUMN person_name VARCHAR(25)
COLLATE Latin1_General_CS_AS
SELECT *
FROM Collate_tab
WHERE person_name = 'ram';
-- Change in the DB level
-- ALTER DATABASE adventureworks collate SQL_Latin1_General_CP1_CI_AS
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
CAST and CONVERT
-- Using cast
--------------
-- CAST is supported by SQL standards
SELECT 'The date is : ' + CAST(GETDATE() AS VARCHAR(20))
-- Using Covert
----------------
-- CONVERT is a more powerful SQL Server extension to the SQL language
SELECT 'The date is : ' + CONVERT(VARCHAR(20) ,GETDATE() , 104)
USE tempdb;
GO
-- Step 2: Execute statements to see different formats
-- of a date conversion
SELECT CAST(SYSDATETIME() as varchar(20)) as CastDate,
CONVERT(varchar(20), SYSDATETIME(), 110) as USA,
CONVERT(varchar(20), SYSDATETIME(), 104) as German,
CONVERT(varchar(20), SYSDATETIME(), 105) as Italian,
CONVERT(varchar(20), SYSDATETIME(), 112) as ISO,
CONVERT(varchar(20), SYSDATETIME(), 114) as [Time];
GO
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Parse
-- http://go.microsoft.com/fwlink/?LinkID=233801
SELECT PARSE('2010 13 December' AS datetime2 USING 'en-US');
SELECT PARSE('$345.98' AS money USING 'en-US') AS Result;
-- error
SELECT PARSE ('NotLikely' AS decimal USING 'en-US') AS result
-- null
SELECT TRY_PARSE ('NotLikely' AS decimal USING 'en-US') AS result ;
SELECT
CASE WHEN TRY_PARSE('NotLikely' AS decimal
USING
'sr-Latn-CS') IS NULL
THEN 'Not Decimal'
ELSE 'Decimal'
END AS Result ;
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Implicit Conversion
DECLARE @int1 int = 1;
DECLARE @int2 int = 2;
DECLARE @char char(1) = 3;
SELECT @int1 + @int2 ;
SELECT @int2 * @char
GO
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
ROWVERSION
• Rowversion is the synonym for timestamp in SQL Server 2005
and SQL Server 2008.
• Timestamp has been deprecated and replaced by rowversion.
• Rowversion should be used for all new work. timestamp does
not contain any value related to time.
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
ROWVERSION
USE tempdb;
GO
-- Step 2: Create and populate a table that uses the rowversion data type
CREATE TABLE dbo.Orders
(
OrderID int NOT NULL
IDENTITY(1,1),
OrderDate date NOT NULL,
SalespersonID int NULL,
Concurrency rowversion NOT NULL
);
GO
-- Step 3: Add 2 new rows to dbo.Opportunity
INSERT dbo.Orders (OrderDate)
VALUES (SYSDATETIME()),
(SYSDATETIME());
GO
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
ROWVERSION
-- Step 4: Show that the rowversion column was populated automatically
SELECT * FROM dbo.Orders;
GO
-- Step 5: Try to update the rowversion column. This will fail as
-- you cannot update a rowversion column directly.
UPDATE dbo.Orders
SET Concurrency = Concurrency +1
WHERE OrderID =1;
GO
-- Step 6: Try to insert an explicit value for the rowversion column.
-- This will fail as you cannot insert into a rowversion
-- column directly.
INSERT dbo.Orders (OrderDate, Concurrency)
VALUES (SYSDATETIME(), 0x00000000000007E4);
GO
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
ROWVERSION
-- Step 7: Update another column for OrderID 1
SELECT * FROM dbo.Orders
WHERE OrderID = 1;
UPDATE dbo.Orders
SET SalespersonID = 36
WHERE OrderID =1;
SELECT * FROM dbo.Orders
WHERE OrderID = 1;
GO
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Alias Data Types
• The main use of these alias types is in maintaining consistency
across development.
CREATE TYPE ProductNumber
FROM nvarchar(20) NOT NULL;
GO
CREATE TABLE Production.ProductConversion
( ProductConversionID int IDENTITY(1,1),
FromProduct ProductNumber,
ToProduct ProductNumber
);
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Computed Columns
• Computed columns are actually not physically created on
the related database table unless they are defined as
"Persisted" computed columns.
• You can think of computed columns as virtual columns.
They are not physically stored in the related sql database
table.
• A non-persisted computed column is calculated every
time a SELECT operation occurs on the column.
• A persisted computed column is calculated when the
data in the row is inserted or updated
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Computed Columns
-- Step 1: Open a new query window to the tempdb database
USE tempdb;
GO
-- Step 2: Create a table with a persisted computed column
DROP TABLE pet ;
GO
CREATE TABLE Pet
(PetID int IDENTITY(1,1) PRIMARY KEY,
PetName nvarchar(30) NOT NULL,
PetType nvarchar(10) NOT NULL,
DateOfBirth date NOT NULL,
YearOfBirth AS DATEPART(year,DateOfBirth) PERSISTED
);
GO
-- Step 3: Insert some data into the table
INSERT Pet (PetName, PetType, DateOfBirth)
VALUES ('Brutus','DOG','2007-12-31'),
('Bruno','DOG','2006-01-01'),
('Tweetie','BIRD','2005-04-02');
GO
-- Step 4: Query the table
SELECT * FROM Pet;
GO
GO
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Computed Columns
-- Demo 2 - Using CASE ()
-------------------------
CREATE TABLE emps
(id int,
sal int,
grade_level as (CASE WHEN sal BETWEEN 0 AND 5000 THEN 'a' ELSE 'b' END ))
INSERT INTO emps VALUES (1, 1)
SELECT * FROM emps
-- Demo 3 - Combination of different columns
--------------------------------------------
DROP TABLE emps
CREATE TABLE emps
(id int,
sal_per_hour int,
total_hours int,
total_sal AS sal_per_hour * total_hours PERSISTED)
INSERT INTO emps VALUES (1, 25, 180)
SELECT * FROM emps
UPDATE emps SET sal_per_hour = 40 ;
Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent
Computed Columns
-- Demo 4 - Computed column in another computed column
------------------------------------------------------
DROP TABLE emps
CREATE TABLE emps
(id int,
birthdate datetime,
age as datediff(yyyy, birthdate , getdate()),
emp_rank as (CASE WHEN age BETWEEN 0 AND 30 THEN 'Begginer' ELSE 'Senior' END) )

More Related Content

PDF
3 indexes
PDF
4 execution plans
PDF
2 designing tables
PPTX
Introduction to (sql)
PPT
SQL : introduction
PPTX
Oraclesql
PPTX
Sql Basics And Advanced
PPTX
Introduction to SQL (for Chicago Booth MBA technology club)
3 indexes
4 execution plans
2 designing tables
Introduction to (sql)
SQL : introduction
Oraclesql
Sql Basics And Advanced
Introduction to SQL (for Chicago Booth MBA technology club)

What's hot (20)

PPTX
DDL(Data defination Language ) Using Oracle
PPT
Sql server T-sql basics ppt-3
PPT
Introduction to-sql
PDF
Introduction To Oracle Sql
PPTX
Introduction to SQL
PPTX
Structure query language (sql)
PPT
Advanced Sql Training
PDF
Introduction to SQL
PPTX
SQL Commands
PPTX
Introduction to SQL
PPTX
Dbms & oracle
PPTX
Sql.pptx
PPTX
Advanced SQL Webinar
ODP
BIS05 Introduction to SQL
PDF
Chapter 4 Structured Query Language
PDF
Oracle SQL Basics
DOC
A must Sql notes for beginners
PPT
SQL Tutorial - Basic Commands
PPT
Dbms oracle
PPT
Intro to tsql unit 7
DDL(Data defination Language ) Using Oracle
Sql server T-sql basics ppt-3
Introduction to-sql
Introduction To Oracle Sql
Introduction to SQL
Structure query language (sql)
Advanced Sql Training
Introduction to SQL
SQL Commands
Introduction to SQL
Dbms & oracle
Sql.pptx
Advanced SQL Webinar
BIS05 Introduction to SQL
Chapter 4 Structured Query Language
Oracle SQL Basics
A must Sql notes for beginners
SQL Tutorial - Basic Commands
Dbms oracle
Intro to tsql unit 7
Ad

Viewers also liked (10)

PPT
Database indexing framework
PPTX
Indexing the MySQL Index: Key to performance tuning
PDF
Introduction to Databases
ODP
Ms sql-server
PPTX
Database indexing techniques
PPSX
MS SQL Server
PDF
Introduction to TFS 2013
PDF
MySQL: Indexing for Better Performance
PPTX
MySQL Indexing - Best practices for MySQL 5.6
PDF
How to Design Indexes, Really
Database indexing framework
Indexing the MySQL Index: Key to performance tuning
Introduction to Databases
Ms sql-server
Database indexing techniques
MS SQL Server
Introduction to TFS 2013
MySQL: Indexing for Better Performance
MySQL Indexing - Best practices for MySQL 5.6
How to Design Indexes, Really
Ad

Similar to 1 data types (20)

PPT
Intro To TSQL - Unit 5
 
PPT
Intro to tsql unit 5
PDF
DP080_Lecture_2 SQL related document.pdf
PPTX
MySQL Data types
PPTX
Data type[s] on MS SQL Server
PPTX
session_2 on database mysql databaseds from file to
DOCX
Sql data types for various d bs by naveen kumar veligeti
PPT
Intro to tsql unit 10
DOCX
Built-in Functions in SQL | Numeric Functions
PDF
New fordevelopersinsql server2008
PPTX
SQL Server - Introduction to TSQL
PPTX
Session 2 - "MySQL Basics & Schema Design"
PPT
Oracle Sql & PLSQL Complete guide
PPTX
Sql server lesson5
PDF
Sql tutorial
PDF
Sql tutorial
PPTX
SQL Commands Part 1.pptx
DOC
Most useful queries
DOCX
Sql Server Interview Question
Intro To TSQL - Unit 5
 
Intro to tsql unit 5
DP080_Lecture_2 SQL related document.pdf
MySQL Data types
Data type[s] on MS SQL Server
session_2 on database mysql databaseds from file to
Sql data types for various d bs by naveen kumar veligeti
Intro to tsql unit 10
Built-in Functions in SQL | Numeric Functions
New fordevelopersinsql server2008
SQL Server - Introduction to TSQL
Session 2 - "MySQL Basics & Schema Design"
Oracle Sql & PLSQL Complete guide
Sql server lesson5
Sql tutorial
Sql tutorial
SQL Commands Part 1.pptx
Most useful queries
Sql Server Interview Question

More from Ram Kedem (20)

PDF
Impala use case @ edge
PPTX
Managing oracle Database Instance
PDF
Power Pivot and Power View
PDF
Data Mining in SSAS
PDF
Data mining In SSAS
PPTX
SQL Injections - Oracle
PDF
SSAS Attributes
PDF
SSRS Matrix
PDF
DDL Practice (Hebrew)
PDF
DML Practice (Hebrew)
PDF
Exploring Oracle Database Architecture (Hebrew)
PDF
Deploy SSRS Project - SQL Server 2014
PDF
Pig - Processing XML data
PDF
SSAS Cubes & Hierarchies
PDF
SSRS Basic Parameters
PPTX
SSRS Gauges
PDF
SSRS Conditional Formatting
PDF
SSRS Calculated Fields
PDF
SSRS Groups
PDF
Deploy SSIS
Impala use case @ edge
Managing oracle Database Instance
Power Pivot and Power View
Data Mining in SSAS
Data mining In SSAS
SQL Injections - Oracle
SSAS Attributes
SSRS Matrix
DDL Practice (Hebrew)
DML Practice (Hebrew)
Exploring Oracle Database Architecture (Hebrew)
Deploy SSRS Project - SQL Server 2014
Pig - Processing XML data
SSAS Cubes & Hierarchies
SSRS Basic Parameters
SSRS Gauges
SSRS Conditional Formatting
SSRS Calculated Fields
SSRS Groups
Deploy SSIS

Recently uploaded (20)

DOCX
search engine optimization ppt fir known well about this
PDF
How IoT Sensor Integration in 2025 is Transforming Industries Worldwide
PDF
Getting started with AI Agents and Multi-Agent Systems
PPTX
Configure Apache Mutual Authentication
PPTX
Modernising the Digital Integration Hub
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PPTX
The various Industrial Revolutions .pptx
PDF
Produktkatalog fĂĽr HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
PPTX
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
PPT
Geologic Time for studying geology for geologist
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PDF
CloudStack 4.21: First Look Webinar slides
PDF
Convolutional neural network based encoder-decoder for efficient real-time ob...
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
sbt 2.0: go big (Scala Days 2025 edition)
PPT
What is a Computer? Input Devices /output devices
PPTX
2018-HIPAA-Renewal-Training for executives
PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
search engine optimization ppt fir known well about this
How IoT Sensor Integration in 2025 is Transforming Industries Worldwide
Getting started with AI Agents and Multi-Agent Systems
Configure Apache Mutual Authentication
Modernising the Digital Integration Hub
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
The various Industrial Revolutions .pptx
Produktkatalog fĂĽr HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
Geologic Time for studying geology for geologist
Consumable AI The What, Why & How for Small Teams.pdf
The influence of sentiment analysis in enhancing early warning system model f...
CloudStack 4.21: First Look Webinar slides
Convolutional neural network based encoder-decoder for efficient real-time ob...
A review of recent deep learning applications in wood surface defect identifi...
sbt 2.0: go big (Scala Days 2025 edition)
What is a Computer? Input Devices /output devices
2018-HIPAA-Renewal-Training for executives
Enhancing plagiarism detection using data pre-processing and machine learning...
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf

1 data types

  • 1. Working with MSSQL Server Data Types Ram Kedem
  • 2. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Data Types Introduction • Data types determine what can be stored • Constrains the type of data that an object can hold • Provides limits on the range of values • Critical to choose appropriate data type • It constrains the type of data an object can hold. This means that you can't put text in a numeric object, etc. • It rovides limits on the range of values. If you know it's an integer, you can't try to put 2304892309232323423 in it. • It Assists with query optimization. If SQL Server knows a column is an integer, it can build a different query plan to one where the value might also be a name. • It provides a level of self-documentation. If all columns were variant, you would need to separately document the type of data stored in them to know how to work with them.
  • 3. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Exact Numeric Data Types - Integer DROP TABLE int_tab ; CREATE TABLE int_tab (c_tinyint tinyint, -- (0 to 255), -- Cannot store negative numbers c_smallint smallint, -- (-32768 to 32767) c_int int, -- (-2147483648 to 2147483647) c_bigint bigint -- (-2^63 to 2^63 – 1) ) INSERT INTO int_tab VALUES (1.5 , 1.6 , 1.7 , 1.8) SELECT * FROM int_tab ; DELETE FROM int_tab ;
  • 4. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Exact Numeric Data Types -Decimal • decimal and numeric are functionally equivalent. • we normally write decimal(p,s) • p (precision) is a value from 1 to 38 with a default of 18 and • S (scale) is the number of decimal places and can be any value from 0 up to the P value. • The default scale is zero.
  • 5. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Exact Numeric Data Types - Decimal DROP TABLE dec_tab CREATE TABLE dec_tab (c_decimal_1 decimal, -- Default is decimal(18) c_decimal_2 decimal (8,2), -- c_decimal_3 decimal (8,9), -- Error : The scale (9) for column 'c_decimal_3' must -- be within the range 0 to 8. c_numeric_1 numeric, c_numeric_2 numeric (8,2)) INSERT INTO dec_tab VALUES (1.5 , 1.6 , 1.7 , 1.8) INSERT INTO dec_tab VALUES (1, 1 ,123456789123456789 ,1) SELECT * FROM dec_tab ;
  • 6. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Exact Numeric Data Types -Currency • Money and Smallmoney have a fixed scale of 4 • Typically decimal would be a better (and more standard) choice DROP TABLE curr_tab CREATE TABLE curr_tab (c_smallmoney smallmoney, -- Maximum precision is 6, fixed scale of 4. c_money money, -- Maximum precision is 15, fixed scale of 4. c_bit bit) -- values of 1, 0, or NULL INSERT INTO curr_tab VALUES (1.12345 , 1.12345 , 1) SELECT * FROM curr_tab ;
  • 7. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Approximate Numeric Data Types • You should try to avoid the FLOAT datatype whenever possible, and opt for the more versatile, and precise, DECIMAL or NUMERIC datatypes instead • float is from float(1) to float(53) and defaults to float(53) • The ISO synonym for real is float(24).
  • 8. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Approximate Numeric Data Types DROP TABLE approx_tab CREATE TABLE approx_tab (c_real_1 real, c_real_2 real, -- c_real_3 real(4), -- Error - Cannot specify a column width on data type real. c_float_1 float(3), c_float_2 float) INSERT INTO approx_tab VALUES (54 , 3.1 , 1.3, 1.4) SELECT * FROM approx_tab SELECT (0 + c_real_2 + c_real_1) - c_real_1 - c_real_2 FROM approx_tab DECLARE @Float1 float, @Float2 float, @Float3 float, @Float4 float; SET @Float1 = 54; SET @Float2 = 0.03; SET @Float3 = 0 + @Float1 + @Float2; SELECT @Float3 - @Float1 - @Float2 AS "Should be 0";
  • 9. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Exact VS Approximate • A grand choice for “exact” numeric data, is when dealing with numbers that have a fixed number of decimal places and represent an exact amount, such as monetary units. • But if you are dealing with scientific data, that is usually derived from some measurement and hence by definition an approximation of reality (since there’s no way to measure with unlimited precision) , floating point data is an excellent choice
  • 10. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Dates CREATE TABLE dates_tab (c_date date, -- 0001-01-01 to 9999-12-31 -- Accuracy of 1 day c_datetime2 datetime2, -- 0001-01-01 to 9999-12-31 -- Accuracy of 100 nanosecond -- DateTime2 is the new Data Type introduced in Sql Server 2008 -- Microsoft Suggests to use this new Data Type for new work instead of DateTime c_datetime datetime, -- 1753-01-01 to 9999-12-31 -- Accuracy of 3.33 milliseconds c_datetimeoffset datetimeoffset , -- 0001-01-01 to 9999-12-31 -- Accuracy of 100 nanosecond -- Plus timezone c_smalldatetime smalldatetime, -- 1900-01-01 to 2079-06-06 -- Accuracy of 1 minute c_time time -- 00:00:00.0000000 to 23:59:59.9999999 -- Accuracy of 100 nanosecond )
  • 11. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Dates INSERT INTO dates_tab VALUES (GETDATE() , GETDATE() , GETDATE() , GETDATE() , GETDATE() , GETDATE() ) SELECT * FROM dates_tab SELECT c_date AS 'Date' , DATALENGTH ( c_date ) AS 'Date Size', c_datetime2 AS 'Datetime2' , DATALENGTH ( c_datetime2 ) AS 'Datetime2 Size', c_datetime AS 'datetime', DATALENGTH ( c_datetime ) AS 'datetime Size', c_datetimeoffset AS 'datetimeoffset', DATALENGTH ( c_datetimeoffset )AS 'datetimeoffset Size', c_smalldatetime AS 'smalldatetime', DATALENGTH ( c_smalldatetime ) AS 'smalldatetime Size', c_time AS 'time', DATALENGTH ( c_time ) AS 'time Size' FROM dates_tab
  • 12. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Working with Character Data Unicode / Non Unicode • Unicode • Is a worldwide character-encoding standard • Simplifies software localization • Improves multilingual character processing • Is implemented in SQL Server as double-byte for Unicode types Requires N prefix on constants • Uses LEN() to return number of characters, DATALENGTH() to return the number of bytes
  • 13. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Working with Character Data Unicode / Non Unicode DROP TABLE dbo.testcharacter ; CREATE TABLE dbo.TestCharacter ( id int NOT NULL IDENTITY(1,1), NonUnicodeData varchar(10), UnicodeData nvarchar(10) ); INSERT dbo.TestCharacter (NonUnicodeData,UnicodeData) VALUES ('Hello',N'Hello'), ('‫,'שלום‬N'‫)'שלום‬
  • 14. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Working with Character Data Unicode / Non Unicode SELECT * FROM dbo.TestCharacter; SELECT nonUnicodeData , LEN(nonUnicodeData) AS 'number of characters' , DATALENGTH(nonUnicodeData) AS 'number of bytes' FROM dbo.TestCharacter WHERE nonUnicodeData = 'hello' ; SELECT UnicodeData , LEN(UnicodeData) AS 'number of characters' , DATALENGTH(UnicodeData) AS 'number of bytes' FROM dbo.TestCharacter WHERE UnicodeData = N'‫'שלום‬ ; SELECT UnicodeData , LEN(UnicodeData) AS 'number of characters' , DATALENGTH(UnicodeData) AS 'number of bytes' FROM dbo.TestCharacter WHERE UnicodeData = 'hello' ;
  • 15. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Character Data Types DROP TABLE char_tab ; CREATE TABLE char_tab (c_char char(5), -- maximum 8000 c_nchar nchar(20), -- maximum 4000 c_varchar varchar, -- maximum 8000 c_nvarchar nvarchar, -- maximum 4000 c_varchar_max varchar(max), -- maximum 2G c_nvarchar_max nvarchar(max), -- maximum 2G c_text text, -- deprecated, use varchar(max) c_ntext ntext) -- deprecated, use nvarchar(max)
  • 16. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Understanding Collations • 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.
  • 17. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Understanding Collations -- The CS and AS values mean "case-sensitive" and "accent- sensitive". DROP TABLE collate_tab GO CREATE TABLE Collate_tab (person_id int identity (1,1), person_name varchar(25)); GO INSERT INTO Collate_tab VALUES ('Ram') , ('ram') , ('RAM') , ('rAM'); SELECT * FROM Collate_tab ;
  • 18. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Understanding Collations -- By defualt not case sensitive SELECT * FROM Collate_tab WHERE person_name = 'ram'; -- Change to case sensitive in the SQL Statement level SELECT * FROM Collate_tab WHERE person_name COLLATE Latin1_General_CS_AS= 'ram'; -- Change to case sensitive in the Table column level ALTER TABLE Collate_tab ALTER COLUMN person_name VARCHAR(25) COLLATE Latin1_General_CS_AS SELECT * FROM Collate_tab WHERE person_name = 'ram'; -- Change in the DB level -- ALTER DATABASE adventureworks collate SQL_Latin1_General_CP1_CI_AS
  • 19. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent CAST and CONVERT -- Using cast -------------- -- CAST is supported by SQL standards SELECT 'The date is : ' + CAST(GETDATE() AS VARCHAR(20)) -- Using Covert ---------------- -- CONVERT is a more powerful SQL Server extension to the SQL language SELECT 'The date is : ' + CONVERT(VARCHAR(20) ,GETDATE() , 104) USE tempdb; GO -- Step 2: Execute statements to see different formats -- of a date conversion SELECT CAST(SYSDATETIME() as varchar(20)) as CastDate, CONVERT(varchar(20), SYSDATETIME(), 110) as USA, CONVERT(varchar(20), SYSDATETIME(), 104) as German, CONVERT(varchar(20), SYSDATETIME(), 105) as Italian, CONVERT(varchar(20), SYSDATETIME(), 112) as ISO, CONVERT(varchar(20), SYSDATETIME(), 114) as [Time]; GO
  • 20. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Parse -- http://go.microsoft.com/fwlink/?LinkID=233801 SELECT PARSE('2010 13 December' AS datetime2 USING 'en-US'); SELECT PARSE('$345.98' AS money USING 'en-US') AS Result; -- error SELECT PARSE ('NotLikely' AS decimal USING 'en-US') AS result -- null SELECT TRY_PARSE ('NotLikely' AS decimal USING 'en-US') AS result ; SELECT CASE WHEN TRY_PARSE('NotLikely' AS decimal USING 'sr-Latn-CS') IS NULL THEN 'Not Decimal' ELSE 'Decimal' END AS Result ;
  • 21. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Implicit Conversion DECLARE @int1 int = 1; DECLARE @int2 int = 2; DECLARE @char char(1) = 3; SELECT @int1 + @int2 ; SELECT @int2 * @char GO
  • 22. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent ROWVERSION • Rowversion is the synonym for timestamp in SQL Server 2005 and SQL Server 2008. • Timestamp has been deprecated and replaced by rowversion. • Rowversion should be used for all new work. timestamp does not contain any value related to time.
  • 23. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent ROWVERSION USE tempdb; GO -- Step 2: Create and populate a table that uses the rowversion data type CREATE TABLE dbo.Orders ( OrderID int NOT NULL IDENTITY(1,1), OrderDate date NOT NULL, SalespersonID int NULL, Concurrency rowversion NOT NULL ); GO -- Step 3: Add 2 new rows to dbo.Opportunity INSERT dbo.Orders (OrderDate) VALUES (SYSDATETIME()), (SYSDATETIME()); GO
  • 24. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent ROWVERSION -- Step 4: Show that the rowversion column was populated automatically SELECT * FROM dbo.Orders; GO -- Step 5: Try to update the rowversion column. This will fail as -- you cannot update a rowversion column directly. UPDATE dbo.Orders SET Concurrency = Concurrency +1 WHERE OrderID =1; GO -- Step 6: Try to insert an explicit value for the rowversion column. -- This will fail as you cannot insert into a rowversion -- column directly. INSERT dbo.Orders (OrderDate, Concurrency) VALUES (SYSDATETIME(), 0x00000000000007E4); GO
  • 25. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent ROWVERSION -- Step 7: Update another column for OrderID 1 SELECT * FROM dbo.Orders WHERE OrderID = 1; UPDATE dbo.Orders SET SalespersonID = 36 WHERE OrderID =1; SELECT * FROM dbo.Orders WHERE OrderID = 1; GO
  • 26. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Alias Data Types • The main use of these alias types is in maintaining consistency across development. CREATE TYPE ProductNumber FROM nvarchar(20) NOT NULL; GO CREATE TABLE Production.ProductConversion ( ProductConversionID int IDENTITY(1,1), FromProduct ProductNumber, ToProduct ProductNumber );
  • 27. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Computed Columns • Computed columns are actually not physically created on the related database table unless they are defined as "Persisted" computed columns. • You can think of computed columns as virtual columns. They are not physically stored in the related sql database table. • A non-persisted computed column is calculated every time a SELECT operation occurs on the column. • A persisted computed column is calculated when the data in the row is inserted or updated
  • 28. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Computed Columns -- Step 1: Open a new query window to the tempdb database USE tempdb; GO -- Step 2: Create a table with a persisted computed column DROP TABLE pet ; GO CREATE TABLE Pet (PetID int IDENTITY(1,1) PRIMARY KEY, PetName nvarchar(30) NOT NULL, PetType nvarchar(10) NOT NULL, DateOfBirth date NOT NULL, YearOfBirth AS DATEPART(year,DateOfBirth) PERSISTED ); GO -- Step 3: Insert some data into the table INSERT Pet (PetName, PetType, DateOfBirth) VALUES ('Brutus','DOG','2007-12-31'), ('Bruno','DOG','2006-01-01'), ('Tweetie','BIRD','2005-04-02'); GO -- Step 4: Query the table SELECT * FROM Pet; GO GO
  • 29. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Computed Columns -- Demo 2 - Using CASE () ------------------------- CREATE TABLE emps (id int, sal int, grade_level as (CASE WHEN sal BETWEEN 0 AND 5000 THEN 'a' ELSE 'b' END )) INSERT INTO emps VALUES (1, 1) SELECT * FROM emps -- Demo 3 - Combination of different columns -------------------------------------------- DROP TABLE emps CREATE TABLE emps (id int, sal_per_hour int, total_hours int, total_sal AS sal_per_hour * total_hours PERSISTED) INSERT INTO emps VALUES (1, 25, 180) SELECT * FROM emps UPDATE emps SET sal_per_hour = 40 ;
  • 30. Copyright 2014 © Ram Kedem. All rights reserved. Not to be reproduced without written consent Computed Columns -- Demo 4 - Computed column in another computed column ------------------------------------------------------ DROP TABLE emps CREATE TABLE emps (id int, birthdate datetime, age as datediff(yyyy, birthdate , getdate()), emp_rank as (CASE WHEN age BETWEEN 0 AND 30 THEN 'Begginer' ELSE 'Senior' END) )