Skip to content

06 SQL ‐ Temporary Tables

Pankaj Chouhan edited this page Sep 29, 2023 · 1 revision

In SQL, temporary tables are a type of table that is created and used for a short duration within a session. They are particularly useful when you need to store intermediate results or perform complex operations in stages. Temporary tables are scoped to the session in which they are created and are typically automatically dropped when the session ends or when they are explicitly dropped.

The syntax and usage of temporary tables may vary slightly depending on the database management system you are using (e.g., MySQL, PostgreSQL, SQL Server). Here's a general overview of how to create and use temporary tables:

  1. Creating a Temporary Table: To create a temporary table, you typically use the CREATE TEMPORARY TABLE statement or a similar database-specific command. Here's an example:

    CREATE TEMPORARY TABLE temp_table (
        id INT,
        name VARCHAR(50)
    );

    This command creates a temporary table named "temp_table" with columns "id" and "name."

  2. Inserting Data: You can insert data into the temporary table just like you would with a regular table using the INSERT INTO statement.

    INSERT INTO temp_table (id, name)
    VALUES (1, 'John'), (2, 'Jane');
  3. Querying and Using Temporary Tables: You can query and use temporary tables like any other table in your database. For example:

    SELECT * FROM temp_table;

    Temporary tables can be used in joins, subqueries, and other operations within the same session.

  4. Dropping Temporary Tables: Temporary tables are typically automatically dropped when the session ends, but you can also explicitly drop them using the DROP TEMPORARY TABLE statement:

    DROP TEMPORARY TABLE temp_table;

    This statement removes the temporary table from the session.

It's important to note that the exact syntax and behavior of temporary tables can vary between database systems. Some databases may use different keywords or have specific rules regarding the use of temporary tables. Additionally, temporary tables are often not visible to other database sessions and are meant for temporary storage within the current session only.

Always refer to the documentation of your specific database system for detailed information on working with temporary tables and any system-specific features or limitations.

Clone this wiki locally