Search code examples
sqlgoogle-bigquerydml

Google BigQuery: Delete Statement for several tables in one query


It is possible to delete rows in several tables in one query?

Like this :

delete FROM project.dataset.table1, project.dataset.table2, project.dataset.table3
where id not in 
(
    select distinct id from project.dataset.table4
)

Is there a way to do this ??


Solution

  • DML is usually on one table. It is possible to perform many operations on the single table using a MERGE Statement.

    All three deletes will need to be performed indivudually.

    bq utility enables multiple query statements to be processed if they are passed as a single sql file.

    mydeletefile.sql

    delete FROM dataset.table1 where id not in 
    (select distinct id from dataset.table4);
    
    delete FROM dataset.table2 where id not in 
    (select distinct id from dataset.table4);
    
    delete FROM dataset.table3 where id not in 
    (select distinct id from dataset.table4);
    

    Run bq

    cat mydeletefile.sql | bq query --use_legacy_sql=false
    

    (assumes bq init has been run already and project is configured)

    As @T0ny1234 comments need to check FK constraints are not in breach.
    But bottom line - multiple table row delete is not a concept normally even considered and not seen in any SQL implementations happy to be corrected