Roadmap › SQL Server & T-SQL › Module: Database Design
Lessons in this course (19)
1. Keys, constraints and data types
Basic★ Must knowLesson 1 of 19
sql
CREATE TABLE dbo.Departments (
DeptId INT IDENTITY(1,1) CONSTRAINT PK_Departments PRIMARY KEY,
DeptName NVARCHAR(100) NOT NULL CONSTRAINT UQ_Departments_Name UNIQUE
);
CREATE TABLE dbo.Employees (
EmpId INT IDENTITY(1,1) PRIMARY KEY, -- clustered by default
FullName NVARCHAR(150) NOT NULL,
Email VARCHAR(200) NOT NULL UNIQUE,
DeptId INT NULL REFERENCES dbo.Departments(DeptId), -- foreign key
ManagerId INT NULL REFERENCES dbo.Employees(EmpId), -- self-reference
Salary DECIMAL(12,2) NOT NULL CHECK (Salary > 0),
HireDate DATE NOT NULL DEFAULT (CAST(GETDATE() AS DATE)),
IsActive BIT NOT NULL DEFAULT 1,
RowVer ROWVERSION
);| Key/constraint | Meaning |
|---|---|
| Primary key | Unique + NOT NULL; one per table; clustered index by default |
| Candidate key | Any column set that could be the PK |
| Alternate key | Candidate key not chosen as PK (enforce with UNIQUE) |
| Composite key | PK of several columns |
| Surrogate key | System-generated (IDENTITY, SEQUENCE, GUID) |
| Natural key | Business value (PAN, email) |
| Foreign key | References a PK/unique key; enforces referential integrity |
| UNIQUE | No duplicates (allows one NULL in SQL Server) |
| CHECK / DEFAULT / NOT NULL | Domain rules |
Types: INT/BIGINT, DECIMAL(p,s) for money (avoid FLOAT), VARCHAR (1 byte/char, non-Unicode) vs NVARCHAR (Unicode), DATE, DATETIME2 (prefer over DATETIME), DATETIMEOFFSET, BIT, UNIQUEIDENTIFIER, VARBINARY(MAX).