i2tutorials

MySQL – Temporary Table

MySQL – Temporary Table

 

It is possible to store temporary data in MySQL by creating a special table called a Temporary Table. This table can be reused several times within a single session. If we use an older version of MySQL, this table is not available. It is available in MySQL from version 3.23 and above. Only the current session has access to this table. Whenever the current session is closed or the user terminates the connection, MySQL automatically deletes this table. The DROP TABLE command can also be used to remove this table explicitly when the user will not be using it.

When the PHP script is used to run the code, this table is automatically removed once it has completed its execution. If the user is connected to the server using the MySQL client, then this table will remain until the user closes the MySQL client program, terminates the connection, or manually removes the table from the server.

With temporary tables, we can perform complex tasks quickly, such as querying data that requires a single SELECT statement with JOIN clauses. In this case, the user may use this table to store the output and then run another query to process it.

In MySQL, temporary tables have a number of features, which are outlined below:

Syntax

mysql> CREATE TEMPORARY TABLE table_name (  
   column_1, column_2, ..., table_constraints  
);  

Example

CREATE TEMPORARY TABLE emp_details( emp_name VARCHAR(40) NOT NULL,
total_salary DECIMAL(12,2) NOT NULL DEFAULT 0.00,
total_roles INT UNSIGNED NOT NULL DEFAULT 0);

The next step is to insert values into the temporary table:

INSERT INTO emp_details(emp_name, total_salary, total_roles) VALUES
('Joseph', 150000.75, 2), ('Peter', 180000.75, 2);

To obtain the results, run the following query:

SELECT * from emp_details;

t1

Exit mobile version