Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL temporary vs memory table in stored procedures

What's is better to use in a stored procedure: a temporary table or a memory table?

The table is used to stored summary data for reports.

Are there any trade offs that developers should be aware off?

CREATE TEMPORARY TABLE t (avg (double));

or

CREATE TABLE t (avg (double)) ENGINE=MEMORY;
like image 759
Yada Avatar asked Nov 20 '09 00:11

Yada


People also ask

Can you use temp tables in stored procedures?

You can create and use temporary tables in a stored procedure, but the temporary table exists only for the duration of the stored procedure that creates it. When the procedure completes, Adaptive Server automatically drops the temporary table.

Are temporary tables faster MySQL?

Since temporary tables are stored in memory, they are significantly faster than disk-based tables. Consequently, they can be effectively used as intermediate storage areas, to speed up query execution by helping to break up complex queries into simpler components, or as a substitute for subquery and join support.

What is the advantage of using a temporary table instead of a heap table in MySQL?

These memory tables never have values with data type like “BLOB” or “TEXT”. They use indexes which make them faster. Temporary table : The temporary tables could be very useful in some cases to keep temporary data. Temporary table is that they will be deleted when the current client session terminates.

What is the advantage of using a temporary table instead of a table?

Advantages of Temporary Tables You can create a temporary table and insert, delete and update its records without worrying about whether you have sufficient rights to change data in permanent tables, or whether you might be accidentally doing so.


3 Answers

I Just wanted to point out that, in 2021 using MariaDB-10.3.27, the code @biziclop said doesn't work, is not the case any more, this is possible:

CREATE TEMPORARY TABLE tmp1 AS
SELECT * FROM products LIMIT 10;
SELECT * FROM tmp1, tmp1 AS t2;

(I just tested it)

like image 87
AlexisAmasis Avatar answered Oct 09 '22 13:10

AlexisAmasis


Why is this restricted to just the two options? You can do:

CREATE TEMPORARY TABLE t (avg double) ENGINE=MEMORY;

Which works, although I'm not sure how to check if the memory engine is actually being used here.

like image 31
Eloff Avatar answered Oct 09 '22 12:10

Eloff


A temporary table will only exist for the duration of your session. A table declared with Engine=Memory will persist across user sessions / connections but will only exist in the lifetime of the MySQL instance. So if MySQL gets restarted the table goes away.

like image 45
Cody Caughlan Avatar answered Oct 09 '22 12:10

Cody Caughlan