Until now you used tables that already existed. This guide teaches you to design and build them: creating a database and tables with CREATE TABLE, choosing data types, and protecting your data with primary keys, foreign keys and constraints. These are the skills that turn a pile of data into a reliable database.
Part of the SQL Server for Beginners series. This article is the written version of lesson 5 of the Bigland Network video course, with the same sample data. The results shown were worked out by hand from that data, so run every example on a test database, not on production data.
Watch lesson 5 as a video or open it on YouTube. The written lesson below follows the same steps and the same sample data.
Contents
- 1. Create a database
- 2. Your first table
- 3. Data types
- 4. Constraints
- 5. Everything in one table
- 6. ALTER and DROP
- 7. Mistakes and best practices
- 8. Practice
1. Create a database
CREATE DATABASE BiglandTraining;
GO
USE BiglandTraining;
GO
CREATE DATABASE makes an empty database and USE switches to it. GO separates batches in SSMS. A script is repeatable and can be saved in a file, unlike clicking through the wizard. Practise on a test database, never on production data.
2. Your first table
CREATE TABLE Departments (
DeptId INT PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL,
Location VARCHAR(50)
);
One line per column: a name, a data type and optional constraints, separated by commas.
3. Common data types
| Type | Use it for |
|---|---|
| INT / BIGINT | Whole numbers (BIGINT for very large ones) |
| DECIMAL(10,2) | Exact decimals such as money: up to 10 digits, 2 after the point |
| VARCHAR(n) | Text up to n characters |
| NVARCHAR(n) | Unicode text: Arabic, French accents and other languages |
| DATE / DATETIME2 | A date, or a date and time |
| BIT | Yes or no (1 or 0) |
4. Constraints that keep data clean
PRIMARY KEY and IDENTITY
A primary key uniquely identifies each row: never NULL, never repeated, one per table. With IDENTITY(1,1) SQL Server generates the numbers, starting at 1 and adding 1.
CREATE TABLE Employees (
Id INT IDENTITY(1,1) PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL
);
INSERT INTO Employees (FirstName) VALUES ('Amina'),('Youssef'),('Salma'); -- Ids 1, 2, 3
NOT NULL
The column must always have a value. Inserting an employee without a first name fails with Cannot insert the value NULL into column ‘FirstName’.
UNIQUE
No two rows may share the value, for example an email. A second row with the same email fails with Violation of UNIQUE KEY constraint. A table can have many UNIQUE constraints, and a unique column may allow one NULL.
DEFAULT
A value used when none is given, for example HireDate DATE DEFAULT GETDATE(). Great for created dates, status columns and counters that start at 0.
CHECK
Validates a value against a rule, for example Salary INT CHECK (Salary >= 0). A negative salary is rejected with conflicted with the CHECK constraint. The rule can be any condition, such as an age between 18 and 65 or a status from a list.
FOREIGN KEY
Links a column to the primary key of another table, so only existing values are accepted. A department Id of 99 is refused when no such department exists, and a department that still has employees cannot be deleted. That is how a database avoids orphan rows.
5. Everything in one table
CREATE TABLE Departments (
DeptId INT PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL
);
CREATE TABLE Employees (
Id INT IDENTITY(1,1) PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE,
HireDate DATE DEFAULT GETDATE(),
Salary INT CHECK (Salary >= 0),
DeptId INT REFERENCES Departments(DeptId)
);
Create Departments first, because Employees refers to it. Now test it:
INSERT INTO Departments VALUES (1,'Sales'),(2,'IT');
INSERT INTO Employees (FirstName, Email, Salary, DeptId)
VALUES ('Amina', 'amina@bigland.com', 4200, 1);
Id becomes 1 and HireDate gets today’s date. Every constraint passed, so the row is accepted.
Named, table-level constraints
CREATE TABLE Projects (
ProjectId INT IDENTITY(1,1),
ProjectName VARCHAR(100) NOT NULL,
EmpId INT NOT NULL,
CONSTRAINT PK_Projects PRIMARY KEY (ProjectId),
CONSTRAINT FK_Projects_Emp FOREIGN KEY (EmpId) REFERENCES Employees(Id)
);
Naming constraints is a best practice: when an error occurs, the message shows the name and you know immediately which rule was broken. Table-level syntax is also the only way to build a key from several columns.
6. ALTER TABLE and DROP TABLE
ALTER TABLE Employees ADD Phone VARCHAR(20);
ALTER TABLE Employees ALTER COLUMN Phone VARCHAR(30);
ALTER TABLE Employees DROP COLUMN Phone;
ALTER TABLE Employees ADD CONSTRAINT UQ_Employees_Email UNIQUE (Email);
ALTER TABLE Employees DROP CONSTRAINT UQ_Employees_Email;
Adding a NOT NULL column to a table that already has rows needs a default, for example ADD Stock INT NOT NULL DEFAULT 0, otherwise SQL Server does not know what to put in the existing rows. ON DELETE CASCADE on a foreign key deletes the child rows automatically when the parent is deleted. It is convenient but dangerous, so use it only when the children cannot exist without the parent.
To inspect a table, query INFORMATION_SCHEMA.COLUMNS or run EXEC sp_help 'Employees';. To remove tables, drop the children first (Projects, then Employees, then Departments), and use DROP TABLE IF EXISTS in scripts to avoid errors.
7. Common mistakes and best practices
- Creating a child table before its parent, so the foreign key fails.
- Storing dates as text or money as
FLOAT, which breaks sorting and calculations. UseDATEandDECIMAL. - Forgetting the primary key and
NOT NULL, which lets duplicate and empty rows in. - Running
DROP TABLEorALTER COLUMNon real data without a backup (How to Back Up and Restore a SQL Server Database with T-SQL). - Best practice: every table gets a primary key; use
NVARCHARfor names that may contain Arabic or accents; name constraints with PK, FK, CK and UQ prefixes; script every change and test it first.
8. Practice
- Create a Products table: identity primary key, required ProductName (100 characters), Price DECIMAL(10,2) above zero, CreatedOn defaulting to today.
- Add a required Stock column of type INT with default 0.
- Create an OrderItems table with a foreign key to Products and a Quantity above zero.
CREATE TABLE Products (
ProductId INT IDENTITY(1,1) PRIMARY KEY,
ProductName VARCHAR(100) NOT NULL,
Price DECIMAL(10,2) CHECK (Price > 0),
CreatedOn DATE DEFAULT GETDATE()
);
ALTER TABLE Products ADD Stock INT NOT NULL DEFAULT 0;
CREATE TABLE OrderItems (
OrderItemId INT IDENTITY(1,1) PRIMARY KEY,
ProductId INT NOT NULL REFERENCES Products(ProductId),
Quantity INT NOT NULL CHECK (Quantity > 0)
);
Frequently asked questions
What is the difference between PRIMARY KEY and UNIQUE?
A primary key is unique and never NULL, and a table has only one. UNIQUE allows many constraints per table and one NULL.
Should I use VARCHAR or NVARCHAR?
Use NVARCHAR when text may contain non-Latin characters such as Arabic. VARCHAR is fine for plain ASCII codes.
Why use DECIMAL instead of FLOAT for money?
FLOAT is approximate and can produce rounding surprises. DECIMAL is exact.
What to learn next
Next, make queries fast and reusable with indexes, views and stored procedures in Lesson 6: Indexes, Views and Stored Procedures. Previous lesson: Lesson 4: INSERT, UPDATE, DELETE and Transactions.
The whole series
- Lesson 1: SELECT, WHERE and ORDER BY
- Lesson 2: JOINs
- Lesson 3: GROUP BY, HAVING and Subqueries
- Lesson 4: INSERT, UPDATE, DELETE and Transactions
- Lesson 5: CREATE TABLE, Data Types and Constraints (this article)
- Lesson 6: Indexes, Views and Stored Procedures
- Lesson 7: CTEs and Window Functions
- Lesson 8: Built-in Functions
- Lesson 9: Functions, Temp Tables and Table Variables
- Lesson 10: Triggers and Audit Tables
- Lesson 11: Security: Logins, Users and Roles
- Lesson 12: Backup, Restore and Recovery Models
- Lesson 13: Query Performance Tuning
- Lesson 14: SQL Server Agent Jobs and Maintenance
- Lesson 15: Encryption and Auditing Basics
- Lesson 16: Working with JSON
- Lesson 17: Temporal Tables and Row History
- Lesson 18: Partitioning and Large Tables
- lesson 19: Full Text Search
- lesson 20: Query Store and Slow Queries
Sources and further reading
- Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for every statement used here.
- Microsoft Learn, SQL Server documentation, for SQL Server Management Studio (SSMS) and the sample concepts.
More tutorials like this
Msg 208 Invalid Object Name in SQL Server: Causes and Fix
Fix SQL Server Msg 208 Invalid object name: check the spelling, the database and the schema, with real SSMS examples and scripts to find…
SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan
Turn on Query Store, find the most expensive queries with the sys.query_store views and the SSMS reports, compare the plans of one query and…
SQL Server Full Text Search Tutorial: CONTAINS, FORMSOF and CONTAINSTABLE
Search words inside text columns fast: create a full text catalog and index, use CONTAINS, word forms, phrases and rank the best matches with…
