MySQL TRUNCATE() function
TRUNCATE() function
MySQL TRUNCATE() returns a number after truncated to certain decimal places. The number and the number of decimal places are specified as arguments of the TRUNCATE function.
- TRUNCATE is a fast and efficient way to remove all rows from a table compared to using DELETE with no WHERE clause.
- TRUNCATE is a non-logged operation, meaning it doesn't generate transaction logs for each deleted row.
- Since TRUNCATE is a non-logged operation and doesn't require as much resource overhead as a DELETE, it is significantly faster, especially for very large tables.
- TRUNCATE doesn't fire triggers associated with the table.
- When a table has an auto-incrementing primary key, using TRUNCATE resets the auto-increment counter to its starting value.
- Unlike dropping and re-creating a table, TRUNCATE preserves the table's structure, constraints, indexes, and other attributes.
- When a table is part of a foreign key relationship, using TRUNCATE might be more straightforward compared to using DELETE with cascading delete actions.
Syntax:
TRUNCATE(N, D);
Arguments:
Name | Description |
---|---|
N | A number which is to be truncated up to D decimal places. |
D | A number indicating up to how many decimal places, N is to be truncated. |
Note: When the value of ‘D’ is 0 the results have no fractional part and the ‘D’ digits left of the decimal point of the value ‘N’ become 0 when the value of ‘D’ is negative.
Syntax Diagram:
MySQL Version: 8.0
Example of MySQL TRUNCATE() function
Code:
SELECT TRUNCATE(2.465,1);
Explanation:
The above MySQL statement will return a value truncating 2.465 up to 1 decimal place.
Output:
mysql> SELECT TRUNCATE(2.465,1); +-------------------+ | TRUNCATE(2.465,1) | +-------------------+ | 2.4 | +-------------------+ 1 row in set (0.00 sec)
Example :TRUNCATE() function with negative decimal places
Code:
SELECT TRUNCATE(142.465,-2);
Explanation:
The above MySQL statement will return a value truncating 142.465 up to -2 decimal places.
Output:
mysql> SELECT TRUNCATE(142.465,-2); +----------------------+ | TRUNCATE(142.465,-2) | +----------------------+ | 100 | +----------------------+ 1 row in set (0.00 sec)
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/mysql/mathematical-functions/mysql-truncate-function.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics