CREATE TABLE Statement π¨ΒΆ
Prerequisites: CREATE DATABASE, Data Types
Mentor's Note: A Database is the house, but Tables are the rooms. Each room has a purpose (Kitchen, Bedroom) and specific furniture (Stove, Bed). Similarly, a Table has a purpose (Users, Orders) and specific columns (Name, Price). π‘
π The Scenario: The Spreadsheet Grid πΒΆ
Think of a Table like an Excel Sheet. - Table Name: The Sheet Name (e.g., "Students"). - Columns: The Headers (Roll No, Name, Age). - Rows: The Data (101, 'Rahul', 15).
You must define the headers before you can add any data.
π¨ Visual Logic: Table AnatomyΒΆ
classDiagram
class STUDENTS {
+INT id (PK)
+VARCHAR name
+DATE dob
}
π» 1. The Basic SyntaxΒΆ
Example: Creating a "Students" TableΒΆ
CREATE TABLE students (
student_id INT,
first_name VARCHAR(50),
last_name VARCHAR(50),
birth_date DATE,
email VARCHAR(100)
);
π» 2. Creating with Constraints (Best Practice)ΒΆ
A professional table always has rules (Constraints).
CREATE TABLE employees (
emp_id INT PRIMARY KEY, -- π Unique ID
full_name VARCHAR(100) NOT NULL,-- π€ Mandatory
salary DECIMAL(10, 2), -- π° Money
join_date DATE DEFAULT SYSDATE -- π
Auto-fill today
);
π» 3. Creating a Table from Another TableΒΆ
Sometimes you want to backup data or create a test table with the exact same structure.
π‘ Naming ConventionsΒΆ
- Plural vs Singular:
usersvsuser. (Pick one and stick to it. Plural is common for tables). - Snake_Case:
order_detailsis better thanOrderDetails. - Prefixes: Avoid prefixes like
tbl_users. It's redundant. We know it's a table.