This article is shared from Huawei Cloud Community " GaussDB Database SQL Series-DROP & TRUNCATE & DELETE ", author: Gauss Squirrel Club Assistant 2.
I. Introduction
In the database, SQL, as a commonly used database programming language, plays a vital role. SQL can not only be used to create, modify, and query databases, but can also delete data through statements such as DROP, DELETE, and TRUNCATE. These statements are the most commonly used commands in the SQL language, and they have different meanings and usage scenarios.
This article uses the GaussDB database as a platform to introduce in detail the meaning, usage scenarios, and precautions of statements such as DROP, TRUNCATE, and DELETE in SQL, helping readers better understand and master these commonly used database operation commands.
2. Brief description of DROP & TRUNCATE & DELETE of GaussDB
1. Brief description
• The DROP statement can delete the entire table, including table structure and data;
• The TRUNCATE statement can quickly delete all data in the table, but does not delete the table structure.
• The DELETE statement can delete data in the table, excluding the table structure;
2. Command comparison
Category |
DROP |
TRUNCATE |
DELETE |
SQL type |
DDL |
DDL |
DML |
Remove content |
Delete all data in the table, including table structure, indexes, permissions, etc. |
Delete all data in the table, or data in a specified partition |
Delete all or part (+condition) data of a table |
Execution speed |
fastest |
medium speed |
slowest |
Tip: In the GaussDB database, DROP is one of the commands used to define or modify objects in the database. The objects mainly include: libraries, schemas, table spaces, tables, indexes, views, stored procedures, functions, encryption keys, etc. This time we only focus on operations on tables.
3. GaussDB DROP TABLE command and examples
1. Function description
The function of DROP TABLE is to delete an existing Table.
2. Grammar
DROP TABLE [IF EXISTS] [db_name.]table_name;
Note: Adding [IF EXISTS] to SQL can prevent execution errors caused by the table not existing.
Parameters: db_name: Database name. If not specified, the current database will be selected. table_name: The name of the Table to be deleted.
3. Example
The following example demonstrates the use of the DROP command and executes the following SQL statements in sequence:
--Delete the entire table course DROP TABLE IF EXISTS course --Create course table CREATE TABLE course(cid VARCHAR(10),cname VARCHAR(10),teid VARCHAR(10)); --Initialize data INSERT INTO course VALUES('01 ' , 'Chinese' , '02'); INSERT INTO course VALUES('02' , 'Mathematics' , '01'); INSERT INTO course VALUES('03' , 'English' , '03'); --3 records SELECT count(1) FROM course; --Delete the entire table DROP TABLE IF EXISTS course --View the results, the table does not exist (the table structure and data do not exist) SELECT count(1) FROM course;
1) DROP TABLE, prompting that the table does not exist
2) Create and initialize an experiment table
3) DROP TABLE was executed successfully
4) View execution results
4. TRUNCATE command and examples of GaussDB
1. Function description
Remove all data from a table or table partition, TRUNCATE quickly deletes all rows from the table. It has the same effect as performing an unconditional DELETE on the target table, but because TRUNCATE does not perform a table scan, it is much faster and uses less system and transaction log resources. The operation effect is more obvious on large tables.
TRUNCATE TABLE deletes all rows in the table, but leaves the table structure with its columns, constraints, indexes, etc. unchanged. The count used to identify new rows is reset to the seed of that column.
2. Grammar
TRUNCATE [TABLE] table_name;
or
ALTER TABLE [IF EXISTS] table_name TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) }
Parameters: table_name: The name of the Table whose data needs to be deleted. partition_name: The partition name of the partition table that needs to be deleted. partition_value: The partition value of the partition table that needs to be deleted.
3. Example 1
The following example demonstrates the use of the TRUNCATE command:
--Create course table DROP TABLE IF EXISTS course; CREATE TABLE course(cid VARCHAR(10),cname VARCHAR(10),teid VARCHAR(10)); --Initialize data INSERT INTO course VALUES('01', 'Chinese' , '02'); INSERT INTO course VALUES('02' , 'Math' , '01'); INSERT INTO course VALUES('03' , 'English' , '03'); --3 records SELECT count( 1) FROM course; --Clear the table TRUNCATE TABLE course; --or TRUNCATE course; --0 records SELECT count(1) FROM course;
1) Create an experiment table and initialize the data
2) TRUNCATE TABLE is executed successfully
3) View execution results
4. Example 2
The following example demonstrates the TRUNCATE command to delete partition table data
--创建列表分区(LIST) DROP TABLE IF EXISTS orders; CREATE TABLE orders ( id INT PRIMARY KEY, customer_id INT, order_date DATE, product_id INT, quantity INT ) PARTITION BY LIST (customer_id) ( PARTITION p1 VALUES (100), PARTITION p2 VALUES (200), PARTITION p3 VALUES (300), PARTITION p4 VALUES (400), PARTITION p5 VALUES (500) ); --插入测试数据 INSERT INTO orders(id,customer_id,order_date,product_id,quantity)VALUES(1001,100,date'20230822',1,10); INSERT INTO orders(id,customer_id,order_date,product_id,quantity)VALUES(1002,100,date'20230822',2,20); INSERT INTO orders(id,customer_id,order_date,product_id,quantity)VALUES(1003,100,date'20230822',3,30); INSERT INTO orders(id,customer_id,order_date,product_id,quantity)VALUES(1004,200,date'20230822',4,40); --查看分区p1、p2的数据 SELECT * FROM orders WHERE customer_id IN (100,200); --或 --根据分区名称查询 SELECT * FROM orders PARTITION(p2); --清空分区p1。 ALTER TABLE orders TRUNCATE PARTITION p1; --或者 --清空分区p2=200。 ALTER TABLE orders TRUNCATE PARTITION for (200); --查看分区p1、p2的数据 SELECT * FROM orders WHERE customer_id IN (100,200);
1) Create an experiment table and initialize it
2) Delete data according to partition
5. GaussDB DELETE command and examples
1. Function description
Delete rows that satisfy the WHERE clause from the specified table. If the WHERE clause does not exist, all rows in the table will be deleted, leaving only the table structure.
2. Things to note
• LIMIT is not supported in DELETE statements. A WHERE condition should be used to specify the target row that needs to be updated.
• Deleting multiple tables in a single SQL statement is not supported.
• The DELETE statement must have a WHERE clause to avoid a full table scan.
• It is forbidden to use ORDER BY and GROUP BY clauses in the DELETE statement to avoid unnecessary sorting.
• If you need to clear a table, it is recommended to use TRUNCATE instead of DELETE.
• TRUNCATE will create a new physical file and physically delete the original file at the end of the transaction to clear the disk space. DELETE will mark the data in the table, and the disk space will not be actually cleared until the VACCUUM FULL stage.
• DELETE a table with a primary key or index. The WHERE condition should be combined with the primary key or index to improve execution efficiency.
• The DELETE statement deletes one row at a time and records an entry in the transaction log for each row deleted.
• If you want to retain the ID count value, use DELETE instead
3. Grammar
DELETE FROM table_name [WHERE condition];
Parameters: table_name: The name of the Table whose data needs to be deleted. condition: used to determine which rows need to be deleted.
4. Example
Reuse the previous experiment table:
1) Delete all data with customer_id <200 in the orders table:
DELETE FROM orders WHERE customer_id <200;
6. Application scenarios
• When data needs to be deleted based on certain business conditions, and the data volume and performance are controllable, you can consider using DELETE.
• TRUNCATE can be used when a large amount of data needs to be deleted with fast speed, high efficiency and no need to undo it.
• In enterprise-level development, logical deletion (data is "marked for deletion") is actually performed instead of physical deletion.
• In actual production environments, data in business processing (transition tables) is generally deleted.
• In the actual enterprise development and maintenance process, data backup must be considered before using DELETE, TRUNCATE or DROP commands.
7. Summary
In databases such as GaussDB, DROP, TRUNCATE and DELETE are commonly used commands to delete data. However, in actual business use, accurate choices need to be made based on different needs. However, no matter which data deletion method is chosen, data security needs to be considered - important things must be said three times: backup ! Back up! Back up!
Click to follow and learn about Huawei Cloud’s new technologies as soon as possible~
Alibaba Cloud suffered a serious failure, affecting all products (has been restored). The Russian operating system Aurora OS 5.0, a new UI, was unveiled on Tumblr. Many Internet companies urgently recruited Hongmeng programmers . .NET 8 is officially GA, the latest LTS version UNIX time About to enter the 1.7 billion era (already entered) Xiaomi officially announced that Xiaomi Vela is fully open source, and the underlying kernel is .NET 8 on NuttX Linux. The independent size is reduced by 50%. FFmpeg 6.1 "Heaviside" is released. Microsoft launches a new "Windows App"