Data Definition Language (DDL) Statements

Introduction to DDL

Data Definition Language (DDL) statements are used to define, modify, and drop database objects. These statements are crucial for structuring and managing the database schema. DDL commands interact with the database's metadata, affecting the way data is stored and organized.

The primary DDL statements in SQL include:

Core DDL Statements

CREATE Statement

The CREATE statement is used to define new database objects. The syntax varies depending on the object type being created.

CREATE TABLE

Creates a new table in the database. You define the table name, column names, data types, and constraints.


CREATE TABLE Customers (
    CustomerID INT PRIMARY KEY,
    FirstName VARCHAR(50) NOT NULL,
    LastName VARCHAR(50) NOT NULL,
    Email VARCHAR(100) UNIQUE,
    RegistrationDate DATE DEFAULT GETDATE()
);
            

CREATE INDEX

Creates an index on one or more columns of a table to speed up data retrieval operations.


CREATE INDEX IX_Customers_LastName
ON Customers (LastName);
            

CREATE VIEW

Creates a virtual table based on the result-set of an SQL statement.


CREATE VIEW ActiveCustomers AS
SELECT CustomerID, FirstName, LastName
FROM Customers
WHERE RegistrationDate >= DATEADD(year, -1, GETDATE());
            

ALTER Statement

The ALTER statement allows you to modify existing database objects.

ALTER TABLE

Modifies an existing table.


-- Add a new column
ALTER TABLE Customers
ADD Phone VARCHAR(20);

-- Modify an existing column
ALTER TABLE Customers
ALTER COLUMN Email VARCHAR(150);

-- Drop a column
ALTER TABLE Customers
DROP COLUMN Phone;
            

DROP Statement

The DROP statement is used to delete database objects.

DROP TABLE

Deletes a table and all its data.


DROP TABLE Customers;
            

DROP INDEX

Deletes an index.


DROP INDEX IX_Customers_LastName ON Customers;
            

TRUNCATE TABLE

Removes all rows from a table, but the table structure remains intact. It's generally faster and uses fewer system resources than DELETE when removing all rows.


TRUNCATE TABLE Orders;
            

RENAME Statement

Renames an existing database object.


-- Example for SQL Server (syntax might vary slightly across different RDBMS)
EXEC sp_rename 'OldTableName', 'NewTableName';
            

Constraints and DDL

DDL statements are also used to define and manage constraints, which enforce data integrity.

Constraints can be defined when creating a table or added/modified using the ALTER TABLE statement.


-- Adding a foreign key constraint
ALTER TABLE Orders
ADD CONSTRAINT FK_Orders_CustomerID
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);
            

Best Practices

Note: The exact syntax for DDL statements might vary slightly between different database management systems (e.g., SQL Server, PostgreSQL, MySQL, Oracle). This documentation primarily refers to standard SQL and common implementations.