📅  最后修改于: 2023-12-03 15:33:01.466000             🧑  作者: Mango
MySQL DDL - SQL refers to the Data Definition Language (DDL) statements used in MySQL to define and manipulate database objects. DDL statements are used to create, modify, and delete database objects such as tables, indexes, views, and stored procedures. As a programmer, it is essential to have an understanding of MySQL DDL - SQL to develop efficient and robust database applications.
To create a table in MySQL, we use the CREATE TABLE
statement. The basic syntax for creating a table is as follows:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
...
table_constraint
);
Here, table_name
is the name of the table, column1
, column2
, column3
, and so on are the names of the columns in the table, datatype
is the data type of the column, and constraint
specifies any constraints on the column. table_constraint
is an optional constraint that can be added to the whole table.
Here is an example of creating a table called users
with the columns id
, name
, email
, and password
:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
password VARCHAR(255) NOT NULL
);
In this example, we have added AUTO_INCREMENT
to the id
column, making it the primary key. We have also added NOT NULL
to the name
and password
columns to ensure that they are not empty, and UNIQUE
to the email
column to ensure that no two users have the same email address.
To modify a table, we use the ALTER TABLE
statement. The basic syntax for altering a table is as follows:
ALTER TABLE table_name action;
Here, table_name
is the name of the table, and action
is the modification we want to make. There are several actions we can perform using the ALTER TABLE
statement, such as adding a column, dropping a column, modifying a column, and so on.
Here is an example of adding a new column 'phone_number' in the 'users' table:
ALTER TABLE users ADD phone_number VARCHAR(20) AFTER email;
In this example, 'phone_number' column is added after the 'email' column.
To delete a table from the database, we use the DROP TABLE
statement. The basic syntax for dropping a table is as follows:
DROP TABLE table_name;
Here, table_name
is the name of the table that we want to delete.
MySQL DDL - SQL is an essential part of MySQL that allows programmers to manipulate database objects. By understanding how to create, modify, and delete tables, we can develop efficient and robust database applications.