EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

TRUNCATE TABLE MySQL

By Payal UdhaniPayal Udhani

Home » Data Science » Data Science Tutorials » MySQL Tutorial » TRUNCATE TABLE MySQL

TRUNCATE TABLE MySQL

Introduction to TRUNCATE TABLE MySQL

Truncate table command is used in MySQL to delete all the rows present in the particular table of the database. Truncate table does the equal job as that of delete command which is used for deleting the records of the table or sequence of drop table and create table command when considered the output logically. But, what truncate command does internally is that it drops the table and recreates it hence the result returned after successful completion of execution of the truncate command is zero rows affected unline the delete statement that returns the number of rows that were deleted. The zero number of rows affected stands for no information as the output. In this article, we will learn about the working and internals of truncate command and learn its syntax and usage with the help of an example.

Working of TRUNCATE TABLE Statement

Truncate statement is considered as the DDL(Data Definition Language) command and not the DML(Data Manipulation Command). This is because whenever we use this command the table contents are not manipulated instead the whole table is dropped and recreated. Because of this, there are certain points that we should know before using the TRUNCATE statement which is listed below –

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

  • Whenever a TRUNCATE command is executed on the table the trigger defined on delete event is not executed as rows are not deleted the whole table is deleted.
  • We cannot rollback the action of the TRUNCATE TABLE command as it is implicitly committed. However, if any problem occurs while truncating the whole action is rollbacked by MySQL keeping the data intact as previous.
  • If there are any of the activation locks on the table then TRUNCATE TABLE command cannot be executed on it until and unless that lock is unlocked.
  • If there is any of the foreign key defined in other tables on the current table then the current table cannot be truncated as other table’s foreign key is referencing the columns of this table.
  • The output of the execution of the TRUNCATE query is always 0 rows affected which do not specify the number of records deleted instead it stands for no information.
  • All the indexes and data of the table are deleted but the partitions defined on the table remain intact even after truncating the table.
  • The sequence associated with the column which was assigned the AUTO_INCREMENT attribute is reset to the beginning value. This is also valid for the storage engines like InnoDB and MyISAM that do not support reusing of sequence values.
  • We can even truncate an InnoDB table that is corrupted using the TRUNCATE statement.
  • Considering the performance of the TRUNCATE command, it always exceeds the DELETE command performed for all the rows because it skips the DML operations involved in the table manipulation.

Syntax:

The syntax of the TRUNCATE command is as follows –

TRUNCATE [TABLE] name_of_the_table;

The name_of_the_table is the table name that you wish to truncate i.e whose records are to delete keeping the structure of the table intact. The use of the TABLE keyword is optional in syntax. However, it is a good practice to use the TABLe keyword to avoid the confusion between the TRUNCATE command statement and TRUNCATE() function.

The execution of the above statement will lead to the deletion of all the records present in the table and once truncated the action cannot be rollbacked. Hence, one needs to be careful while using this command. If there is any foreign key reference on the table named name_of_the_table then the execution of the command will fail.

Let us consider one example, We will create one table named educba_writers using the following CREATE TABLE command –

CREATE TABLE `educba_writers` (
`id` int(11) NOT NULL,
`firstName` varchar(10) COLLATE latin1_danish_ci NOT NULL,
`rate` decimal(5,2) DEFAULT NULL,
`joining_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_danish_ci;

that gives the following output –

TRUNCATE TABLE MySQL 1

Let us insert some more rows with rate and joining date value –

INSERT INTO `educba_writers` (`id`, `firstName`, `rate`, `joining_date`) VALUES
(1, 'Payal', 750, "2020-05-01"),
(2, 'Vyankatesh', 700, "2020-01-01"),
(3, 'Omprakash', 600, "2020-02-01"),
(4, 'sakshi', 200, "2020-06-01"),
(5, 'prerna', 150, "2020-02-01"),
(6, 'preeti', 350, "2020-06-01"),
(7, 'sanjana', 400, "2020-02-01"),
(8, 'omkar', 450, "2020-06-01"),
(9, 'sohail', 650, "2020-02-01"),
(10, 'soniya', 850, "2020-06-01"),
(11, 'supriya', 700, "2020-02-01"),
(12, 'saniya', 750, "2020-06-01"),
(13, 'omkar', 410, "2020-02-01"),
(14, 'akshay', 910, "2020-06-01"),
(15, 'akash', 730, "2020-02-01"),
(16, 'siddharth', 980, "2020-06-01");

that gives the following output –

TRUNCATE TABLE MySQL 2

Let us retrieve the records of the table educba_writers and confirm the records that exist in the table using the following SELECT query statement –

select * from educba_writers;

that gives the following output after execution –

TRUNCATE TABLE MySQL 3

Let us now truncate the table educba_writers using the TRUNCATE syntax discussed above and the following query statement –

TRUNCATE TABLE educba_writers;

that gives the following output –

TRUNCATE TABLE MySQL 4

As we can see the output of the query execution of truncate command returns that 0 rows are affected even when all the records present in that table are deleted. Let us confirm the deletion of the records of the table by selecting the records of the educba_writers table again using the following query statement –

select * from educba_writers;

that now gives the following output after execution with none of the records present in it –

TRUNCATE TABLE MySQL 5

Hence, we can see that the truncate command worked properly.

Let us insert some records in educba_writers table again –

INSERT INTO `educba_writers` (`id`, `firstName`, `rate`, `joining_date`) VALUES
(1, 'Payal', 750, "2020-05-01"),
(2, 'Vyankatesh', 700, "2020-01-01"),
(3, 'Omprakash', 600, "2020-02-01"),
(4, 'sakshi', 200, "2020-06-01"),
(5, 'prerna', 150, "2020-02-01");

Popular Course in this category
MS SQL Training (13 Courses, 11+ Projects)13 Online Courses | 11 Hands-on Projects | 62+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,653 ratings)
Course Price

View Course

Related Courses
Oracle Training (14 Courses, 8+ Projects)PL SQL Training (4 Courses, 2+ Projects)

TRUNCATE TABLE MySQL 6

ALTER TABLE educba_writers ADD PRIMARY KEY (id)

TRUNCATE TABLE MySQL 7

Now, we will create one more table that will contain foreign key reference on the educba_writers table named books using the below CREATE TABLE query statement –

CREATE TABLE books (
bookId int NOT NULL,
name VARCHAR(100),
rate int NOT NULL,
writerId int,
PRIMARY KEY (bookId),
FOREIGN KEY (bookId) REFERENCES educba_writers(id)
);

TRUNCATE TABLE MySQL 8

and insert the following record in it –

INSERT INTO `books` (`bookId`, `name`, `rate`, `writerId`) VALUES
(1, 'Techniques Of MySQL', 750, 1),
(2, 'Concepts of OOPS', 700, 3);

record 1

Now, we will try truncating the same educba_writers table that we did previously. But now the table has foreign constraints referenced on it by some other table. Hence, we will not be able to truncate the table educba_writers anymore.

TRUNCATE TABLE educba_writers;

record 2

Conclusion

The TRUNCATE command is used in MySQL to delete all the rows of the table in an efficient and faster manner. We can use this command but we need to keep certain things in mind before using it about the behavior of the statement that we discussed previously.

Recommended Articles

This is a guide to TRUNCATE TABLE MySQL. Here we discuss the introduction, syntax, Working of TRUNCATE TABLE Statement respectively. You may also have a look at the following articles to learn more –

  1. MySQL Data Type
  2. MySQL INSERT IGNORE
  3. MySQL Create Function
  4. MySQL Lock Table

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
MySQL Tutorial
  • Functions
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL count()
    • MIN() in MySQL
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • TRUNCATE TABLE MySQL
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL 
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT 
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL COALESCE
    • MySQL Cluster
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Basic
    • Introduction to MySQL
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • How To Install MySQL
    • MySQL OpenSource
    • MySQL Commands
    • Views in MySQL
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL UUID
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL Transaction
    • MySQL sort_buffer_size
    • MySQL Sync
    • MySQL Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - MS SQL Certification Courses Learn More