58

Is there any way to create a temporary table in Google BigQuery through:

SELECT * INTO <temp table> 
FROM <table name> 

same as we can create in SQL?

For complex queries, I need to create temporary tables to store my data.

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Vasundhara
  • 645
  • 1
  • 6
  • 9

11 Answers11

37

2018 update - definitive answer with DDL

With BigQuery's DDL support you can create a table from the results a query - and specify its expiration at creation time. For example, for 3 days:

#standardSQL
CREATE TABLE `fh-bigquery.public_dump.vtemp`
OPTIONS(
  expiration_timestamp=TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 3 DAY)
) AS
SELECT corpus, COUNT(*) c
FROM `bigquery-public-data.samples.shakespeare`
GROUP BY corpus
Felipe Hoffa
  • 54,922
  • 16
  • 151
  • 325
28

2019 update -- With BigQuery scripting (Beta now), CREATE TEMP TABLE is officially supported. See public documentation here.

2018 update: https://stackoverflow.com/a/50227484/132438

Every query in bigquery creates a temporary table with the results. Temporary unless you give a name to the destination table, then you are in control of its lifecycle.

Use the api to see the temporary table name, or name your tables when querying.

Yun Zhang
  • 5,185
  • 2
  • 10
  • 29
Felipe Hoffa
  • 54,922
  • 16
  • 151
  • 325
  • 3
    I don't want to create temporary table by API. I want to create it through query itself while querying in browser tool (https://bigquery.cloud.google.com). – Vasundhara Dec 19 '13 at 09:38
  • 1
    Same thing. If you look at the query history on the web ui, you'll see the temporary table name each of your past queries get. – Felipe Hoffa Dec 19 '13 at 13:22
  • 1
    You can also specify a destination table (see the 'enable options' button in the UI); this can let you give a name to the destination table for your query. There is no way to do SELECT INTO to write results to a table. – Jordan Tigani Dec 19 '13 at 16:50
  • We might add something into our JDBC driver. Since we're using a custom query parser, Its possible to create INSERT INTO SELECT ... All we need to do is set the API parameters to store it into a new table not a temporary one. We're very busy right now but if we have some time this is a way to improve the JDBC driver. Which can be found at: https://code.google.com/p/starschema-bigquery-jdbc/
    – Balazs Gunics Dec 21 '13 at 14:01
  • Can you give it a name from within the SQL? Or can you only do it through an API? – Emery Lapinski Mar 23 '16 at 19:39
  • Update: Now you can create a temporary table within a query https://stackoverflow.com/a/50227484/132438 – Felipe Hoffa May 08 '18 at 06:48
  • Which means then that we dont have #tables mode in BigQuery – Andres Urrego Angel Dec 21 '18 at 14:56
  • what is a "#tables mode" – Felipe Hoffa Dec 24 '18 at 07:26
23

2019 update -- With BigQuery scripting, CREATE TEMP TABLE is officially supported. See public documentation here.

CREATE TEMP TABLE Example
(
  x INT64,
  y STRING
);

INSERT INTO Example
VALUES (5, 'foo');

INSERT INTO Example
VALUES (6, 'bar');

SELECT *
FROM Example;
Yun Zhang
  • 5,185
  • 2
  • 10
  • 29
  • 7
    You need a `Begin` and `End` statement immediately before and immediately after the CREATE statement, but otherwise this is the easiest answer. – mrp Jul 30 '21 at 20:18
  • It is a surprise to me if you need begin/end around the the create. Could you post the query without begin/end that gives an error? – Yun Zhang Jul 31 '21 at 17:31
  • 2
    I can't run the CREATE statement unless I place a `Begin` before and an `End` statement after. If I don't I receive an error: "Error running query Use of CREATE TEMPORARY TABLE requires a script" – mrp Aug 03 '21 at 17:01
12

A temporary table can be created with WITH in the "New Standard SQL". See WITH clause.

An example given by Google:

WITH subQ1 AS (SELECT SchoolID FROM Roster),
     subQ2 AS (SELECT OpponentID FROM PlayerStats)
SELECT * FROM subQ1
UNION ALL
SELECT * FROM subQ2;
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Fardream
  • 654
  • 2
  • 6
  • 10
  • 22
    This answer, while potentially useful for some use cases, does not address the original question. WITH does not create a temporary table - it is a named sub-query. Big query does not materialize the results of WITH as tables. Each time the named subsquery is referenced, it is executed again, which is presumably what the original question was trying to avoid. See the WITH link in the answer for confirmation. – cbailiss Sep 01 '18 at 08:01
  • 13
    This answer is wrong, `WITH` does not create a temporary table. Whenever you call the `WITH` table , the query is run. https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#with-clause – DollarAkshay Nov 02 '18 at 13:17
  • This even go thru in BigQuery – Andres Urrego Angel Dec 21 '18 at 15:09
11

To create a temporary table, use the TEMP or TEMPORARY keyword when you use the CREATE TABLE statement and use of CREATE TEMPORARY TABLE requires a script , so its better to start with begin statement.

Begin CREATE TEMP TABLE <table_name> as select * from <table_name> where <condition>; End ;

Kuldeep Pal
  • 111
  • 1
  • 2
  • 1
    have in mind that temp table lives only for the life of script it is in, so above "trick" with BEGIN/END makes no much sense. And the rest is already in Yun's answer! – Mikhail Berlyant Oct 11 '19 at 18:40
  • I also noticed that if you are getting the "Use of CREATE TEMPORARY TABLE requires a script" error in the BigQuery console, then you can just make sure you have more than one statement highlighted and end each one with a semicolon. Apparently that qualifies as a "script". – Ryan Shirley Aug 07 '20 at 18:34
5

It's 2022, and if you type the codes to create a TEMP table in BQ's interactive windows, it will not work. Probably will display below error message:

enter image description here

Vaguely it will give you an idea that your interactive windows should be tied with some session. There is the official documentation on how to create sessions etc.,

The short and easy method for me was go to MORE menu of the Google BigQuery Interactive windows, select Query Settings

enter image description here

It will display below SS (as of 2022 April) enter image description here

Enable/click Use session mode and SAVE. That's it enjoy your Temporary Tables :D

DBear
  • 91
  • 1
  • 1
  • This creates a temp table but is there a way to specify the name of table as it creates a table with some random name – Touseef Zaki Jul 11 '23 at 11:27
4

Example of creating temp tables in GCP bigquery

CREATE TABLE  `project_ID_XXXX.Sales.superStore2011` 
OPTIONS(
  expiration_timestamp=TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 1 DAY)
) AS
SELECT 
  Product_Name,Product_Category, SUM(profit) Total_Profit,  FORMAT_DATE("%Y",Order_Date) AS Year
FROM 
  `project_ID_XXXX.Sales.superStore` 
WHERE
  FORMAT_DATE("%Y",Order_Date)="2011"
GROUP BY 
  Product_Name,Product_Category,Order_Date
ORDER BY 
   Year, Total_Profit DESC
LIMIT 5 
Ayaz Hoda
  • 51
  • 1
3

Take the SQL sample of

SELECT name,count FROM mydataset.babynames 
  WHERE gender = 'M' ORDER BY count DESC LIMIT 6 INTO mydataset.happyhalloween;

The easiest command line equivalent is

bq query --destination_table=mydataset.happyhalloween \ 
"SELECT name,count FROM mydataset.babynames WHERE gender = 'M' \
ORDER BY count DESC LIMIT 6"

See the documentation here: https://cloud.google.com/bigquery/bq-command-line-tool#createtablequery

Feczo
  • 608
  • 5
  • 8
  • 3
    This creates a table, but it's not a *temporary* table. – EM0 Jul 01 '19 at 12:07
  • From https://cloud.google.com/bigquery/docs/writing-results#bq -- Enter the bq query command and specify the --destination_table flag to create a permanent table based on the query results. – Yogesh Devi Mar 03 '21 at 12:32
1

I followed Google's official document while learning UDF and encountered the issue: use of create temporary table requires a script or session

Erroneous script:

CREATE TEMP TABLE users
AS  SELECT 1 id, 10 age
UNION ALL SELECT 2, 30
UNION ALL SELECT 3, 10;

Solution:

BEGIN
    CREATE TEMP TABLE users
    AS  SELECT 1 id, 10 age
    UNION ALL SELECT 2, 30
    UNION ALL SELECT 3, 10;
END;
shary.sharath
  • 649
  • 2
  • 14
  • 29
0

To create and store your data on the fly, you can specify optional _SESSION qualifier to create temporary table.

CREATE TEMP TABLE _SESSION.tmp_01
AS
 SELECT name FROM `bigquery-public-data`.usa_names.usa_1910_current
 WHERE year = 2017 
;

Here you can create the table from a complex query starting after 'AS' and the temporary table will be created at once and will be deleted after 24 hours.

To access the table,

select * from _SESSION.tmp_01;
0

Update September 2022:

As per the documentation, you can create a temporary table like:

    CREATE TEMP TABLE continents(name STRING, visitors INT64)
    AS
     select  geo.continent, count(distinct user_pseudo_id)  as Continent_Visitors
    FROM `firebaseProject.dataset.events_date`
    group by geo.continent order by Continent_Visitors desc;
    SELECT * from continents;
Drop table continents;
Simon
  • 761
  • 6
  • 12