SQL TEMPORARY TABLE

Temporary tables, also known as TEMP tables, are used to store intermediate results during a session. These tables are automatically dropped when the session ends.

Syntax


CREATE TEMPORARY TABLE temp_table_name (column1 datatype, column2 datatype, ...);
        

Example

Let us create a temporary table named Temp_Staff and insert data into it:

Code Example


-- Create a Temporary Table
CREATE TEMPORARY TABLE Temp_Staff (
    ID INT,
    Name VARCHAR(50),
    Age INT,
    Department VARCHAR(50)
);

-- Insert Data into the Temporary Table
INSERT INTO Temp_Staff VALUES (4, 'Diana', 30, 'HR');

-- Display the Temporary Table
SELECT * FROM Temp_Staff;
            

Output

-- SELECT * FROM Temp_Staff:
ID Name Age Department
4 Diana 30 HR

Explanation

- The CREATE TEMPORARY TABLE command creates a session-limited table named Temp_Staff.
- Data is inserted into the temporary table using the INSERT INTO statement.
- The SELECT * command displays the data stored in the temporary table.

Best Practices

- Use temporary tables for intermediate calculations and short-term data storage.
- Avoid using large data in temporary tables to minimize memory usage.