Data Definition Language (DDL) queries in SQL are used to define, modify, and manage the structure of a database and its objects. DDL statements allow you to create, alter, and delete database schemas, tables, indexes, and other database objects. Here are the key aspects of DDL queries:
CREATE Statement:
The CREATE
statement is used to create new database objects, such as tables, indexes, views, and schemas.
Example: Creating a new table.
sqlCopy code
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE
);
ALTER Statement:
The ALTER
statement is used to modify existing database objects, such as adding, modifying, or deleting columns from a table.
Example: Adding a new column to an existing table.
sqlCopy code
ALTER TABLE employees
ADD email VARCHAR(100);
DROP Statement:
The DROP
statement is used to delete database objects, including tables, indexes, views, and schemas.
Example: Deleting a table.
sqlCopy code
DROP TABLE employees;
TRUNCATE Statement:
The TRUNCATE
statement is used to remove all rows from a table but retains the table structure. It is faster than the DELETE
statement.
Example: Truncating a table.
sqlCopy code
TRUNCATE TABLE employees;
RENAME Statement:
Some database systems support the RENAME
statement, which is used to rename database objects.
Example: Renaming a table (specific syntax may vary by database system).
sqlCopy code
RENAME TABLE old_table TO new_table;
Constraints:
DDL queries allow you to define constraints on tables, such as primary keys, unique constraints, foreign keys, and check constraints.
Example: Adding a primary key constraint.
sqlCopy code
ALTER TABLE employees
ADD CONSTRAINT pk_employee_id PRIMARY KEY (employee_id);
Indexes:
You can create and manage indexes on columns to improve query performance.
Example: Creating an index on a column.
sqlCopy code
CREATE INDEX idx_last_name ON employees (last_name);
Views:
DDL queries are used to create and modify views, which are virtual tables representing data from one or more tables.
Example: Creating a view.
sqlCopy code
CREATE VIEW employee_names AS
SELECT employee_id, CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;
Schemas:
DDL queries allow you to create and manage database schemas, which are containers for organizing database objects.
Example: Creating a schema.
sqlCopy code
CREATE SCHEMA hr;
Transactions:
COMMIT
and ROLLBACK
statements to manage transactions.DQL queries are used to define and manipulate the structure of a database, ensuring that it meets the requirements of the application and adheres to data integrity constraints. Properly defining and maintaining the database schema is crucial for data management and application development.