Creating and Managing Tables (DDL)

Introduction

Data Definition Language (DDL) is a subset of SQL used to define and manage database structures. DDL commands help in creating, altering, and deleting database objects like tables, indexes, and views. In this article, we will focus on how to create and manage tables using DDL commands.

1. Creating a Table (CREATE TABLE)

The CREATE TABLE command is used to define a new table along with its columns and data types.

Syntax:

CREATE TABLE table_name (
    column1 datatype constraints,
    column2 datatype constraints,
    ...
);

Example:

Let's create a table named employees with relevant columns.

CREATE TABLE employees (
    emp_id INT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE,
    salary DECIMAL(10,2),
    hire_date DATE
);

Explanation:

  • emp_id is the primary key, ensuring uniqueness.

  • first_name and last_name are required fields (NOT NULL).

  • email must be unique.

  • salary stores decimal values.

  • hire_date holds date values.

2. Modifying a Table (ALTER TABLE)

The ALTER TABLE command allows you to modify an existing table by adding, modifying, or deleting columns.

Adding a Column

ALTER TABLE employees ADD phone_number VARCHAR(15);

Modifying a Column

ALTER TABLE employees MODIFY salary DECIMAL(12,2);

Deleting a Column

ALTER TABLE employees DROP COLUMN phone_number;

3. Deleting a Table (DROP TABLE)

The DROP TABLE command removes a table permanently from the database.

Syntax:

DROP TABLE table_name;

Example:

DROP TABLE employees;

โš  Warning: This command deletes all records and the table structure.

4. Truncating a Table (TRUNCATE TABLE)

The TRUNCATE TABLE command removes all records from a table without deleting the table structure.

Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE employees;

โš  Note: Unlike DELETE, TRUNCATE does not log individual row deletions, making it faster.

Conclusion

DDL commands (CREATE TABLE, ALTER TABLE, DROP TABLE, and TRUNCATE TABLE) are essential for managing database structures. By understanding and applying these commands, you can efficiently create, modify, and delete tables as needed.

Next Steps:

  • Try creating tables in an SQL database.

  • Practice modifying and deleting tables.

  • Learn about indexing for better performance.

Stay tuned for more SQL learning! ๐Ÿš€

ย