- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL CREATE TABLE
The CREATE TABLE statement is the foundation of relational database design. It allows you to define a new table from scratch, acting as a blueprint for how your data will be stored. When you create a table, you aren't just naming it; you are defining the rules (constraints) and the type of data (integers, strings, dates) that each column can hold.
CREATE TABLE script in a production environment, it is good practice to use IF NOT EXISTS (e.g., CREATE TABLE IF NOT EXISTS table_name...). This prevents your script from crashing if the table already exists.
Key Features of SQL CREATE TABLE
- Structural Definition: It establishes the permanent schema for your data.
- Data Integrity: By defining data types (like
INT,VARCHAR, orDATETIME), you ensure that only valid data is saved. - Rules and Relationships: It supports constraints such as
PRIMARY KEYto identify rows andFOREIGN KEYto link tables together.
SQL CREATE TABLE Syntax
The syntax follows a specific pattern: you name the table, then list every column followed by its data type and any optional rules.
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
...
);
Example: Creating a Table
Let's look at a standard real-world scenario: building a table to manage staff information.
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Age INT,
Salary DECIMAL(10,2),
DepartmentID INT
);
In this Employees table, we have defined the following architecture:
ID: An integer that serves as the Primary Key. This means every employee must have a unique ID, and it cannot be empty.Name: A variable-length string. We've set a limit of 100 characters and usedNOT NULLbecause every employee must have a name.Age: A simple integer column.Salary: ADECIMAL(10,2). This is ideal for financial data, allowing up to 10 digits in total with 2 reserved for cents.DepartmentID: An integer used to categorize the employee.
DECIMAL or NUMERIC for currency and financial data. Avoid FLOAT or DOUBLE for money, as they can cause rounding errors that result in lost pennies!
Example: Creating a Table with Constraints
Constraints are rules applied to columns to ensure data quality. In this example, we create a Departments table with a unique constraint.
CREATE TABLE Departments (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50) UNIQUE NOT NULL
);
DeptID: The unique identifier for the department.DeptName: By usingUNIQUE, we ensure that no two departments (like "Accounting") can have the same name.
VARCHAR is important. While it's tempting to use VARCHAR(255) for everything, keeping sizes realistic (like 50 for a name) helps other developers understand the expected data and can slightly improve performance in some database engines.
Creating a Table with a Foreign Key
In relational databases, tables often need to "talk" to each other. A Foreign Key creates a link between two tables, ensuring that you can't add an employee to a department that doesn't exist.
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Age INT,
Salary DECIMAL(10,2),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(DeptID)
);
- The
DepartmentIDin theEmployeestable now points to theDeptIDin theDepartmentstable. This maintains Referential Integrity.
Departments table must exist before you can run the code to create the Employees table.
Checking Table Structure
Once you have created your table, you might want to verify that the columns and types were set up correctly. Commands vary slightly depending on your SQL flavor (MySQL, PostgreSQL, etc.).
For MySQL or MariaDB:
DESCRIBE Employees;
Or use the standard command:
SHOW COLUMNS FROM Employees;
\d Employees in the command line. If you are using SQL Server (T-SQL), you can use exec sp_help Employees; to see the schema details.
Summary
- The
CREATE TABLEstatement is used to define the schema and data types for your database objects. - Use Primary Keys to uniquely identify records and Foreign Keys to create relationships between tables.
- Constraints like
NOT NULLandUNIQUEact as your first line of defense against "dirty" or inconsistent data. - Always double-check your table structure using
DESCRIBEor engine-specific inspection tools after creation.