How to work with temporary tables?
Sheik Shahul M
Freelance Data Analyst ? Data Visualisation Expert ? Looker Studio Specialist ? Power BI Developer ? I help Businesses use data to make Smarter Decisions
Temporary tables are exactly what they sound like—temporary tables in a SQL database that aren’t stored permanently. In this reading, you will learn the methods to create temporary tables using SQL commands. You will also learn a few best practices to follow when working with temporary tables.?
It is important to point out that each database has its own unique set of commands to create and manage temporary tables. We have been working with BigQuery, so we will focus on the commands that work well in that environment. The rest of this reading will go over the ways to create temporary tables, primarily in BigQuery.
Temporary table creation in BigQuery
Temporary tables can be created using different clauses. In BigQuery, the WITH clause can be used to create a temporary table. The general syntax for this method is as follows:
Breaking down this query a bit, notice the following:
When the database executes this query, it will first complete the subquery and assign the values that result from that subquery to “new_table_data,” which is the temporary table. You can then run multiple queries on this filtered data without having to filter the data every time.?
Temporary table creation in other databases (not supported in BigQuery)
The following method isn’t supported in BigQuery, but most other versions of SQL databases support it, including SQL Server and mySQL. Using SELECT and INTO, you can create a temporary table based on conditions defined by a WHERE clause to locate the information you need for the temporary table. The general syntax for this method is as follows:
领英推荐
This SELECT statement uses the standard clauses like FROM and WHERE, but the INTO clause tells the database to store the data that is being requested in a new temporary table named, in this case, “AfricaSales.”?
User-managed temporary table creation?
So far, we have explored ways of creating temporary tables that the database is responsible for managing. But, you can also create temporary tables that you can manage as a user. As an analyst, you might decide to create a temporary table for your analysis that you can manage yourself. You would use the CREATE TABLE statement to create this kind of temporary table. After you have finished working with the table, you would then delete or drop it from the database at the end of your session.
Note: BigQuery uses CREATE TEMP TABLE instead of CREATE TABLE, but the general syntax is the same.
After you have completed working with your temporary table, you can remove the table from the database using the DROP TABLE clause. The general syntax is as follows:
Best practices when working with temporary tables
For more information