Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: IF EXISTS ... TRUNCATE

Tags:

mysql

Want to truncate a table if it exists:

IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'mytable') TRUNCATE mytable

Error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'mytable') ' at line 1

I tried also to add THEN after ) but the problems seems to be at IF.

like image 369
b4154 Avatar asked Dec 03 '15 10:12

b4154


People also ask

Is truncate faster than delete?

TRUNCATE is faster than DELETE , as it doesn't scan every record before removing it. TRUNCATE TABLE locks the whole table to remove data from a table; thus, this command also uses less transaction space than DELETE .


2 Answers

You need the two statements below to do that:

create table if not exists <mytable>;

truncate table <mytable>;
like image 197
Thanos Markou Avatar answered Nov 19 '22 21:11

Thanos Markou


So I had a similar issue, and to resolve it, I created this procedure:

DELIMITER $$
DROP PROCEDURE IF EXISTS `truncate_if_exist`$$

CREATE  PROCEDURE `truncate_if_exist`(IN tbl_name VARCHAR(150) )
  BEGIN
    IF EXISTS( SELECT 1 FROM information_schema.TABLES WHERE table_name = tbl_name AND table_schema = DATABASE()) THEN
    SET @query = CONCAT('TRUNCATE ', tbl_name);
    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    END IF;
  END $$

DELIMITER ;

And then called it for each table that I wanted to truncate

for example:

CALL truncate_if_exist('users');
CALL truncate_if_exist('random_tmp_table');

Obviously, if the table does not exist, it will not run the TRUNCATE command.

like image 24
DevToolBox Avatar answered Nov 19 '22 22:11

DevToolBox