Introduction to SQL in BigQuery
This document provides an overview of supported statements and SQL dialects inBigQuery.
GoogleSQL is an ANSI-compliantStructured Query Language (SQL)that includes the following types of supported statements:
- Query statements, alsoknown as Data Query Language (DQL) statements, are the primary method toanalyze data in BigQuery. They scan one or more tables orexpressions and return the computed result rows. Query statements canincludepipe syntax.
- Procedural language statementsare procedural extensions toGoogleSQL that allow you to execute multiple SQLstatements in one request. Procedural statements can use variables andcontrol-flow statements, and can have side effects.
Data Definition Language (DDL) statementslet you create and modify objects such as the following:
- Datasets
- Tables, including their schema and column types
- Table clones and snapshots
- Views
- Functions
- Indexes
- Capacity commitments, reservations, and assignments
- Row-level access policies
Data Manipulation Language (DML) statementsenable you to update, insert, and delete data from yourBigQuery tables.
Data Control Language (DCL) statementslet you control BigQuery system resources such as access andcapacity.
Transaction Control Language (TCL) statementsallow you to manage transactions for data modifications.
Load statementsandexport statementsto manage data coming in and out of BigQuery.
BigQuery SQL dialects
BigQuery supports the GoogleSQL dialect, but a legacySQL dialect is also available. If you are new to BigQuery, youshould use GoogleSQL as it supports the broadest range offunctionality. For example, features such as DDL and DML statements are onlysupported using GoogleSQL. Legacy SQL is maintained for backwardcompatibility and we recommend that customersmigrateif they are using legacy SQL.
Changing from the default dialect
The interface you use to query your data determines which query dialect is thedefault. To switch to a different dialect:
Console
The default dialect for the Google Cloud console is GoogleSQL. Tochange the dialect to legacy SQL:
In the Google Cloud console, go to theBigQuery page.
In the query editor, click theMore > Query settings button.
In theAdvanced options section, forSQL dialect, clickLegacy, then clickSave. This sets the legacy SQL option for thisquery. When you clickadd_boxSQL Query to create a new query, you must select the legacy SQL optionagain.
SQL
The default SQL dialect is GoogleSQL.You can set the SQL dialect by including the prefix#standardSQL
or#legacySQL
as part of your query.These query prefixes are not case-sensitive, must precede the query, andmust be separated from the query by a newline character. The followingexample sets the dialect to legacy SQL and queries the natality dataset:
In the Google Cloud console, go to theBigQuery page.
In the query editor, enter the following statement:
#legacySQLSELECTweight_pounds,state,year,gestation_weeksFROM[bigquery-public-data:samples.natality]ORDERBYweight_poundsDESCLIMIT10;
Click
Run.
For more information about how to run queries, seeRun an interactive query.
bq
The default query dialect in thebq
command-line tool is legacy SQL. Toswitch to the GoogleSQL dialect, add the--use_legacy_sql=false
or--nouse_legacy_sql
flag to your command-line statement.
Switch to the GoogleSQL dialect
To use GoogleSQL syntax in a query job, set theuse_legacy_sql
parameter tofalse
.
bqquery\--use_legacy_sql=false\'SELECT word FROM `bigquery-public-data.samples.shakespeare`'
Set GoogleSQL as the default dialect
You can set GoogleSQL as the default dialect for the command-line tool andthe interactive shell by editing the command-line tool's configuration file:.bigqueryrc
.
For more information on.bigqueryrc
, seeSetting default values for command-specific flags.
To set--use_legacy_sql=false
in.bigqueryrc
:
- Open
.bigqueryrc
in a text editor. By default,.bigqueryrc
should be inyour user directory, for example,$HOME/.bigqueryrc
. Add the following text to the file. This example sets GoogleSQL as thedefault syntax for queries and for the
mk
command (used when you create aview). If you have already configured default values forquery
ormk
commandflags, you do not need to add[query]
or[mk]
again.[query]--use_legacy_sql=false[mk]--use_legacy_sql=false
Save and close the file.
If you are using the interactive shell, you must exit and restart for the changes to be applied.
For information on available command-line flags, seebq command-line tool reference.
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.
Switch to the legacy SQL dialect
To use legacy SQL syntax in a query job, set theUseLegacySql
parameter totrue
.
usingGoogle.Cloud.BigQuery.V2;usingSystem;publicclassBigQueryQueryLegacy{publicvoidQueryLegacy(stringprojectId="your-project-id"){BigQueryClientclient=BigQueryClient.Create(projectId);stringquery=@" SELECT name FROM [bigquery-public-data:usa_names.usa_1910_2013] WHERE state = 'TX' LIMIT 100";BigQueryJobjob=client.CreateQueryJob(sql:query,parameters:null,options:newQueryOptions{UseLegacySql=true});// Wait for the job to complete.job=job.PollUntilCompleted().ThrowOnAnyError();// Display the resultsforeach(BigQueryRowrowinclient.GetQueryResults(job.Reference)){Console.WriteLine($"{row["name"]}");}}}
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.
Switch to the legacy SQL dialect
To use legacy SQL syntax in a query job, set theUseLegacySQL
propertywithin the query configuration totrue
.
import("context""fmt""io""cloud.google.com/go/bigquery""google.golang.org/api/iterator")// queryLegacy demonstrates running a query using Legacy SQL.funcqueryLegacy(wio.Writer,projectID,sqlStringstring)error{// projectID := "my-project-id"// sqlString = "SELECT 3 as somenum"ctx:=context.Background()client,err:=bigquery.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("bigquery.NewClient: %w",err)}deferclient.Close()q:=client.Query(sqlString)q.UseLegacySQL=true// 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.
Switch to the legacy SQL dialect
To use legacy SQL syntax in a query job, set theuseLegacySql
parametertotrue
.
importcom.google.cloud.bigquery.BigQuery;importcom.google.cloud.bigquery.BigQueryException;importcom.google.cloud.bigquery.BigQueryOptions;importcom.google.cloud.bigquery.QueryJobConfiguration;importcom.google.cloud.bigquery.TableResult;publicclassRunLegacyQuery{publicstaticvoidmain(String[]args){runLegacyQuery();}publicstaticvoidrunLegacyQuery(){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();// To use legacy SQL syntax, set useLegacySql to true.Stringquery="SELECT corpus FROM [bigquery-public-data:samples.shakespeare] GROUP BY corpus;";QueryJobConfigurationqueryConfig=QueryJobConfiguration.newBuilder(query).setUseLegacySql(true).build();// Execute the query.TableResultresult=bigquery.query(queryConfig);// Print the results.result.iterateAll().forEach(rows->rows.forEach(row->System.out.println(row.getValue())));System.out.println("Legacy query ran successfully");}catch(BigQueryException|InterruptedExceptione){System.out.println("Legacy query did not run \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.
Switch to the legacy SQL dialect
To use legacy SQL syntax in a query job, set theuseLegacySql
parametertotrue
.
// Import the Google Cloud client libraryconst{BigQuery}=require('@google-cloud/bigquery');constbigquery=newBigQuery();asyncfunctionqueryLegacy(){// Queries the U.S. given names dataset for the state of Texas using legacy SQL.constquery='SELECT word FROM [bigquery-public-data:samples.shakespeare] LIMIT 10;';// For all options, see https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/queryconstoptions={query:query,// Location must match that of the dataset(s) referenced in the query.location:'US',useLegacySql:true,};// Run the query as a jobconst[job]=awaitbigquery.createQueryJob(options);console.log(`Job${job.id} started.`);// Wait for the query to finishconst[rows]=awaitjob.getQueryResults();// Print the resultsconsole.log('Rows:');rows.forEach(row=>console.log(row));}
PHP
Before trying this sample, follow thePHP setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryPHP API reference documentation. To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
Switch to the legacy SQL dialect
To use legacy SQL syntax in a query job, set theuseLegacySql
parametertotrue
.
use Google\Cloud\BigQuery\BigQueryClient;/** * Query using legacy sql * * @param string $projectId The project Id of your Google Cloud Project. */function query_legacy(string $projectId): void{ $query = 'SELECT corpus FROM [bigquery-public-data:samples.shakespeare] GROUP BY corpus'; $bigQuery = new BigQueryClient([ 'projectId' => $projectId, ]); $jobConfig = $bigQuery->query($query)->useLegacySql(true); $queryResults = $bigQuery->runQuery($jobConfig); $i = 0; foreach ($queryResults as $row) { printf('--- Row %s ---' . PHP_EOL, ++$i); foreach ($row as $column => $value) { printf('%s: %s' . PHP_EOL, $column, json_encode($value)); } } printf('Found %s row(s)' . PHP_EOL, $i);}
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.
Switch to the legacy SQL dialect
To use legacy SQL syntax in a query job, set theuse_legacy_sql
parametertoTrue
.
fromgoogle.cloudimportbigquery# Construct a BigQuery client object.client=bigquery.Client()query=("SELECT name FROM [bigquery-public-data:usa_names.usa_1910_2013] "'WHERE state = "TX" '"LIMIT 100")# Set use_legacy_sql to True to use legacy SQL syntax.job_config=bigquery.QueryJobConfig(use_legacy_sql=True)# Start the query and waits for query job to complete, passing in the extra configuration.results=client.query_and_wait(query,job_config=job_config)# Make an API request.print("The query data:")forrowinresults:print(row)
Ruby
Before trying this sample, follow theRuby setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryRuby API reference documentation. To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
Switch to the legacy SQL dialect
To use legacy SQL syntax in a query job, pass the optionlegacy_sql: true
with your query.
require"google/cloud/bigquery"defquery_legacybigquery=Google::Cloud::Bigquery.newsql="SELECT name FROM [bigquery-public-data:usa_names.usa_1910_2013] "\"WHERE state = 'TX' "\"LIMIT 100"results=bigquery.querysql,legacy_sql:truedo|config|# Location must match that of the dataset(s) referenced in the query.config.location="US"endresults.eachdo|row|putsrow.inspectendend
What's next
- For information about how to run a SQL query in BigQuery, seeRunning interactive and batch query jobs.
- For more information about query optimization in general, seeIntroduction to optimizing query performance.
- To learn about the GoogleSQL syntax used for querying data inBigQuery, seeQuery syntax.
- To learn more about how to use pipe syntax in your queries, seepipe syntax.
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 2025-10-02 UTC.