Delete a BigQuery Table using Python

In this tutorial, we will learn how to delete a BigQuery table using Python. This is a common operation for managing datasets and cleaning up resources.

The delete_table method permanently deletes the BigQuery table.

Argument 1: table_id

🔹 What it is

A table reference that identifies which table to delete. A fully qualified string is the recommended way to specify table_id as shown below:

table_id = "my-project.my_dataset.my_table"    

Argument 2: not_found_ok=True

🔹 What it controls

It controls error behavior when the table does not exist.

ValueBehavior
TrueNo error if table is missing
False (default)Raises NotFound exception

Python Code to Delete Table

We will use the delete_table method from the google-cloud-bigquery library.

Python

# Import the packages
from dotenv import load_dotenv
import os
from google.oauth2 import service_account
from google.cloud import bigquery

def main():
    # Loads environment variables from a .env file
    load_dotenv()

    # Read environment variables
    credentials_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
    project_name = os.getenv("project_id")

    # Create credentials using the service account file
    credentials = service_account.Credentials.from_service_account_file(credentials_path)

    # Create the BigQuery client
    client = bigquery.Client(credentials=credentials, project=project_name)

    table_id = "ashishcoder.Coding_Dataset.copied_table"

    # Delete the table
    # not_found_ok=True prevents an error if the table does not exist
    client.delete_table(table_id, not_found_ok=True)

    print("The " + table_id + " of the table is deleted.")

if __name__ == "__main__":
    main()    

Key Steps Explained

Note: Deletion is permanent. Be careful when deleting tables as the data cannot be recovered through simple commands.