Array parameters
Stay organized with collections
Save and categorize content based on your preferences.
Run a query with array parameters.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis document provides code samples in C#, Go, Java, Node.js, and Python for running queries in BigQuery with array parameters.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples demonstrate how to execute a query that filters data based on both a gender and a list of states, utilizing the \u003ccode\u003eIN UNNEST\u003c/code\u003e clause.\u003c/p\u003e\n"],["\u003cp\u003eAll code examples use a common SQL query against the \u003ccode\u003ebigquery-public-data.usa_names.usa_1910_2013\u003c/code\u003e dataset to find the top 10 names based on count, filtered by gender and states.\u003c/p\u003e\n"],["\u003cp\u003eEach language-specific section includes setup instructions, API reference links, and authentication guidance for BigQuery client libraries.\u003c/p\u003e\n"],["\u003cp\u003eThese code samples emphasize the use of Standard SQL, which is required to implement query parameters.\u003c/p\u003e\n"]]],[],null,["Run a query with array parameters.\n\nExplore further\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Running parameterized queries](/bigquery/docs/parameterized-queries)\n\nCode sample \n\nC#\n\n\nBefore trying this sample, follow the C# setup instructions in the\n[BigQuery quickstart using\nclient libraries](/bigquery/docs/quickstarts/quickstart-client-libraries).\n\n\nFor more information, see the\n[BigQuery C# API\nreference documentation](/dotnet/docs/reference/Google.Cloud.BigQuery.V2/latest).\n\n\nTo authenticate to BigQuery, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/bigquery/docs/authentication#client-libs).\n\n\n using Google.Cloud.BigQuery.V2;\n using System;\n\n public class BigQueryQueryWithArrayParameters\n {\n public void QueryWithArrayParameters(string projectId = \"your-project-id\")\n {\n var gender = \"M\";\n string[] states = { \"WA\", \"WI\", \"WV\", \"WY\" };\n\n // Note: Standard SQL is required to use query parameters.\n var query = @\"\n SELECT name, sum(number) as count\n FROM `bigquery-public-data.usa_names.usa_1910_2013`\n WHERE gender = @gender\n AND state IN UNNEST(@states)\n GROUP BY name\n ORDER BY count DESC\n LIMIT 10;\";\n\n // Initialize client that will be used to send requests.\n var client = BigQueryClient.Create(projectId);\n\n var parameters = new BigQueryParameter[]\n {\n new BigQueryParameter(\"gender\", BigQueryDbType.String, gender),\n new BigQueryParameter(\"states\", BigQueryDbType.Array, states)\n };\n\n var job = client.CreateQueryJob(\n sql: query,\n parameters: parameters,\n options: new QueryOptions { UseQueryCache = false });\n // Wait for the job to complete.\n job = job.PollUntilCompleted().ThrowOnAnyError();\n // Display the results\n foreach (BigQueryRow row in client.GetQueryResults(job.Reference))\n {\n Console.WriteLine($\"{row[\"name\"]}: {row[\"count\"]}\");\n }\n }\n }\n\nGo\n\n\nBefore trying this sample, follow the Go setup instructions in the\n[BigQuery quickstart using\nclient libraries](/bigquery/docs/quickstarts/quickstart-client-libraries).\n\n\nFor more information, see the\n[BigQuery Go API\nreference documentation](https://godoc.org/cloud.google.com/go/bigquery).\n\n\nTo authenticate to BigQuery, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/bigquery/docs/authentication#client-libs).\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"io\"\n\n \t\"cloud.google.com/go/bigquery\"\n \t\"google.golang.org/api/iterator\"\n )\n\n // queryWithArrayParams demonstrates issuing a query and specifying query parameters that include an\n // array of strings.\n func queryWithArrayParams(w io.Writer, projectID string) error {\n \t// projectID := \"my-project-id\"\n \tctx := context.Background()\n \tclient, err := bigquery.NewClient(ctx, projectID)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"bigquery.NewClient: %w\", err)\n \t}\n \tdefer client.Close()\n\n \tq := client.Query(\n \t\t`SELECT\n \t\t\tname,\n \t\t\tsum(number) as count \n FROM ` + \"`bigquery-public-data.usa_names.usa_1910_2013`\" + `\n \t\tWHERE\n \t\t\tgender = @gender\n \tAND state IN UNNEST(@states)\n \t\tGROUP BY\n \t\t\tname\n \t\tORDER BY\n \t\t\tcount DESC\n \t\tLIMIT 10;`)\n \tq.Parameters = []bigquery.QueryParameter{\n \t\t{\n \t\t\tName: \"gender\",\n \t\t\tValue: \"M\",\n \t\t},\n \t\t{\n \t\t\tName: \"states\",\n \t\t\tValue: []string{\"WA\", \"WI\", \"WV\", \"WY\"},\n \t\t},\n \t}\n \t// Run the query and process the returned row iterator.\n \tit, err := q.Read(ctx)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"query.Read(): %w\", err)\n \t}\n \tfor {\n \t\tvar row []bigquery.Value\n \t\terr := it.Next(&row)\n \t\tif err == iterator.Done {\n \t\t\tbreak\n \t\t}\n \t\tif err != nil {\n \t\t\treturn err\n \t\t}\n \t\tfmt.Fprintln(w, row)\n \t}\n \treturn nil\n }\n\nJava\n\n\nBefore trying this sample, follow the Java setup instructions in the\n[BigQuery quickstart using\nclient libraries](/bigquery/docs/quickstarts/quickstart-client-libraries).\n\n\nFor more information, see the\n[BigQuery Java API\nreference documentation](/java/docs/reference/google-cloud-bigquery/latest/overview).\n\n\nTo authenticate to BigQuery, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/bigquery/docs/authentication#client-libs).\n\n import com.google.cloud.bigquery.BigQuery;\n import com.google.cloud.bigquery.BigQueryException;\n import com.google.cloud.bigquery.BigQueryOptions;\n import com.google.cloud.bigquery.QueryJobConfiguration;\n import com.google.cloud.bigquery.QueryParameterValue;\n import com.google.cloud.bigquery.TableResult;\n\n // Sample to running a query with array query parameters.\n public class QueryWithArrayParameters {\n\n public static void main(String[] args) {\n String gender = \"M\";\n String[] states = {\"WA\", \"WI\", \"WV\", \"WY\"};\n String query =\n \"SELECT name, sum(number) as count\\n\"\n + \"FROM `bigquery-public-data.usa_names.usa_1910_2013`\\n\"\n + \"WHERE gender = @gender\\n\"\n + \"AND state IN UNNEST(@states)\\n\"\n + \"GROUP BY name\\n\"\n + \"ORDER BY count DESC\\n\"\n + \"LIMIT 10;\";\n queryWithArrayParameters(query, gender, states);\n }\n\n public static void queryWithArrayParameters(String query, String gender, String[] states) {\n try {\n // Initialize client that will be used to send requests. This client only needs to be created\n // once, and can be reused for multiple requests.\n BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();\n\n // Note: Standard SQL is required to use query parameters.\n QueryJobConfiguration queryConfig =\n QueryJobConfiguration.newBuilder(query)\n .addNamedParameter(\"gender\", QueryParameterValue.string(gender))\n .addNamedParameter(\"states\", QueryParameterValue.array(states, String.class))\n .build();\n\n TableResult results = bigquery.query(queryConfig);\n\n // Print the results.\n results\n .iterateAll()\n .forEach(row -\u003e row.forEach(val -\u003e System.out.printf(\"%s,\", val.toString())));\n System.out.println(\"Query with arrays parameters performed successfully\");\n } catch (BigQueryException | InterruptedException e) {\n System.out.println(\"Query not performed \\n\" + e.toString());\n }\n }\n }\n\nNode.js\n\n\nBefore trying this sample, follow the Node.js setup instructions in the\n[BigQuery quickstart using\nclient libraries](/bigquery/docs/quickstarts/quickstart-client-libraries).\n\n\nFor more information, see the\n[BigQuery Node.js API\nreference documentation](https://googleapis.dev/nodejs/bigquery/latest/index.html).\n\n\nTo authenticate to BigQuery, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/bigquery/docs/authentication#client-libs).\n\n // Run a query using array query parameters\n\n // Import the Google Cloud client library\n const {BigQuery} = require('@google-cloud/bigquery');\n const bigquery = new BigQuery();\n\n async function queryParamsArrays() {\n // The SQL query to run\n const sqlQuery = `SELECT name, sum(number) as count\n FROM \\`bigquery-public-data.usa_names.usa_1910_2013\\`\n WHERE gender = @gender\n AND state IN UNNEST(@states)\n GROUP BY name\n ORDER BY count DESC\n LIMIT 10;`;\n\n const options = {\n query: sqlQuery,\n // Location must match that of the dataset(s) referenced in the query.\n location: 'US',\n params: {gender: 'M', states: ['WA', 'WI', 'WV', 'WY']},\n };\n\n // Run the query\n const [rows] = await bigquery.query(options);\n\n console.log('Rows:');\n rows.forEach(row =\u003e console.log(row));\n }\n\nPython\n\n\nBefore trying this sample, follow the Python setup instructions in the\n[BigQuery quickstart using\nclient libraries](/bigquery/docs/quickstarts/quickstart-client-libraries).\n\n\nFor more information, see the\n[BigQuery Python API\nreference documentation](/python/docs/reference/bigquery/latest).\n\n\nTo authenticate to BigQuery, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/bigquery/docs/authentication#client-libs).\n\n from google.cloud import bigquery\n\n # Construct a BigQuery client object.\n client = bigquery.Client()\n\n query = \"\"\"\n SELECT name, sum(number) as count\n FROM `bigquery-public-data.usa_names.usa_1910_2013`\n WHERE gender = @gender\n AND state IN UNNEST(@states)\n GROUP BY name\n ORDER BY count DESC\n LIMIT 10;\n \"\"\"\n job_config = bigquery.QueryJobConfig(\n query_parameters=[\n bigquery.ScalarQueryParameter(\"gender\", \"STRING\", \"M\"),\n bigquery.ArrayQueryParameter(\"states\", \"STRING\", [\"WA\", \"WI\", \"WV\", \"WY\"]),\n ]\n )\n rows = client.query_and_wait(query, job_config=job_config) # Make an API request.\n\n for row in rows:\n print(\"{}: \\t{}\".format(row.name, row.count))\n\nWhat's next\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=bigquery)."]]