Positional parameters Stay organized with collections Save and categorize content based on your preferences.
Run a query with positional 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;publicclassBigQueryQueryWithPositionalParameters{publicvoidQueryWithPositionalParameters(stringprojectId="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 = ? AND word_count >= ? ORDER BY word_count DESC;";// Initialize client that will be used to send requests.varclient=BigQueryClient.Create(projectId);// Set the name to None to use positional parameters.// Note that you cannot mix named and positional parameters.varparameters=newBigQueryParameter[]{newBigQueryParameter(null,BigQueryDbType.String,corpus),newBigQueryParameter(null,BigQueryDbType.Int64,minWordCount)};varjob=client.CreateQueryJob(sql:query,parameters:parameters,options:newQueryOptions{UseQueryCache=false,ParameterMode=BigQueryParameterMode.Positional});// 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")// queryWithPostionalParams demonstrate issuing a query using positional query parameters.funcqueryWithPositionalParams(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 = ? AND word_count >= ? ORDER BY word_count DESC;`)q.Parameters=[]bigquery.QueryParameter{{Value:"romeoandjuliet",},{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;publicclassQueryWithPositionalParameters{publicstaticvoidmain(String[]args){queryWithPositionalParameters();}publicstaticvoidqueryWithPositionalParameters(){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 = ?\n"+"AND word_count >= ?\n"+"ORDER BY word_count DESC";// Note: Standard SQL is required to use query parameters.QueryJobConfigurationqueryConfig=QueryJobConfiguration.newBuilder(query).addPositionalParameter(QueryParameterValue.string(corpus)).addPositionalParameter(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 positional 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 positional query parameters// Import the Google Cloud client libraryconst{BigQuery}=require('@google-cloud/bigquery');constbigquery=newBigQuery();asyncfunctionqueryParamsPositional(){// The SQL query to runconstsqlQuery=`SELECT word, word_count FROM \`bigquery-public-data.samples.shakespeare\` WHERE corpus = ? AND 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:['romeoandjuliet',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 = ? AND word_count >= ? ORDER BY word_count DESC;"""# Set the name to None to use positional parameters.# Note that you cannot mix named and positional parameters.job_config=bigquery.QueryJobConfig(query_parameters=[bigquery.ScalarQueryParameter(None,"STRING","romeoandjuliet"),bigquery.ScalarQueryParameter(None,"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.