Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigQuery Equivalent of "CREATE TABLE my_table (LIKE your_table)"

I want to create a table which schema is exactly the same as another table. In other SQL engines, I think I was able to use "CREATE TABLE my_table (LIKE your_table)" or some variations.

I couldn't find the equivalent in BigQuery yet. Is this possible in some fashion?

like image 294
kee Avatar asked Dec 18 '22 21:12

kee


2 Answers

Use this form:

CREATE TABLE dataset.new_table AS
SELECT *
FROM dataset.existing_table
LIMIT 0

This creates a new table with the same schema as the old one, and there is no cost due to the LIMIT 0.

Note that this does not preserve partitioning, table description, etc., however. Another option is to use the CLI (or API), making a copy of the table and then overwriting its contents, e.g.:

$ bq cp dataset.existing_table dataset.new_table
$ bq query --use_legacy_sql --replace --destination_table=dataset.new_table \
    "SELECT * FROM dataset.new_table LIMIT 0;"

Now the new table has the same structure and attributes as the original did.

like image 171
Elliott Brossard Avatar answered Dec 28 '22 06:12

Elliott Brossard


To create a partitioned and/or clustered table the syntax would be:

CREATE TABLE project.dataset.clustered_table PARTITION BY DATE(created_time) CLUSTER BY account_id AS SELECT * FROM project.dataset.example_table LIMIT 0

like image 45
Evan Vaughan Avatar answered Dec 28 '22 05:12

Evan Vaughan