Federated query functions

GoogleSQL for BigQuery supports the following federated query functions.

Function list

NameSummary
EXTERNAL_QUERY Executes a query on an external database and returns the results as a temporary table.

EXTERNAL_QUERY

EXTERNAL_QUERY('connection_id','''external_database_query'''[,'options'])

Description

Executes a query on an external database and returns the results as atemporary table. The external database data type isconverted to aGoogleSQL data type in the temporaryresult table withthese data type mappings.

  • external_database_query: The query to run on the external database.
  • connection_id: The ID of theconnection resource.The connection resource contains settings for the connection between theexternal database and BigQuery.If you don't have a default project configured, prepend the project ID tothe connection ID in following format:

    projects/PROJECT_ID/locations/LOCATION/connections/CONNECTION_ID

    Replace the following:

    • PROJECT_ID: The project ID.
    • LOCATION: The location of the connection.
    • CONNECTION_ID: The connection ID.

    For example,projects/example-project/locations/us/connections/sql-bq.

    Caution: If you have a view that's shared across multiple projects where you useEXTERNAL_QUERY, alwaysuse the fully qualified connection ID (projects/PROJECT_ID/locations/LOCATION/connections/CONNECTION_ID), otherwise the wrong project might be used.
  • options: An optional string of a JSON format map with key value pairs ofoption name and value (both are case sensitive).

    For example:'{"default_type_for_decimal_columns":"numeric"}'

    Supported options:

    Option NameDescription
    "default_type_for_decimal_columns"Can be "float64", "numeric", "bignumeric" or "string". With this option, the MySQL Decimal type or PostgreSQL Numeric type will be mapped to the provided BigQuery type. When this option isn't provided, the MySQL Decimal type or PostgreSQL Numeric type will be mapped to BigQuery NUMERIC type.
    "query_execution_priority"Can be "low", "medium" or "high". Only supported in Spanner. Specifies priority for execution of the query. Execution priority is "medium" by default.

Additional notes:

  • TheEXTERNAL_QUERY function is usually used in aFROM clause.
  • You can use theEXTERNAL_QUERY() function to access metadataabout the external database.
  • EXTERNAL_QUERY() won't honor the ordering of the external query result,even if your external query includesORDER BY.

Return Data Type

BigQuery table

Examples

Suppose you need the date of the first order for each of your customers toinclude in a report. This data isnot currently in BigQuery but is available in your operationalPostgreSQL database in . The following federated query exampleaccomplishes this and includes 3 parts:

  1. Run the external querySELECT customer_id, MIN(order_date) ASfirst_order_date FROM orders GROUP BY customer_id in the operationalPostgreSQL database to get the first order date for each customer throughtheEXTERNAL_QUERY() function.
  2. Join external query result table with customers table inBigQuery bycustomer_id.
  3. Select customer information and first order date.
SELECTc.customer_id,c.name,SUM(t.amount)AStotal_revenue,rq.first_order_dateFROMcustomersAScINNERJOINtransaction_factAStONc.customer_id=t.customer_idLEFTOUTERJOINEXTERNAL_QUERY('connection_id','''SELECT customer_id, MIN(order_date) AS first_order_date       FROM orders       GROUP BY customer_id''')ASrqONrq.customer_id=c.customer_idGROUPBYc.customer_id,c.name,rq.first_order_date;

You can use theEXTERNAL_QUERY() function to query information_schema tablesto access database metadata, such as list all tables in the database or showtable schema. The following example information_schema queries work in bothMySQL andPostgreSQL.

-- List all tables in a database.SELECT*FROMEXTERNAL_QUERY('connection_id','''SELECT * FROM information_schema.tables''');
-- List all columns in a table.SELECT*FROMEXTERNAL_QUERY('connection_id','''SELECT * FROM information_schema.columns WHERE table_name='x';''');

EXTERNAL_QUERY() won't honor the ordering of the external query result, evenif your external query includesORDER BY. The following example query ordersrows by customer ID in the external database, but BigQuerywill not output the result rows in that order.

-- ORDER BY will not order rows.SELECT*FROMEXTERNAL_QUERY('connection_id','''SELECT * FROM customers AS c ORDER BY c.customer_id''');

Data type mappings

When you execute a federated query, the data from the external databaseare converted to GoogleSQLtypes. Below are the data type mappings fromMySQL to BigQuery andPostgreSQL to BigQuery.

Things to know about mapping:

  • Most MySQL data types can be matched to the same BigQuery datatype, with a few exceptions such asdecimal,timestamp, andtime.
  • PostgreSQL supports many non-standard data types which aren't supportedin BigQuery, for examplemoney,path,uuid,boxer, andothers.
  • The numeric data types in MySQL and PostgreSQL will be mapped toBigQueryNUMERIC value by default. The BigQueryNUMERIC value range is smaller than in MySQL and PostgreSQL. It can also bemapped toBIGNUMERIC,FLOAT64, orSTRING with"default_type_for_decimal_columns" inEXTERNAL_QUERY options.

Error handling

If your external query contains a data type that's unsupported inBigQuery, the query will fail immediately. You can cast theunsupported data type to a different MySQL / PostgreSQL data type that issupported. Seeunsupported data typesfor more information on how to cast.

MySQL to BigQuery type mapping

MySQL typeMySQL DescriptionBigQuery typeType difference
Integer
INT4 bytes, 2^32 - 1INT64
TINYINT1 byte, 2^8 - 1INT64
SMALLINT2 bytes, 2^16 - 1INT64
MEDIUMINT3 bytes, 2^24 - 1INT64
BIGINT8 bytes, 2^64 - 1INT64
UNSIGNED BIGINT8 bytes, 2^64 - 1NUMERIC
Exact numeric
DECIMAL (M,D)A decimal represents by (M,D) where M is the total number of digits and Dis the number of decimals. M<= 65NUMERIC, BIGNUMERIC, FLOAT64, or STRING

DECIMAL (M,D) will to mapped to NUMERIC by default, or can be mapped toBIGNUMERIC, FLOAT64, or STRING withdefault_type_for_decimal_columns.
Approximate numeric
FLOAT (M,D)4 bytes, M<= 23FLOAT64
DOUBLE (M,D)8 bytes, M<= 53FLOAT64
Date and time
TIMESTAMP'1970-01-01 00:00:01'UTC to '2038-01-19 03:14:07' UTC.TIMESTAMPMySQL TIMESTAMP is retrieved as UTC timezone no matter where user callBigQuery
DATETIME'1000-01-01 00:00:00' to '9999-12-31 23:59:59'DATETIME
DATE'1000-01-01' to '9999-12-31'.DATE
TIMETime in 'HH:MM:SS' format
'-838:59:59' to '838:59:59'.
TIME
BigQuery TIME range is smaller, from 00:00:00 to 23:59:59
YEARINT64
Character and strings
ENUMstring object with a value chosen from a list of permitted valuesSTRING
CHAR (M)A fixed-length string between 1 and 255 charactersSTRING
VARCHAR (M)A variable-length string between 1 and 255 characters in length.STRING
TEXTA field with a maximum length of 65535 characters.STRING
TINYTEXTTEXT column with a maximum length of 255 characters.STRING
MEDIUMTEXTTEXT column with a maximum length of 16777215 characters.STRING
LONGTEXTTEXT column with a maximum length of 4294967295 characters.STRING
Binary
BLOBA binary large object with a maximum length of 65535 characters.BYTES
MEDIUM_BLOBA BLOB with a maximum length of 16777215 characters.BYTES
LONG_BLOBA BLOB with a maximum length of 4294967295 characters.BYTES
TINY_BLOBA BLOB with a maximum length of 255 characters.BYTES
BINARYA fixed-length binary string between 1 and 255 characters.BYTES
VARBINARYA variable-length binary string between 1 and 255 characters.BYTES
Other
SETwhen declare SET column, predefine some values. Then INSERT any set ofpredefined values into this columnSTRING
GEOMETRYGEOGRAPHYNOT YET SUPPORTED
BITINT64NOT YET SUPPORTED

PostgreSQL to BigQuery type mapping

NameDescriptionBigQuery typeType difference
Integer
smallint2 bytes, -32768 to +32767INT64
smallserialSee smallintINT64
integer4 bytes, -2147483648 to +2147483647INT64
serialSee integerINT64
bigint8 bytes, -9223372036854775808 to 9223372036854775807INT64
bigserialSee bigintINT64
Exact numeric
numeric [ (p, s) ]Precision up to 1,000.NUMERIC, BIGNUMERIC, FLOAT64, or STRINGnumeric [ (p, s) ] will to mapped to NUMERIC by default, or can be mapped toBIGNUMERIC, FLOAT64, or STRING withdefault_type_for_decimal_columns.
Decimal [ (p, s) ]See numericNUMERICSee numeric
money8 bytes, 2 digit scale, -92233720368547758.08 to +92233720368547758.07NOT SUPPORTED
Approximate numeric
real4 bytes, single precision floating-point numberFLOAT64
double precision8 bytes, double precision floating-point numberFLOAT64
Date and time
datecalendar date (year, month, day)DATE
time [ (p) ] [ without time zone ]time of day (no time zone)TIME
time [ (p) ] with time zonetime of day, including time zoneNOT SUPPORTED
timestamp [ (p) ] [ without time zone ]date and time (no time zone)DATETIME
timestamp [ (p) ] with time zonedate and time, including time zoneTIMESTAMPPostgreSQL TIMESTAMP is retrieved as UTC timezone no matter where user callBigQuery
intervalA time durationNOT SUPPORTED
Character and strings
character [ (n) ]fixed-length character stringSTRING
character varying [ (n) ]variable-length character stringSTRING
textvariable-length character stringSTRING
Binary
byteabinary data ("byte array")BYTES
bit [ (n) ]fixed-length bit stringBYTES
bit varying [ (n) ]variable-length bit stringBYTES
Other
booleanlogical Boolean (true/false)BOOL
inetIPv4 or IPv6 host addressNOT SUPPORTED
pathgeometric path on a planeNOT SUPPORTED
pg_lsnPostgreSQL Log Sequence NumberNOT SUPPORTED
pointgeometric point on a planeNOT SUPPORTED
polygonclosed geometric path on a planeNOT SUPPORTED
tsquerytext search queryNOT SUPPORTED
tsvectortext search documentNOT SUPPORTED
txid_snapshotuser-level transaction ID snapshotNOT SUPPORTED
uuiduniversally unique identifierNOT SUPPORTED
xmlXML dataSTRING
boxrectangular box on a planeNOT SUPPORTED
cidrIPv4 or IPv6 network addressNOT SUPPORTED
circlecircle on a planeNOT SUPPORTED
interval [ fields ] [ (p) ]time spanNOT SUPPORTED
jsontextual JSON dataSTRING
jsonbbinary JSON data, decomposedNOT SUPPORTED
lineinfinite line on a planeNOT SUPPORTED
lsegline segment on a planeNOT SUPPORTED
macaddrMAC (Media Access Control) addressNOT SUPPORTED
macaddr8MAC (Media Access Control) address (EUI-64 format)NOT SUPPORTED

Unsupported MySQL and PostgreSQL data types

If your external query contains a data type that's unsupported inBigQuery, the query will fail immediately. You can cast theunsupported data type to a different supported MySQL / PostgreSQL data type.

  • Unsupported MySQL data type
    • Error message:Invalid table-valued function external_query Foundunsupported MySQL type in BigQuery. at [1:15]
    • Unsupported type:GEOMETRY,BIT
    • Resolution: Cast the unsupported data type to STRING.
    • Example:SELECT ST_AsText(ST_GeomFromText('POINT(1 1)'));This command casts the unsupported data typeGEOMETRY toSTRING.
  • Unsupported PostgreSQL data type
    • Error message:Invalid table-valued function external_queryPostgres type (OID = 790) isn't supported now at [1:15]
    • Unsupported type:money, time with time zone, inet, path, pg_lsn,point, polygon, tsquery, tsvector, txid_snapshot, uuid, box, cidr, circle,interval, jsonb, line, lseg, macaddr, macaddr8
    • Resolution: Cast the unsupported data type to STRING.
    • Example:SELECT CAST('12.34'::float8::numeric::money AS varchar(30));This command casts the unsupported data typemoney tostring.

Spanner to BigQuery type mapping

When you execute a Spanner federated query, the data fromSpanner is converted to GoogleSQLtypes.

Spanner GoogleSQL typeSpanner PostgreSQL typeBigQuery type
ARRAY-ARRAY
BOOLboolBOOL
BYTESbyteaBYTES
DATEdateDATE
FLOAT64float8FLOAT64
INT64bigintINT64
JSONJSONBJSON
NUMERICnumeric*NUMERIC
STRINGvarcharSTRING
STRUCT-Not supported forSpanner federatedqueries
TIMESTAMPtimestamptzTIMESTAMP with nanoseconds truncated

* PostgreSQL numeric values with a precision that's greater than the precision that BigQuery supports are rounded. Values that are larger than the maximum value generate anInvalid NUMERIC value error.

If your external query contains a data type that's unsupported for federatedqueries, the query fails immediately. You can cast the unsupported data typeto a supported data type.

SAP Datasphere to BigQuery type mapping

When you execute aSAP Datasphere federated query,the data from SAP Datasphere is converted to the following GoogleSQLtypes.

SAP Datasphere typeSAP Datasphere descriptionBigQuery type
Integer
IntegerStandard signed integer.INT64
Integer64Signed 64-bit integer.BIGNUMERIC
hana.SMALLINTSigned 16-bit integer supporting the values -32,768 to 32,767.INT64
hana.TINYINTUnsigned 8-bit integer supporting the values 0 to 255.INT64
Exact numeric
Decimal (p, s)Precision (p) defines the number of total digits and can be between 1 and 38.

Scale (s) defines the number of digits after the decimal point and can be between 0 and p.
BIGNUMERIC
DecimalFloatDecimal floating-point number with 34 mantissa digits.BIGNUMERIC
hana.SMALLDECIMAL64-bit decimal floating-point number, where (p) can be between 1 and 16 and s can be between -369 and 368.BIGNUMERIC
Approximate numeric
DoubleDouble-precision, 64-bit floating-point number.FLOAT64
hana.REAL32-bit binary floating-point number.FLOAT64
Date and time
DateDefault format YYYY-MM-DD.DATE
DatetimeDefault format YYYY-MM-DD HH24:MI:SS.TIMESTAMP
TimeDefault format HH24:MI:SS.TIME
TimestampDefault format YYYY-MM-DD HH24:MI:SS.TIMESTAMP
Character and strings
LargeStringVariable length string of up to 2GB.STRING
String (n)Variable-length Unicode string of up to 5000 characters.STRING
Binary
Binary (n)Variable length byte string of up to 4000 bytes.BYTES
LargeBinaryVariable length byte string of up to 2GB.BYTES
hana.BINARY (n)Byte string of fixed length (n).STRING
Other
BooleanTRUE, FALSE and UNKNOWN, where UNKNOWN is a synonym of NULL.BOOL
UUIDUniversally unique identifier encoded as a 128-bit integer.STRING
hana.ST_GEOMETRYSpatial data in any form, including 0-dimensional points, lines, multi-lines, and polygons.NOT SUPPORTED
hana.ST_POINTSpatial data in the form of 0-dimensional points that represents a single location in coordinate space.NOT SUPPORTED

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-12-15 UTC.