SQL Data Definition Language - RamNayakTech/knowledge-hub GitHub Wiki

Here are the key topics related to SQL DDL:

1. CREATE

  • CREATE TABLE: Used to create a new table in the database.
    CREATE TABLE table_name (
        column1 datatype PRIMARY KEY,
        column2 datatype,
        column3 datatype
    );
    
  • CREATE DATABASE: Creates a new database.
    CREATE DATABASE database_name;
    
  • CREATE INDEX: Creates an index on a table.
    CREATE INDEX index_name
    ON table_name (column_name);
    
  • CREATE VIEW: Creates a virtual table (view) based on the result set of a SELECT query.
    CREATE VIEW view_name AS
    SELECT column1, column2
    FROM table_name
    WHERE condition;
    

2. ALTER

  • ALTER TABLE: Used to modify an existing table's structure.
    • Add a new column:
      ALTER TABLE table_name
      ADD column_name datatype;
      
    • Modify an existing column:
      ALTER TABLE table_name
      MODIFY COLUMN column_name datatype;
      
    • Drop a column:
      ALTER TABLE table_name
      DROP COLUMN column_name;
      

3. DROP

  • DROP TABLE: Deletes an existing table and its data.
    DROP TABLE table_name;
    
  • DROP DATABASE: Deletes an entire database and its data.
    DROP DATABASE database_name;
    
  • DROP INDEX: Deletes an index.
    DROP INDEX index_name ON table_name;
    
  • DROP VIEW: Deletes a view.
    DROP VIEW view_name;
    

4. TRUNCATE

  • TRUNCATE TABLE: Removes all rows from a table without logging individual row deletions. It's faster than the DELETE statement for large tables.
    TRUNCATE TABLE table_name;
    

5. RENAME

  • RENAME TABLE: Changes the name of a table.
    RENAME TABLE old_table_name TO new_table_name;
    

Example:

Here's a combined example of creating, altering, and dropping a table:

-- Create a table
CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    DepartmentID INT
);

-- Alter the table to add a new column
ALTER TABLE Employees
ADD DateOfBirth DATE;

-- Drop the table
DROP TABLE Employees;