Mastering SQL: The Ultimate Guide to Querying and Managing Relational Databases

0 0 0 0 0

📘 Chapter 2: Data Definition Language (DDL)

🧠 What is DDL?

Data Definition Language (DDL) is a subset of SQL used to define and manage the structure of database objects, such as:

  • Databases
  • Tables
  • Columns
  • Indexes
  • Constraints

Unlike DML (Data Manipulation Language), which deals with data, DDL deals with the structure of the database itself.


🔧 Key DDL Commands

Command

Description

CREATE

Creates databases, tables, views

ALTER

Modifies existing database objects

DROP

Deletes database objects permanently

TRUNCATE

Removes all data from a table

RENAME

Changes name of table/column


📦 1. CREATE – Creating Database Objects

Creating a Database

sql

 

CREATE DATABASE SchoolDB;


Creating a Table

sql

 

CREATE TABLE Students (

    StudentID INT PRIMARY KEY,

    Name VARCHAR(100),

    Age INT,

    EnrollmentDate DATE

);

🔹 Data Types

Data Type

Description

INT

Integer numbers

VARCHAR(n)

Text with a limit

DATE

Stores dates

DECIMAL(10,2)

Numeric with precision (money, etc.)


Table with Constraints

sql

 

CREATE TABLE Courses (

    CourseID INT PRIMARY KEY,

    Title VARCHAR(100) NOT NULL,

    CreditHours INT CHECK (CreditHours > 0),

    DepartmentID INT,

    FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)

);


🧱 2. ALTER – Modifying Table Structure

Add a Column

sql

 

ALTER TABLE Students

ADD Email VARCHAR(150);


Modify a Column

sql

 

ALTER TABLE Students

MODIFY Age TINYINT;

Note: Syntax may vary (e.g., MODIFY for MySQL, ALTER COLUMN in SQL Server/PostgreSQL).


Drop a Column

sql

 

ALTER TABLE Students

DROP COLUMN Email;


Rename a Table

sql

 

ALTER TABLE Students

RENAME TO StudentInfo;


🗑️ 3. DROP – Removing Objects

Drop a Table

sql

 

DROP TABLE Students;

  • Completely deletes structure and all data.
  • Cannot be rolled back in most RDBMS.

Drop a Database

sql

 

DROP DATABASE SchoolDB;

️ Use caution—this removes all tables and data in the database.


🔄 4. TRUNCATE – Clearing Table Data

Clear All Rows (Preserve Structure)

sql

 

TRUNCATE TABLE Students;

Feature

TRUNCATE

Deletes Rows

Yes (All)

Keeps Table

Yes

Rollback

Not always supported

Fast Operation

Yes (No logging of each row)


🧩 5. Constraints in DDL

Constraints enforce rules at the table level.

🔹 Types of Constraints

Constraint

Description

PRIMARY KEY

Unique identifier for rows

FOREIGN KEY

Connects rows between tables

UNIQUE

Ensures all values in a column are unique

NOT NULL

Column must have a value

CHECK

Restricts values in a column (e.g., Age > 0)

DEFAULT

Assigns a default value if none is provided


Example with All Constraints

sql

 

CREATE TABLE Employees (

    EmpID INT PRIMARY KEY,

    Name VARCHAR(50) NOT NULL,

    Salary DECIMAL(10, 2) CHECK (Salary > 0),

    JoinDate DATE DEFAULT CURRENT_DATE,

    DepartmentID INT,

    FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)

);


🔍 6. Viewing Table Schema

Describe Table (MySQL / Oracle)

sql

 

DESCRIBE Students;


Using INFORMATION_SCHEMA (Standard SQL)

sql

 

SELECT column_name, data_type, is_nullable

FROM information_schema.columns

WHERE table_name = 'Students';


🧪 Practice Exercise

sql

 

-- Create a department table

CREATE TABLE Departments (

    DepartmentID INT PRIMARY KEY,

    DepartmentName VARCHAR(50) UNIQUE NOT NULL

);

 

-- Alter table: Add phone number

ALTER TABLE Departments

ADD Phone VARCHAR(20);

 

-- Create table referencing foreign key

CREATE TABLE Professors (

    ProfessorID INT PRIMARY KEY,

    Name VARCHAR(100),

    DepartmentID INT,

    FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)

);

 

-- Truncate data from table

TRUNCATE TABLE Professors;

 

-- Drop a table

DROP TABLE Professors;


📚 Real-World Scenarios for DDL

Scenario

SQL Action

Launching a new app

CREATE TABLE for all entities

Changing a feature requirement

ALTER TABLE to add/remove column

Deleting a failed test module

DROP TABLE

Resetting table data

TRUNCATE TABLE

Enforcing rules

Constraints like CHECK, FK, etc.


Summary Table


Command

Purpose

CREATE

Define new tables/databases

ALTER

Modify existing table structure

DROP

Remove tables or databases

TRUNCATE

Quickly delete all rows in a table

CONSTRAINT

Enforce rules on data integrity

Back

FAQs


1. Q: Is SQL a programming language?

A: SQL is a query language, not a general-purpose programming language. It’s used to communicate with databases.

2. Q: What's the difference between SQL and MySQL?

A: SQL is a language. MySQL is a database management system (DBMS) that uses SQL.

3. Q: Can SQL be used with Python or Java?

A: Yes. Libraries like JDBC (Java) or sqlite3/sqlalchemy (Python) allow SQL integration.

4. Q: What is a JOIN in SQL?

A: A JOIN combines rows from two or more tables based on a related column between them.

5. Q: What is normalization?

A: The process of structuring data to reduce redundancy and improve integrity.

6. Q: What’s the difference between WHERE and HAVING?

A: WHERE filters rows before aggregation. HAVING filters groups after aggregation.

7. Q: Is SQL case-sensitive?

A: SQL keywords are case-insensitive, but string comparisons may be case-sensitive, depending on the DBMS.

8. Q: Can SQL handle big data?

A: SQL can handle moderate volumes. For large-scale datasets, use SQL-based engines like Presto, Hive, or BigQuery.

9. Q: What is a view in SQL?

A: A view is a virtual table based on the result of a query. It doesn't store data itself.

10. Q: How do I prevent SQL injection?

A: Use parameterized queries or prepared statements instead of dynamic SQL strings