Named parameters Stay organized with collections Save and categorize content based on your preferences.
Run a query with named parameters.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
C#
Before trying this sample, follow theC# setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryC# API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
usingGoogle.Cloud.BigQuery.V2;usingSystem;publicclassBigQueryQueryWithNamedParameters{publicvoidQueryWithNamedParameters(stringprojectId="your-project-id"){varcorpus="romeoandjuliet";varminWordCount=250;// Note: Standard SQL is required to use query parameters.varquery=@" SELECT word, word_count FROM `bigquery-public-data.samples.shakespeare` WHERE corpus = @corpus AND word_count >= @min_word_count ORDER BY word_count DESC";// Initialize client that will be used to send requests.varclient=BigQueryClient.Create(projectId);varparameters=newBigQueryParameter[]{newBigQueryParameter("corpus",BigQueryDbType.String,corpus),newBigQueryParameter("min_word_count",BigQueryDbType.Int64,minWordCount)};varjob=client.CreateQueryJob(sql:query,parameters:parameters,options:newQueryOptions{UseQueryCache=false});// Wait for the job to complete.job=job.PollUntilCompleted().ThrowOnAnyError();// Display the resultsforeach(BigQueryRowrowinclient.GetQueryResults(job.Reference)){Console.WriteLine($"{row["word"]}: {row["word_count"]}");}}}Go
Before trying this sample, follow theGo setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryGo API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
import("context""fmt""io""cloud.google.com/go/bigquery""google.golang.org/api/iterator")// queryWithNamedParams demonstrate issuing a query using named query parameters.funcqueryWithNamedParams(wio.Writer,projectIDstring)error{// projectID := "my-project-id"ctx:=context.Background()client,err:=bigquery.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("bigquery.NewClient: %w",err)}deferclient.Close()q:=client.Query(`SELECT word, word_count FROM `+"`bigquery-public-data.samples.shakespeare`"+` WHERE corpus = @corpus AND word_count >= @min_word_count ORDER BY word_count DESC;`)q.Parameters=[]bigquery.QueryParameter{{Name:"corpus",Value:"romeoandjuliet",},{Name:"min_word_count",Value:250,},}// Run the query and process the returned row iterator.it,err:=q.Read(ctx)iferr!=nil{returnfmt.Errorf("query.Read(): %w",err)}for{varrow[]bigquery.Valueerr:=it.Next(&row)iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Fprintln(w,row)}returnnil}Java
Before trying this sample, follow theJava setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryJava API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
importcom.google.cloud.bigquery.BigQuery;importcom.google.cloud.bigquery.BigQueryException;importcom.google.cloud.bigquery.BigQueryOptions;importcom.google.cloud.bigquery.QueryJobConfiguration;importcom.google.cloud.bigquery.QueryParameterValue;importcom.google.cloud.bigquery.TableResult;publicclassQueryWithNamedParameters{publicstaticvoidmain(String[]args){queryWithNamedParameters();}publicstaticvoidqueryWithNamedParameters(){try{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.BigQuerybigquery=BigQueryOptions.getDefaultInstance().getService();Stringcorpus="romeoandjuliet";longminWordCount=250;Stringquery="SELECT word, word_count\n"+"FROM `bigquery-public-data.samples.shakespeare`\n"+"WHERE corpus = @corpus\n"+"AND word_count >= @min_word_count\n"+"ORDER BY word_count DESC";// Note: Standard SQL is required to use query parameters.QueryJobConfigurationqueryConfig=QueryJobConfiguration.newBuilder(query).addNamedParameter("corpus",QueryParameterValue.string(corpus)).addNamedParameter("min_word_count",QueryParameterValue.int64(minWordCount)).build();TableResultresults=bigquery.query(queryConfig);results.iterateAll().forEach(row->row.forEach(val->System.out.printf("%s,",val.toString())));System.out.println("Query with named parameters performed successfully.");}catch(BigQueryException|InterruptedExceptione){System.out.println("Query not performed \n"+e.toString());}}}Node.js
Before trying this sample, follow theNode.js setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryNode.js API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
// Run a query using named query parameters// Import the Google Cloud client libraryconst{BigQuery}=require('@google-cloud/bigquery');constbigquery=newBigQuery();asyncfunctionqueryParamsNamed(){// The SQL query to runconstsqlQuery=`SELECT word, word_count FROM \`bigquery-public-data.samples.shakespeare\` WHERE corpus = @corpus AND word_count >= @min_word_count ORDER BY word_count DESC`;constoptions={query:sqlQuery,// Location must match that of the dataset(s) referenced in the query.location:'US',params:{corpus:'romeoandjuliet',min_word_count:250},};// Run the queryconst[rows]=awaitbigquery.query(options);console.log('Rows:');rows.forEach(row=>console.log(row));}Python
Before trying this sample, follow thePython setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryPython API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
fromgoogle.cloudimportbigquery# Construct a BigQuery client object.client=bigquery.Client()query=""" SELECT word, word_count FROM `bigquery-public-data.samples.shakespeare` WHERE corpus = @corpus AND word_count >= @min_word_count ORDER BY word_count DESC;"""job_config=bigquery.QueryJobConfig(query_parameters=[bigquery.ScalarQueryParameter("corpus","STRING","romeoandjuliet"),bigquery.ScalarQueryParameter("min_word_count","INT64",250),])results=client.query_and_wait(query,job_config=job_config)# Make an API request.forrowinresults:print("{}:\t{}".format(row.word,row.word_count))What's next
To search and filter code samples for other Google Cloud products, see theGoogle Cloud sample browser.
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.