Work with SQL stored procedures
Astored procedure is a collection of statements that can be called from otherqueries or other stored procedures. A procedure can take input arguments andreturn values as output. You name and store a procedure in aBigQuery dataset. A stored procedure can access or modify dataacross multiple datasets by multiple users. It can also contain amulti-statement query.
Some stored procedures are built into BigQuery and don't need tobe created. These are calledsystem procedures and you can learn more aboutthem in theSystem procedures reference.
Stored procedures supportprocedural language statements, which let you dothings like define variables and implement control flow. You can learn moreabout procedural language statements in theProcedural language reference.
Create a stored procedure
Choose one of the following options to create a stored procedure:
SQL
To create a procedure, use theCREATE PROCEDUREstatement.
In the following conceptual example,procedure_name representsthe procedure and the body of the procedure appears betweenBEGIN andEND statements:
CREATEPROCEDUREdataset_name.procedure_name()BEGIN-- statements hereENDThe following example shows a procedure that contains a multi-statement query.The multi-statement query sets a variable, runs anINSERT statement, anddisplays the result as a formatted text string.
CREATEORREPLACEPROCEDUREmydataset.create_customer()BEGINDECLAREidSTRING;SETid=GENERATE_UUID();INSERTINTOmydataset.customers(customer_id)VALUES(id);SELECTFORMAT("Created customer %s",id);ENDIn the preceding example, the name of the procedure ismydataset.create_customer, and the body of procedure appears betweenBEGIN andEND statements.
To call the procedure, use theCALLstatement:
CALLmydataset.create_customer();Terraform
Use thegoogle_bigquery_routine resource.
To authenticate to BigQuery, set up Application DefaultCredentials. For more information, seeSet up authentication for client libraries.
The following example creates a stored procedure namedmy_stored_procedure:
# Creates a SQL stored procedure.# Create a dataset to contain the stored procedure.resource "google_bigquery_dataset" "my_dataset" { dataset_id = "my_dataset"}# Create a stored procedure.resource "google_bigquery_routine" "my_stored_procedure" { dataset_id = google_bigquery_dataset.my_dataset.dataset_id routine_id = "my_stored_procedure" routine_type = "PROCEDURE" language = "SQL" definition_body = "SELECT * FROM `bigquery-public-data.ml_datasets.penguins`;"}To apply your Terraform configuration in a Google Cloud project, complete the steps in the following sections.
Prepare Cloud Shell
- LaunchCloud Shell.
Set the default Google Cloud project where you want to apply your Terraform configurations.
You only need to run this command once per project, and you can run it in any directory.
export GOOGLE_CLOUD_PROJECT=PROJECT_ID
Environment variables are overridden if you set explicit values in the Terraform configuration file.
Prepare the directory
Each Terraform configuration file must have its own directory (alsocalled aroot module).
- InCloud Shell, create a directory and a new file within that directory. The filename must have the
.tfextension—for examplemain.tf. In this tutorial, the file is referred to asmain.tf.mkdirDIRECTORY && cdDIRECTORY && touch main.tf
If you are following a tutorial, you can copy the sample code in each section or step.
Copy the sample code into the newly created
main.tf.Optionally, copy the code from GitHub. This is recommended when the Terraform snippet is part of an end-to-end solution.
- Review and modify the sample parameters to apply to your environment.
- Save your changes.
- Initialize Terraform. You only need to do this once per directory.
terraform init
Optionally, to use the latest Google provider version, include the
-upgradeoption:terraform init -upgrade
Apply the changes
- Review the configuration and verify that the resources that Terraform is going to create or update match your expectations:
terraform plan
Make corrections to the configuration as necessary.
- Apply the Terraform configuration by running the following command and entering
yesat the prompt:terraform apply
Wait until Terraform displays the "Apply complete!" message.
- Open your Google Cloud project to view the results. In the Google Cloud console, navigate to your resources in the UI to make sure that Terraform has created or updated them.
Pass a value in with an input parameter
A procedure can have input parameters. An input parameter allows input fora procedure, but does not allow output.
CREATEORREPLACEPROCEDUREmydataset.create_customer(nameSTRING)BEGINDECLAREidSTRING;SETid=GENERATE_UUID();INSERTINTOmydataset.customers(customer_id,name)VALUES(id,name);SELECTFORMAT("Created customer %s (%s)",id,name);ENDPass a value out with an output parameter
A procedure can have output parameters. An output parameter returns a valuefrom the procedure, but does not allow input for the procedure. To create anoutput parameter, use theOUT keyword before the name of the parameter.
For example, this version of the procedure returns the new customer ID throughtheid parameter:
CREATEORREPLACEPROCEDUREmydataset.create_customer(nameSTRING,OUTidSTRING)BEGINSETid=GENERATE_UUID();INSERTINTOmydataset.customers(customer_id,name)VALUES(id,name);SELECTFORMAT("Created customer %s (%s)",id,name);ENDTo call this procedure, you must use a variable to receive the output value:
--- Create a new customer record.DECLAREidSTRING;CALLmydataset.create_customer("alice",id);--- Display the record.SELECT*FROMmydataset.customersWHEREcustomer_id=id;Pass a value in and out with an input/output parameter
A procedure can also have input/output parameters. An input/output parameterreturns a value from the procedure and also accepts input for the procedure. Tocreate an input/output parameter, use theINOUT keyword before the name of theparameter. For more information, seeArgument mode.
Authorize routines
You can authorize stored procedures asroutines.Authorized routines let you share query results with specific users or groupswithout giving them access to the underlying tables that generated the results.For example, an authorized routine can compute an aggregationover data or look up a table value and use that value in a computation.
Authorized routines cancreate,drop,andmanipulate tables,as well asinvoke other stored procedureson the underlying table.
For more information, seeAuthorized routines.
Call a stored procedure
To call a stored procedure after it's been created, use theCALL statement.For example, the following statement calls the stored procedurecreate_customer:
CALLmydataset.create_customer();Call a system procedure
To call a built-in system procedure, use theCALL statement.For example, the following statement calls the system procedureBQ.REFRESH_MATERIALIZED_VIEW:
CALLBQ.REFRESH_MATERIALIZED_VIEW;Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-19 UTC.