- 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 used to create a new table in a database. It defines the table structure, including column names, data types, and constraints.
Key Features of SQL CREATE TABLE
- Creates a new table with specified columns.
- Defines column data types (e.g.,
INT
,VARCHAR
,DATE
). - Supports constraints (
PRIMARY KEY
,NOT NULL
,UNIQUE
,FOREIGN KEY
).
SQL CREATE TABLE Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
...
);
Example: Creating a Table
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Age INT,
Salary DECIMAL(10,2),
DepartmentID INT
);
This creates an Employees
table with:
ID
: Primary key (unique and required).Name
: String (max 100 characters), cannot beNULL
.Age
: Integer.Salary
: Decimal with 10 digits and 2 decimal places.DepartmentID
: Integer.
Example: Creating a Table with Constraints
CREATE TABLE Departments (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50) UNIQUE NOT NULL
);
DeptID
: Primary key.DeptName
: Unique, cannot beNULL
.
Creating a Table with a Foreign Key
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)
);
DepartmentID
referencesDeptID
in theDepartments
table.
Checking Table Structure
To view table details:
DESCRIBE Employees;
or
SHOW COLUMNS FROM Employees;
Summary
CREATE TABLE
defines a new table structure.- Use primary keys, foreign keys, and constraints for data integrity.
- Use
DESCRIBE
orSHOW COLUMNS
to check table structure.