Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TRUNCATE table only if it exists (to avoid errors)

Tags:

mysql

truncate

I have a .sql file that clear cached data in a mysql schema before export because the cached data in these tables is useless when I import the export file to a different server. I use this script on multiple sites, but in some instances certain table don't exist because they are not required. How do I only truncate a table in MySQL if only that table exist?

TRUNCATE accesslog;
TRUNCATE cache;
TRUNCATE cache_block;
TRUNCATE cache_bootstrap;
TRUNCATE cache_customfilter;
TRUNCATE cache_field;
TRUNCATE cache_filter;
TRUNCATE cache_form;
TRUNCATE cache_image;
TRUNCATE cache_menu;
TRUNCATE cache_metatag;
TRUNCATE cache_page;
TRUNCATE cache_path;
TRUNCATE cache_token;
TRUNCATE cache_update;
TRUNCATE cache_views;
TRUNCATE cache_views_data;
TRUNCATE watchdog;

Thanks in advance.

like image 326
Desmond Liang Avatar asked Aug 19 '14 23:08

Desmond Liang


People also ask

What is true about TRUNCATE table?

The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.

What is the disadvantage of using TRUNCATE in SQL?

TRUNCATE TABLE doesn't log the transaction. That means it is lightning fast for large tables. The downside is that you can't undo the operation. DELETE FROM logs each row that is being deleted in the transaction logs so the operation takes a while and causes your transaction logs to grow dramatically.

Why do we TRUNCATE a table?

Typically, TRUNCATE TABLE quickly deletes all records in a table by deallocating the data pages used by the table. This reduces the resource overhead of logging the deletions, as well as the number of locks acquired. Records removed this way cannot be restored in a rollback operation.


2 Answers

See this answer on Using the IF Statement to do a conditional insert:

Can you do the same using the ANSI INFORMATION_SCHEMA

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'accesslog')
    TRUNCATE accesslog
like image 86
Preet Sangha Avatar answered Sep 28 '22 11:09

Preet Sangha


You can try this stored procedure as it is really difficult without it.

CREATE PROCEDURE tbl_delete(IN table_name CHAR(255),IN database_name CHAR(255))
BEGIN
    IF @table_name IN (SELECT table_name FROM information_schema.tables WHERE table_schema = database_name)
    THEN
        SET @query = CONCAT("TRUNCATE TABLE ", @database_name, ".", @table_name);
        PREPARE stmt FROM @query;
        EXECUTE stmt;
    END IF;
END ;
like image 29
Prabhjot Singh Kainth Avatar answered Sep 28 '22 11:09

Prabhjot Singh Kainth