Skip to content

Latest commit

 

History

History
93 lines (75 loc) · 1.99 KB

DDL.md

File metadata and controls

93 lines (75 loc) · 1.99 KB

Data Definition Language (DDL)

  • Define, modify, or delete the structure of the database objects (tables, views, indexes).
  • All the commands of DDL are auto-committed (Permanently save all the changes in the database)

CREATE | ALTER | DROP | TRUNCATE

CREATE

# Create Schema:
CREATE SCHEMA IF NOT EXISTS SchemaName;
# Create Table:
CREATE TABLE Employee
(
    Employee_ID INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,  # IDENTITY(1,1) Start from 1 and Increment by 1 
    FirstName   NVARCHAR(60),
    LastName    NVARCHAR(60),
    Email       NVARCHAR(60)
);
# Create View:
CREATE VIEW Staff_View AS
SELECT s.ID, s.LastName, cd.Company
FROM Staff s
LEFT JOIN Company_Division cd
ON s.Department = cd.Department;
# Create Index:
CREATE INDEX idx_staff_last_name
ON Staff
USING (Last_Name);

ALTER

  • Alter/Modify/Change table structure (data type, column names, add or drop columns).
  • Either to modify the characteristics of an existing attribute or probably to add a new attribute.
# Drop Column:
ALTER TABLE Employee
DROP COLUMN Email;
# Add new columns:
ALTER TABLE Employee
ADD Age INT, Department NVARCHAR(50);
# Modify the size and data type:
ALTER TABLE Employee
ALTER COLUMN Country NVARCHAR(30);
# Rename table name:    
ALTER TABLE table_name
RENAME TO new_table_name;    
# Rename column name:
ALTER TABLE table_name
RENAME COLUMN old_name TO new_name;   

DROP

# Delete the entire table data including structure and constraints.
DROP TABLE Employee;

TRUNCATE

# Delete data from the table, while retaining the structure of the table.
TRUNCATE TABLE Employee
DROP COLUMN Email;