Search code examples
mysql

MySQL: IF EXISTS ... TRUNCATE


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.


Solution

  • You need the two statements below to do that:

    create table if not exists <mytable>;
    
    truncate table <mytable>;