Worldscope

SQL TEMP TABLE

Palavras-chave:

Publicado em: 03/08/2025

Understanding SQL Temporary Tables

SQL temporary tables are a powerful tool for storing intermediate results within a database session. This article provides a comprehensive guide to using temporary tables, including their creation, manipulation, and benefits, specifically within the context of SQL.

Fundamental Concepts / Prerequisites

Before diving into temporary tables, you should have a basic understanding of SQL, including:

  • SQL Data Manipulation Language (DML): SELECT, INSERT, UPDATE, DELETE
  • SQL Data Definition Language (DDL): CREATE TABLE, DROP TABLE
  • Basic table concepts: columns, data types, constraints

Creating and Using Temporary Tables

Temporary tables are created using the CREATE TEMP TABLE or CREATE TEMPORARY TABLE statement. They exist only for the duration of the current database session and are automatically dropped when the session ends. Two primary types exist: session-specific temporary tables and global temporary tables (whose existence depends on the specific database system being used). This explanation focuses on session-specific temporary tables.


-- Create a temporary table named 'temp_employees'
CREATE TEMP TABLE temp_employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(255),
    department_id INT
);

-- Insert data into the temporary table
INSERT INTO temp_employees (employee_id, employee_name, department_id)
VALUES
    (1, 'Alice Smith', 101),
    (2, 'Bob Johnson', 102),
    (3, 'Charlie Brown', 101);

-- Select data from the temporary table
SELECT * FROM temp_employees;

-- Drop the temporary table (optional, as it's automatically dropped at the end of the session)
-- DROP TABLE temp_employees;

-- Demonstrating a more complex scenario: calculating average salary per department using a temporary table
-- First, create a table to work with (if one doesn't exist)
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(255),
    department_id INT,
    salary DECIMAL(10,2)
);

INSERT INTO employees (employee_id, employee_name, department_id, salary) VALUES
(1, 'Alice Smith', 101, 60000.00),
(2, 'Bob Johnson', 102, 75000.00),
(3, 'Charlie Brown', 101, 65000.00),
(4, 'David Lee', 102, 80000.00),
(5, 'Eve Wilson', 103, 90000.00);

-- Create a temporary table to store the average salary per department
CREATE TEMP TABLE temp_avg_salaries AS
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id;

-- Select the results from the temporary table
SELECT * FROM temp_avg_salaries;

-- Optionally drop the original employee table if no longer needed
--DROP TABLE employees;

Code Explanation

The first code block demonstrates creating a simple temporary table named temp_employees. We then insert sample data and select all records from it. The DROP TABLE statement is commented out because the table is automatically dropped at the end of the session. If left uncommented, it will drop the temporary table during the session.

The second code block expands on this by demonstrating a more practical usage. First, we create a regular table employees and populate it with data, including employee IDs, names, department IDs, and salaries. Then, we create a temporary table called temp_avg_salaries using a CREATE TABLE AS statement. This statement creates the temporary table *and* populates it with the results of a SELECT query that calculates the average salary per department. Finally, we select the data from the temporary table to display the average salaries for each department.

Complexity Analysis

The complexity analysis depends heavily on the operations performed on the temporary table. Here's a general overview:

Time Complexity:

  • Creating a temporary table: O(1) on average, but can be higher if there are complex constraints.
  • Inserting data into a temporary table: O(n) in the simplest case (single insert), where n is the number of rows being inserted. Bulk inserts are more efficient.
  • Selecting data from a temporary table: O(n) in the worst case (full table scan), but can be O(log n) or better if indexes are used (though temporary tables are not typically indexed explicitly). Complexity is heavily reliant on WHERE clauses, joins, and the number of rows in the temporary table.

Space Complexity:

  • The space complexity depends on the size of the data stored in the temporary table. It's proportional to the number of rows and the size of the columns in each row. Temporary tables consume disk space, so large tables can impact performance.

Alternative Approaches

While temporary tables are useful, Common Table Expressions (CTEs) offer an alternative approach, particularly for simple operations. CTEs are defined using the WITH clause and are available within a single query. They exist only for the duration of the query.

Trade-offs:

  • Temporary tables persist across multiple statements within a session, while CTEs are scoped to a single query.
  • CTEs can sometimes be more readable for complex queries, as they break down the logic into smaller, named units.
  • Temporary tables can be beneficial when the same intermediate result is used multiple times in different queries within the same session.

Example of the average salary calculation using a CTE:


WITH AvgSalaries AS (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
)
SELECT * FROM AvgSalaries;

Conclusion

SQL temporary tables are a valuable tool for managing intermediate results and simplifying complex queries within a database session. Understanding their creation, usage, and limitations allows developers to write more efficient and maintainable SQL code. While CTEs offer an alternative approach for simpler scenarios, temporary tables provide persistence and reusability that can be beneficial in more complex database operations.