Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping Temp Table At End Of Stored Procedure In MySQL

Do I need to add DROP TEMPORARY TABLE IF EXISTS data; at the end of the stored procedure even though I have the check at the top? Is there a performance implication?

CREATE DEFINER=`TEST`@`%` PROCEDURE `TEST`() BEGIN

    DROP TEMPORARY TABLE IF EXISTS data;

    CREATE TEMPORARY TABLE data AS 
...


END;
like image 925
Mike Flynn Avatar asked Aug 06 '12 20:08

Mike Flynn


People also ask

Should I drop temp table at end of stored procedure?

If you are wondering why it is not required to drop the temp table at the end of the stored procedure, well, it is because when the stored procedure completes execution, it automatically drops the temp table when the connection/session is dropped which was executing it. Well, that's it.

How do I drop a temp table in MySQL?

DROP TABLE MySQL Command Syntax. To remove a table in MySQL, use the DROP TABLE statement. The basic syntax of the command is as follows: DROP [TEMPORARY] TABLE [IF EXISTS] table_name [, table_name] [RESTRICT | CASCADE];

Can we drop table from stored procedure?

You can use these scripts to drop database, table, or other elements In the beginning of your stored procedure, and then create them freely during the SP. While recreating the table you have full control over the data types of the table columns (fields is a wrong word by the way in this context).

Should you explicitly drop temp tables?

It's ok to explicitly include DROP TABLE or let SQL Server handle it for you each time the connection drops. If your stored procedures are already dropping temp tables, that's great. If they're not being dropped, I wouldn't bother spending the time and effort just to drop them.


1 Answers

In MySQL, temporary tables are dropped automatically when a database connection is closed. If you plan on leaving your connection open after the stored procedure, your temp table will exist on disk until that connection is closed. The performance implications depend on many factors, such as how you have configured temporary table storage on your server, how much data is in the table, etc.

It is considered best practice to just drop the temp table as soon as you are done with it. Then you save yourself the worry about those potential performance implications all together

like image 76
EkoostikMartin Avatar answered Oct 13 '22 16:10

EkoostikMartin