Data Types
Data Types
Section titled βData TypesβWhat it means
Section titled βWhat it meansβEvery SQL Server column has a data type that constrains what it can store and how much space it uses. Broad categories: exact numbers (INT, DECIMAL), approximate numbers (FLOAT), text (VARCHAR, NVARCHAR), dates/times (DATE, DATETIME2), and others (BIT for booleans, UNIQUEIDENTIFIER for GUIDs).
Examples
Section titled βExamplesβCREATE TABLE Products ( Id INT PRIMARY KEY IDENTITY(1,1), Name NVARCHAR(100) NOT NULL, -- Unicode text, up to 100 characters Price DECIMAL(10,2) NOT NULL, -- exact decimal, 10 total digits, 2 after the point InStock BIT NOT NULL DEFAULT 1, -- boolean: 0 or 1 CreatedAt DATETIME2 DEFAULT SYSUTCDATETIME(), -- modern, more precise date/time type Sku UNIQUEIDENTIFIER DEFAULT NEWID() -- globally unique identifier);
SELECT CAST('123' AS INT); -- explicit conversionSELECT CONVERT(DECIMAL(10,2), '19.99');Common mistake
Section titled βCommon mistakeβUsing FLOAT for money β floating-point types store approximate values, which can introduce rounding errors that compound over many calculations, exactly the kind of surprise you donβt want with financial data.
DECLARE @price FLOAT = 19.99;DECLARE @quantity FLOAT = 3;SELECT @price * @quantity; -- may not be EXACTLY 59.97 due to floating-point representation
-- Use DECIMAL for exact, predictable arithmetic with moneyDECLARE @price DECIMAL(10,2) = 19.99;DECLARE @quantity INT = 3;SELECT @price * @quantity; -- exactly 59.97Quick practice
Section titled βQuick practiceβ-
Why is
DECIMALpreferred overFLOATfor storing monetary values?Answer
DECIMALstores exact values;FLOATis an approximate, floating-point representation that can introduce small rounding errors, which is risky for financial calculations. -
Whatβs the difference between
VARCHARandNVARCHAR?Answer
NVARCHARstores Unicode text (supporting virtually any language/character set) at roughly double the storage cost per character;VARCHARstores single-byte characters only. -
What does
DECIMAL(10,2)specify?Answer
A decimal number with up to 10 total digits, 2 of which are after the decimal point (so up to 8 digits before the point).