제약조건 정의는 CONSTRAINT 키워드로 시작합니다. 이 예시에서는 오류 메시지에서 찾고 필요할 때마다 참조하는 데 도움이 되도록 제약 조건 이름을 명시적으로 start_before_end로 지정했습니다. 이름을 지정하지 않으면 Spanner에서 CK_ 프리픽스로 시작하는 생성된 이름의 제약 조건을 제공합니다. 제약 조건 이름은 테이블과 색인의 이름을 통해 스키마로 범위가 제한되며 스키마 내에서 고유해야 합니다. 확인 제약 조건 정의는 CHECK 키워드와 괄호로 묶인 표현식으로 구성됩니다. 표현식은 이 테이블의 열만 참조할 수 있습니다. 이 예시에서는 StartTime 및 EndTime을 참조하고 확인 제약 조건에서 연주회 시작 시간이 항상 종료 시간보다 이전인지 확인합니다.
확인 제약 조건 표현식 값은 새 행이 삽입될 때 또는 기존 행의 StartTime 또는 EndTime이 업데이트될 때 평가됩니다. 표현식이 TRUE 또는 NULL로 평가될 경우 확인 제약조건에서 데이터 변경이 허용됩니다. 표현식이 FALSE로 평가되면 데이터 변경이 허용되지 않습니다.
다음 제약조건이 확인 제약조건 expression 항에 적용됩니다.
이 표현식은 동일 테이블의 열만 참조할 수 있습니다.
표현식은 직접 또는 비생성 열을 참조하는 생성 열을 통해 하나 이상의 비생성 열을 참조해야 합니다.
표현식은 allow_commit_timestamp 옵션이 설정된 열을 참조할 수 없습니다.
다시 한 번 제약조건에 concert_id_gt_0 이름을 지정했습니다. 기존 테이블에 CHECK 제약조건을 추가하면 새 데이터에 대해 즉시 제약조건이 적용되고 기존 데이터가 새 제약조건을 준수하는지 확인하는 장기 실행 작업이 시작됩니다. 이러한 검사가 장기 실행 작업으로 수행되기 때문에 테이블에서 진행 중인 트랜잭션은 영향을 받지 않습니다. 자세한 내용은 스키마 업데이트 성능을 참조하세요. 기존 데이터에 위반 사항이 있으면 제약조건이 롤백됩니다.
확인 제약조건 삭제
다음 DDL 문은 Concerts 테이블에서 CHECK 제약 조건을 삭제합니다.
ALTERTABLEConcertsDROPCONSTRAINTconcert_id_gt_0;
확인 제약조건 표현식 수정
CHECK 제약조건의 표현식 수정은 허용되지 않습니다. 대신 새 표현식으로 기존 제약조건을 삭제하고 새 제약조건을 생성해야 합니다.
확인 제약조건의 속성 보기
Spanner의 INFORMATION_SCHEMA에는 데이터베이스의 확인 제약 조건에 대한 정보가 포함되어 있습니다. 다음은 정보 스키마를 쿼리하여 답변할 수 있는 몇 가지 질문의 예시입니다.
기존 테이블에 확인 제약조건을 추가한 경우, 모든 기존 데이터가 제약조건에 대해 검증되었는지 여부와 같이 현재 상태를 확인해야 할 수 있습니다. SPANNER_STATE가 다음 쿼리로 VALIDATING_DATA를 반환하는 경우 이는 Spanner가 해당 제약 조건에 대해 기존 데이터를 계속 검증하고 있음을 나타냅니다.
[[["이해하기 쉬움","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-05(UTC)"],[],[],null,["# Create and manage check constraints\n\nA `CHECK` constraint lets you specify that the values of one or more columns\nmust satisfy a boolean expression. In this page, we describe how to add and\nmanage this type of constraint in GoogleSQL-dialect databases and PostgreSQL-dialect databases.\n\nAdd a check constraint to a new table\n-------------------------------------\n\nIn the following `CREATE TABLE` snippet, we create a table to store information\nabout concerts.\nTo require that the end time of a concert is later than its start time, we\ninclude a check constraint. \n\n### GoogleSQL\n\n CREATE TABLE Concerts (\n ConcertId INT64,\n StartTime Timestamp,\n EndTime Timestamp,\n CONSTRAINT start_before_end CHECK(StartTime \u003c EndTime),\n ) PRIMARY KEY (ConcertId);\n\n### PostgreSQL\n\n CREATE TABLE Concerts (\n ConcertId BIGINT,\n StartTime TIMESTAMPTZ,\n EndTime TIMESTAMPTZ,\n CONSTRAINT start_before_end CHECK(StartTime \u003c EndTime),\n PRIMARY KEY (ConcertId)\n );\n\nThe constraint definition begins with the `CONSTRAINT` keyword. We've explicitly\nnamed the constraint `start_before_end` in this example to help you find it in\nerror messages and whenever we need to refer to it. If no name is given,\nSpanner provides one, with the generated name beginning with\nthe prefix `CK_`. Constraint names are scoped to the schema, along with the\nnames for tables and indexes, and must be unique within the schema. The check\nconstraint definition consists of the keyword `CHECK` followed by an expression\nin parentheses. The expression can only reference columns of this table. In this\nexample, it references **StartTime** and **EndTime**, and the check constraint\nmakes sure that the start time of a concert is always less than the end time.\n\nThe value of the check constraint expression is evaluated when a new row is\ninserted or when the `StartTime` or `EndTime` of an existing row are updated. If\nthe expression evaluates to `TRUE` or `NULL`, the data change is allowed by the\ncheck constraint. If the expression evaluates to `FALSE`, the data change is not\nallowed.\n\n- The following restrictions apply to a check constraint `expression` term.\n\n - The expression can only reference columns in the same table.\n\n - The expression must reference at least one non-generated column, whether\n directly or through a generated column which references a non-generated\n column.\n\n - The expression can't reference columns that have set the\n `allow_commit_timestamp` option.\n\n - The expression can't contain [subqueries](/spanner/docs/reference/standard-sql/subqueries).\n\n - The expression can't contain non-deterministic functions, such as\n [`CURRENT_DATE()`](/spanner/docs/reference/standard-sql/date_functions#current_date)\n and\n [`CURRENT_TIMESTAMP()`](/spanner/docs/reference/standard-sql/timestamp_functions#current_timestamp).\n\nAdd a check constraint to an existing table\n-------------------------------------------\n\nUsing the following `ALTER TABLE` statement, we add a constraint to make sure\nthat all concert ids are greater than zero. \n\n ALTER TABLE Concerts\n ADD CONSTRAINT concert_id_gt_0 CHECK (ConcertId \u003e 0);\n\nOnce again, we've given the constraint a name, **concert_id_gt_0** . Adding a\n`CHECK` constraint to an existing table starts the enforcement of the constraint\nimmediately for new data and starts a long-running operation to validate that\nexisting data conforms to the new constraint. Because this validation is\nperformed as a long-running operation, ongoing transactions on the table are not\nimpacted. For more information, see [Schema update performance](/spanner/docs/schema-updates#performance). If there are\nany violations on existing data, the constraint is rolled back.\n\nRemove a check constraint\n-------------------------\n\nThe following DDL statement drops a `CHECK` constraint from the `Concerts`\ntable. \n\n ALTER TABLE Concerts\n DROP CONSTRAINT concert_id_gt_0;\n\nModify a check constraint expression\n------------------------------------\n\nModifying the expression of a `CHECK` constraint is not allowed. Instead, you\nneed to drop the existing constraint and create a new constraint with the new\nexpression.\n\nView properties of a check constraint\n-------------------------------------\n\nSpanner's [INFORMATION_SCHEMA](/spanner/docs/information-schema) contains information about\nthe check constraints on your database. The following are some examples of the\nquestions you can answer by querying the information schema.\n\n*What check constraints are defined in my database?* \n\n SELECT tc.CONSTRAINT_NAME, tc.TABLE_NAME, tc.CONSTRAINT_TYPE\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc\n WHERE tc.CONSTRAINT_TYPE = 'CHECK';\n\n*What is the current state of the check constraints in my database?*\n\nIf you have added a check constraint to an existing table, you might want to\nview its current state to determine, for example, whether all existing data has\nbeen validated against the constraint. If `SPANNER_STATE` returns\n`VALIDATING_DATA` in the following query, it means\nSpanner is still in the process of validating existing data\nagainst that constraint. \n\n SELECT cc.CONSTRAINT_NAME, cc.SPANNER_STATE\n FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS as cc;\n\nWhat's next\n-----------\n\n- Learn more about Spanner's [INFORMATION SCHEMA](/spanner/docs/information-schema)."]]