Assigns SQL Server data types (INT, VARCHAR, DECIMAL, etc.) to columns and variables to control storage, precision, and validation.
Data types tell SQL Server how to store, compare, and retrieve values. Choosing the correct type preserves precision, saves space, and boosts query speed.
INT and BIGINT store whole numbers; DECIMAL(p,s) holds exact decimals—ideal for money; FLOAT and REAL allow imprecision; BIT stores 0/1 flags.
VARCHAR stores non-Unicode text using 1 byte/char. NVARCHAR stores Unicode using 2 bytes/char. Pick VARCHAR for ASCII-only data and NVARCHAR for multilingual data.
Use DATETIME2 for high-precision timestamps, DATE for date-only, TIME for time-only. Avoid legacy DATETIME unless old code demands it.
CREATE TABLE Products (
id INT PRIMARY KEY,
name NVARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL CHECK (price >= 0),
stock INT DEFAULT 0
);
Use the smallest type that fits future values, match precision to business rules, add CHECK constraints, and document every choice for maintainability.
NVARCHAR(MAX) for short strings wastes memory. Size columns realistically, e.g., NVARCHAR(100).
FLOAT rounds values. Store currency in DECIMAL(19,4) for accuracy.
Run ALTER TABLE ... ALTER COLUMN inside a transaction after validating that existing data converts without truncation. Always back up first.
-- Exact totals with DECIMAL
CREATE TABLE Orders (
id INT PRIMARY KEY,
customer_id INT NOT NULL,
order_date DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(),
total_amount DECIMAL(12,2) NOT NULL
);
NVARCHAR uses more storage but shows similar query speed when indexed. Overhead is mainly in disk and cache usage.
GUIDs ensure global uniqueness but fragment clustered indexes. Prefer INT/BIGINT keys or NEWSEQUENTIALID() to reduce fragmentation.
NVARCHAR’s extra byte per character increases storage, but well-indexed queries perform similarly. Overhead appears mainly in I/O and buffer cache.
Yes. Use NVARCHAR(MAX) and apply OPENJSON, JSON_VALUE, or check constraints to validate JSON format.
DATETIME2 offers a larger date range (0001-9999) and higher precision (100 ns) than DATETIME (1753-9999, ~3 ms). Prefer DATETIME2 for new work.