CREATE Statement
The CREATE
statement is used to create new database objects like tables, views, and indexes. It allows you to define columns, data types, and constraints for the table.
Examples of Using CREATE
Example 1: Creating a Simple Table
CREATE TABLE SocialActivists (
ActivistID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Contribution VARCHAR(100),
BirthDate DATE
);
Output:
Table SocialActivists
created successfully.
Example 2: Creating a Table with Constraints
CREATE TABLE FreedomFighters (
FighterID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
City VARCHAR(50) UNIQUE,
BirthDate DATE CHECK (BirthDate < '2000-01-01'),
Contribution TEXT
);
Output:
Table FreedomFighters
created successfully with constraints.
Explanation of Constraints
Constraint | Description |
---|---|
PRIMARY KEY | Ensures each record has a unique identifier. |
NOT NULL | Prevents NULL values in the specified column. |
UNIQUE | Ensures all values in the column are unique. |
CHECK | Sets a condition for values in the column. |
Do's and Don'ts
Do's
- Use meaningful and descriptive names for tables and columns.
- Define constraints like
PRIMARY KEY
andNOT NULL
to maintain data integrity. - Plan your table structure in advance to avoid frequent alterations.
Don'ts
- Don't use reserved SQL keywords as table or column names.
- Don't leave critical columns without constraints, as it may lead to data inconsistencies.
- Don't create tables with unnecessary columns that may bloat your database.