MSDN Documentation

Relational Databases: Table Creation Tutorial

Introduction to Table Creation

In the world of relational databases, tables are the fundamental building blocks that store your data. They are organized into rows and columns, much like a spreadsheet. Creating tables effectively is crucial for designing a robust and efficient database system. This tutorial will guide you through the process of defining and creating tables, including specifying columns, data types, and essential constraints.

The CREATE TABLE Statement

The primary command used to create a table in SQL (Structured Query Language) is CREATE TABLE. The basic syntax looks like this:

CREATE TABLE table_name ( column1 datatype constraints, column2 datatype constraints, column3 datatype constraints, ... );

Here, table_name is the name you want to give your table, and each column definition specifies its name, its datatype (what kind of data it will hold), and any optional constraints (rules that govern the data in that column).

Defining Columns

Each column within a table must have a name and a data type.

  • Column Names: Should be descriptive and follow naming conventions (e.g., no spaces, start with a letter).
  • Data Types: Determine the type of data a column can store. Common data types include:
    • INT or INTEGER: Whole numbers.
    • VARCHAR(n): Variable-length strings (up to 'n' characters).
    • TEXT: Long strings.
    • DATE: Dates (YYYY-MM-DD).
    • DATETIME or TIMESTAMP: Date and time values.
    • DECIMAL(p, s) or NUMERIC(p, s): Fixed-point numbers where 'p' is the total number of digits and 's' is the number of digits after the decimal point.
    • BOOLEAN: True or false values.

Understanding Data Types

Choosing the correct data type is vital for data integrity and storage efficiency. For example, using INT for age is more appropriate than VARCHAR because it allows for numerical operations and prevents the accidental storage of non-numeric characters.

Adding Constraints

Constraints are rules enforced on data columns. They ensure the accuracy and reliability of data in the database.

Primary Keys

A primary key uniquely identifies each record in a table. A table can have only one primary key, which consists of one or more columns. The values in a primary key column(s) must be unique and cannot be NULL.

CREATE TABLE Products ( ProductID INT PRIMARY KEY, ProductName VARCHAR(255) NOT NULL, Price DECIMAL(10, 2) );

In this example, ProductID is designated as the primary key.

Foreign Keys

A foreign key is a column or set of columns in one table that refers to the primary key in another table. It establishes a link between the two tables, enforcing referential integrity.

CREATE TABLE Orders ( OrderID INT PRIMARY KEY, CustomerID INT, OrderDate DATE, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) );

Here, CustomerID in the Orders table is a foreign key referencing the CustomerID in the (assumed) Customers table.

Unique Constraints

The UNIQUE constraint ensures that all values in a column (or a set of columns) are different. Unlike a primary key, a column with a unique constraint can contain one NULL value.

CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Email VARCHAR(255) UNIQUE, FirstName VARCHAR(50), LastName VARCHAR(50) );

CHECK Constraints

The CHECK constraint is used to limit the range of values that can be placed in a column. It tests each value for a specified condition.

CREATE TABLE Staff ( StaffID INT PRIMARY KEY, FirstName VARCHAR(50), Salary DECIMAL(10, 2), CHECK (Salary >= 30000) );

This ensures that any salary entered must be at least 30000.

Default Values

The DEFAULT constraint inserts a default value into a column when no value is specified during an insert operation.

CREATE TABLE Tasks ( TaskID INT PRIMARY KEY, TaskName VARCHAR(255), Status VARCHAR(50) DEFAULT 'Pending' );

NULL vs. NOT NULL

By default, columns can accept NULL values, which signify missing or unknown data. You can explicitly prevent NULL values by using the NOT NULL constraint.

CREATE TABLE Users ( UserID INT PRIMARY KEY, Username VARCHAR(50) NOT NULL, LastLogin DATETIME );

Here, Username cannot be empty.

Putting It All Together (Example)

Let's create a simple `Customers` table with several constraints.

CREATE TABLE Customers ( CustomerID INT PRIMARY KEY AUTO_INCREMENT, FirstName VARCHAR(50) NOT NULL, LastName VARCHAR(50) NOT NULL, Email VARCHAR(100) UNIQUE, RegistrationDate DATE DEFAULT CURRENT_DATE, AccountBalance DECIMAL(12, 2) CHECK (AccountBalance >= 0) DEFAULT 0.00 );

This table defines a unique customer ID (auto-incrementing), requires first and last names, ensures a unique email address, sets the registration date to the current date by default, and enforces a non-negative account balance with a default of 0.00.

Note: The exact syntax for AUTO_INCREMENT (or IDENTITY in some SQL dialects) and CURRENT_DATE might vary slightly depending on the specific database system you are using (e.g., MySQL, PostgreSQL, SQL Server, Oracle).

Conclusion

Mastering table creation is a fundamental step in database development. By carefully defining your tables, selecting appropriate data types, and implementing robust constraints, you lay the groundwork for a well-structured, reliable, and efficient database. Continue practicing with different scenarios to solidify your understanding.