CREATE TABLE
CREATE TABLE
Section titled βCREATE TABLEβWhat it means
Section titled βWhat it meansβCREATE TABLE defines a new table β its columns, each columnβs data type, and any constraints. Itβs the foundational DDL (Data Definition Language) statement for setting up a database schema.
Examples
Section titled βExamplesβCREATE TABLE Employees ( Id INT PRIMARY KEY IDENTITY(1,1), -- auto-incrementing primary key FirstName NVARCHAR(50) NOT NULL, LastName NVARCHAR(50) NOT NULL, Email NVARCHAR(255) UNIQUE, HireDate DATE NOT NULL DEFAULT GETDATE(), Salary DECIMAL(10,2) CHECK (Salary > 0), DepartmentId INT, CONSTRAINT FK_Employees_Departments FOREIGN KEY (DepartmentId) REFERENCES Departments(Id));Common mistake
Section titled βCommon mistakeβChoosing VARCHAR for text that might contain non-English characters β VARCHAR only stores single-byte characters, so names, addresses, or content in most non-Latin scripts get corrupted or truncated. NVARCHAR (Unicode) is the safer default unless you have a specific, deliberate reason to use VARCHAR.
CREATE TABLE Users ( Name VARCHAR(50) -- 'JosΓ©' or 'η°δΈ' may not store correctly);
-- Better default: NVARCHAR handles Unicode text correctlyCREATE TABLE Users ( Name NVARCHAR(50));Quick practice
Section titled βQuick practiceβ-
What does
IDENTITY(1,1)on a column mean?Answer
The column auto-increments β starting at 1, incrementing by 1 for each new row β and doesn't need to be specified inINSERTstatements. -
Whatβs the risk of using
VARCHARinstead ofNVARCHARfor names or free text?Answer
VARCHARonly supports single-byte characters, so non-Latin-script text (accented characters, Chinese, Arabic, etc.) can be corrupted or fail to store correctly;NVARCHARstores Unicode properly. -
What does
DEFAULT GETDATE()on a column do?Answer
Automatically fills that column with the current date/time if no explicit value is provided in theINSERTstatement.