How to create and use temporary tables in SQL?
In SQL, you can use the CREATE TABLE statement to create a temporary table. Temporary tables exist only for the current session and are automatically deleted once the session ends.
The syntax for creating temporary tables is as follows:
CREATE TEMPORARY TABLE table_name (
column1 datatype,
column2 datatype,
...
);
In this case, table_name is the name of the temporary table to be created, and column1, column2, etc. are the column names and their corresponding data types for the table.
Once the temporary table is created, you can use SELECT, INSERT, UPDATE, DELETE statements to manipulate the temporary table just like you would with a regular table. For example:
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
SELECT * FROM table_name;
Some considerations when using temporary tables:
- Temporary tables are only accessible within the current session and cannot be accessed by other sessions.
- Temporary tables are automatically deleted at the end of a session, or they can be manually deleted using the DROP TABLE statement.