Wednesday, April 20, 2011

Clear data in MySQL table with PHP?

How do I clear all the entries from just one table in MySQL with PHP?

From stackoverflow
  • TRUNCATE TABLE mytable
    

    Be careful with it though.

  • TRUNCATE TABLE tablename
    

    or

    DELETE FROM tablename
    

    The first one is usually the better choice, as DELETE FROM is slow on InnoDB.

    Actually, wasn't this already answered in your other question?

    Kezzer : And from a requirement perspective, truncate will reset the indicies whereas delete won't.
  • TRUNCATE TABLE table;
    

    is the SQL command. In PHP, you'd use:

    mysql_query('TRUNCATE TABLE table;');
    
  • TRUNCATE TABLE `table`
    

    unless you need to preserve the current value of the AUTO_INCREMENT sequence, in which case you'd probably prefer

    DELETE FROM `table`
    

    though if the time of the operation matters, saving the AUTO_INCREMENT value, truncating the table, and then restoring the value using

    ALTER TABLE `table` AUTO_INCREMENT = value
    

    will happen a lot faster.

  • Actually I believe the MySQL optimizer carries out a TRUNCATE when you DELETE all rows.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.