Usage of DML statements (MySQL)


Preface

This article mainly introduces the usage of DML statements in SQL statements.
Before starting the experiment, we first create the table to be used, as shown in the figure below:
Insert image description here


1. Introduction to DML

DML statements are used to add, delete, and modify data records in tables in the database.

  • Add data (INSERT)
  • Modify data (UPDATE)
  • Delete data (DELETE)

2. DML statement operation

1. Add data to the specified field

insert into 表名 (字段名1,字段名2...) values(1,2...);

Add a set of data with id 1 and name Zhang San to the characters table, as shown in the figure below:
Insert image description here
We can query the data we just inserted through a query SQL statement.

select * from 表名;

Insert image description here
It can be seen that we have successfully inserted the data.

In addition to adding data to all fields, this command can also add data to specified fields. As shown in the figure below, we first add 45 to the id, and then add Li Si to the name. The fields that have not been added are displayed as NULL.
Insert image description here

2. Add data to all fields

insert into 表名 values (1,2,...);

Add a data with id equal to 1 and name Wangwu as shown below:
Insert image description here

3. Add data in batches

insert into 表名 (字段名1,字段名2,...) values(1,2,...),
(1,2,...),(1,2,...);

or

insert into 表名 values (1,2,...),(1,2,...),(1,2,...);

For example, insert some data in batches, as shown in the figure below:

Insert image description here
Precautions:

  • When inserting data, the order of the specified fields needs to correspond to the order of the values.
  • String and date data should be enclosed in quotes.
  • The size of the inserted data should be within the specified range of the field.

4. Modify data

update 表名 set 字段名1 =1,字段名 2 =2,...[where 条件];

Modify the data with ID 1 and change the name to Mazi, as shown in the figure below:
Insert image description here
Modify all the IDs to 1, as shown in the figure below:
Insert image description here
Note: The conditions for modifying the statement may or may not be present. If there are no conditions, All data in the entire table will be modified.

5. Delete data

delete from 表名 [where 条件];

Delete the data id=1, name='Mazi', as shown in the figure below:
Insert image description here
Note:

  • When you want to delete multiple conditions, you can use and and or to connect the conditions.
  • The conditions of the delete statement may or may not exist. If there are no conditions, all data in the entire table will be deleted.
  • The delete statement cannot delete the value of a certain field (you can use update to set the field to NULL).

Summarize

This article mainly introduces the usage of DML statements in SQL statements. I hope it can be helpful to you.

Guess you like

Origin blog.csdn.net/weixin_63614711/article/details/132461064