CREATE TABLE Statement 🔨¶
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.