Temporary tables in SQL are used to store intermediate or temporary data within a session. These tables are created and used only for the duration of a transaction or session and are automatically deleted when the transaction is committed or the session is closed. They can be used to store and manipulate data as part of complex queries or to break down complex queries into simpler parts.
There are two types of temporary tables in SQL: local temporary tables and global temporary tables. Local temporary tables are only accessible within the session in which they were created, while global temporary tables are accessible across multiple sessions.
Here are some examples of how to create and use temporary tables in SQL:
Creating a local temporary table:
CREATE TEMPORARY TABLE temp_table (
id INT,
name VARCHAR(50)
);
This creates a local temporary table called temp_table
with two columns: id
of type INT
and name
of type VARCHAR(50)
.
Inserting data into a temporary table:
INSERT INTO temp_table (id, name)
VALUES (1, 'John'),
(2, 'Jane'),
(3, 'Bob');
This inserts three rows of data into the temp_table
.
Selecting data from a temporary table:
SELECT * FROM temp_table;
This selects all the data from the temp_table
.
Dropping a temporary table:
DROP TEMPORARY TABLE temp_table;
This drops the temp_table
temporary table.
Creating a global temporary table:
CREATE GLOBAL TEMPORARY TABLE global_temp_table (
id INT,
name VARCHAR(50)
) ON COMMIT PRESERVE ROWS;
This creates a global temporary table called global_temp_table
with two columns: id
of type INT
and name
of type VARCHAR(50)
. The ON COMMIT PRESERVE ROWS
clause ensures that the data in the table is not deleted when a transaction is committed.
Inserting data into a global temporary table:
INSERT INTO global_temp_table (id, name)
VALUES (1, 'John'),
(2, 'Jane'),
(3, 'Bob');
This inserts three rows of data into the global_temp_table
.
Selecting data from a global temporary table:
SELECT * FROM global_temp_table;
This selects all the data from the global_temp_table
.
Dropping a global temporary table:
DROP GLOBAL TEMPORARY TABLE global_temp_table;
This drops the global_temp_table
temporary table.
In summary, temporary tables are a useful tool in SQL for storing and manipulating data during a transaction or session. They can be used to break down complex queries and simplify data manipulation.
You should take part in a contest for one of the greatest blogs on the web. I most certainly will recommend this website!