[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-04 (世界標準時間)。"],[],[],null,["# Use primary and foreign keys\n============================\n\nPrimary keys and foreign keys are table constraints that can help with\nquery optimization. This document explains how to create, view, and manage\nconstraints, and use them to optimize your queries.\n\nBigQuery supports the following key constraints:\n\n- **Primary key** : A primary key for a table is a combination of one or more columns that is unique for each row and not `NULL`.\n- **Foreign key** : A foreign key for a table is a combination of one or more columns that is present in the primary key column of a referenced table, or is `NULL`.\n\nPrimary and foreign keys are typically used to ensure data integrity and enable\nquery optimization. BigQuery doesn't enforce primary and foreign\nkey constraints. When you declare constraints on your tables, you must ensure\nthat your data conforms to them. BigQuery can use table\nconstraints to optimize your queries.\n\nManage constraints\n------------------\n\nPrimary and foreign key relationships can be created and managed through the\nfollowing DDL statements:\n\n- Create primary and foreign key constraints when you create a table by using the [`CREATE TABLE` statement](/bigquery/docs/reference/standard-sql/data-definition-language#create_table_statement).\n- Add a primary key constraint to an existing table by using the [`ALTER TABLE ADD PRIMARY KEY` statement](/bigquery/docs/reference/standard-sql/data-definition-language#alter_table_add_primary_key_statement).\n- Add a foreign key constraint to an existing table by using the [`ALTER TABLE ADD FOREIGN KEY` statement](/bigquery/docs/reference/standard-sql/data-definition-language#alter_table_add_foreign_key_statement).\n- Drop a primary key constraint from a table by using the [`ALTER TABLE DROP PRIMARY KEY` statement](/bigquery/docs/reference/standard-sql/data-definition-language#alter_table_drop_primary_key_statement).\n- Drop a foreign key constraint from a table by using the [`ALTER TABLE DROP CONSTRAINT` statement](/bigquery/docs/reference/standard-sql/data-definition-language#alter_table_drop_constraint_statement).\n\nYou can also manage table constraints through the BigQuery API\nby updating the\n[`TableConstraints` object](/bigquery/docs/reference/rest/v2/tables#TableConstraints).\n\nView constraints\n----------------\n\nThe following views give you information about your table constraints:\n\n- The [`INFORMATION_SCHEMA.TABLE_CONSTRAINTS` view](/bigquery/docs/information-schema-table-constraints) contains information about all of the primary and foreign key constraints on tables within a dataset.\n- The [`INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE` view](/bigquery/docs/information-schema-constraint-column-usage) contains information about each table's primary key columns and columns referenced by foreign keys from other tables within a dataset.\n- The [`INFORMATION_SCHEMA.KEY_COLUMN_USAGE` view](/bigquery/docs/information-schema-key-column-usage) contains information about each table's columns that are constrained as primary or foreign keys.\n\nOptimize queries\n----------------\n\nWhen you create and enforce primary and foreign keys on your tables,\nBigQuery can use that information to eliminate or optimize\ncertain query joins. While it's possible to mimic these optimizations by\nrewriting your queries, such rewrites aren't always practical.\n\nIn a production environment, you might create views that join many fact and\ndimension tables. Developers can query the views instead of querying the\nunderlying tables and manually rewriting the joins each time. If you define\nthe proper constraints, join optimizations happen automatically for any\nqueries they apply to.\n| **Caution:** Key constraints aren't enforced in BigQuery. You are responsible for maintaining the constraints at all times. Queries over tables with violated constraints might return incorrect results.\n\nThe examples in the following sections reference the `store_sales`\nand `customer` tables with constraints: \n\n CREATE TABLE mydataset.customer (customer_name STRING PRIMARY KEY NOT ENFORCED);\n\n CREATE TABLE mydataset.store_sales (\n item STRING PRIMARY KEY NOT ENFORCED,\n sales_customer STRING REFERENCES mydataset.customer(customer_name) NOT ENFORCED,\n category STRING);\n\n### Eliminate inner joins\n\nConsider the following query that contains an `INNER JOIN`: \n\n SELECT ss.*\n FROM mydataset.store_sales AS ss\n INNER JOIN mydataset.customer AS c\n ON ss.sales_customer = c.customer_name;\n\nThe `customer_name` column is a primary key on the `customer` table, so\neach row from the `store_sales` table has either a single match, or no match\nif `sales_customer` is `NULL`. Since the query only selects columns from the\n`store_sales` table, the query optimizer can eliminate the join and rewrite the\nquery as the following: \n\n SELECT *\n FROM mydataset.store_sales\n WHERE sales_customer IS NOT NULL;\n\n### Eliminate outer joins\n\nTo remove a `LEFT OUTER JOIN`, the join keys on the right side must be unique\nand only columns from the left side are selected. Consider the following query: \n\n SELECT ss.*\n FROM mydataset.store_sales ss\n LEFT OUTER JOIN mydataset.customer c\n ON ss.category = c.customer_name;\n\nIn this example, there is no relationship between `category` and\n`customer_name`. The selected columns only come from\nthe `store_sales` table and the join key\n`customer_name` is a primary key on the `customer` table, so each value is\nunique. This means that there is exactly one (possibly `NULL`) match in the\n`customer` table for each row in the `store_sales` table and the\n`LEFT OUTER JOIN` can be eliminated: \n\n SELECT ss.*\n FROM mydataset.store_sales;\n\n### Reorder joins\n\nWhen BigQuery can't eliminate a join, it can use table\nconstraints to get information about join cardinalities and optimize the order\nin which to perform joins.\n\nLimitations\n-----------\n\nPrimary keys and foreign keys are subject to the following limitations:\n\n- Key constraints are unenforced in BigQuery. You are responsible for maintaining the constraints at all times. Queries over tables with violated constraints might return incorrect results.\n- Primary keys can't exceed 16 columns.\n- Foreign keys must have values that are present in the referenced table column. These values can be `NULL`.\n- Primary keys and foreign keys must be of one of the following types: `BIGNUMERIC`, `BOOLEAN`, `DATE`, `DATETIME`, `INT64`, `NUMERIC`, `STRING`, or `TIMESTAMP`.\n- Primary keys and foreign keys can only be set on top-level columns.\n- Primary keys can't be named.\n- Tables with primary key constraints can't be renamed.\n- A table can have up to 64 foreign keys.\n- A foreign key can't refer to a column in the same table.\n- Fields that are part of primary key constraints or foreign key constraints can't be renamed, or have their type changed.\n- If you [copy](/bigquery/docs/managing-tables#copy-table), [clone](/bigquery/docs/table-clones-create), [restore](/bigquery/docs/table-snapshots-restore), or [snapshot](/bigquery/docs/table-snapshots-create) a table without the `-a` or `--append_table` option, the source table constraints are copied and overwritten to the destination table. If you use the `-a` or `--append_table` option, only the source table records are added to the destination table without the table constraints.\n\nWhat's next\n-----------\n\n- Learn more about how to [Optimize query computation](/bigquery/docs/best-practices-performance-compute)."]]