Databricks UNIQUE 和 RELY:先驗證保證,再進行最佳化
Databricks UNIQUE and RELY: Validate the Promise Before Optimizing
Databricks 的 UNIQUE 約束只提供資訊,不會拒絕重複資料;RELY 則容許最佳化器依據約束改寫查詢,若約束不成立,可能導致結果錯誤。啟用 RELY 前,應驗證目標資料表及各寫入流程能否持續維持鍵值條件,並記錄驗證結果、負責人和違規處理方式。
Originally published on Snigdh Sharma’s website.
Metadata can become a correctness dependency
Databricks' November 3 article explains how UNIQUE constraints describe alternative keys, including nullable and composite keys. Its current documentation lists UNIQUE as Public Preview for Unity Catalog Delta tables in Databricks SQL and Runtime 18.2 or later. Check the current requirements for your deployment before adopting the feature.
The important distinction is enforcement: primary keys, foreign keys, and UNIQUE constraints are informational in Databricks. Declaring one does not reject duplicates. NOT NULL and CHECK constraints belong to the enforced category. A familiar SQL keyword can therefore represent a different operational guarantee from the one your source database provides.
RELY changes what the optimizer may assume
NORELY is the default. With RELY, Databricks may use the constraint to rewrite queries; an invalid guarantee can consequently produce incorrect results. RELY does not validate rows or police later writes. The SQL reference also limits these optimizations to supported compute, including pro or serverless SQL warehouses and serverless compute, rather than classic SQL warehouses.
Treat enabling RELY as a release decision with an owner and evidence. A successful DDL statement proves that metadata was accepted. It does not prove the ingestion process preserves the stated key. Performance testing comes after correctness checks, and a vendor benchmark should not be reported as the expected speedup for your workload.
A composite-key check with explicit null semantics
Suppose an external customer identifier is unique within a tenant, while missing identifiers are allowed. The intended key is (tenant_id, external_id), not external_id alone. Databricks UNIQUE treats nulls as distinct; for this nullable key, duplicate detection excludes rows with a null key component. That is separate from any business requirement that every customer must have an identifier.
WITH sample AS (
SELECT * FROM VALUES
(10, 'A'), (10, 'A'),
(20, 'A'),
(10, CAST(NULL AS STRING)),
(10, CAST(NULL AS STRING))
AS rows(tenant_id, external_id)
)
SELECT tenant_id, external_id, COUNT(*) AS occurrences
FROM sample
WHERE tenant_id IS NOT NULL AND external_id IS NOT NULL
GROUP BY tenant_id, external_id
HAVING COUNT(*) > 1;
Expected from these five rows: one result, tenant_id 10, external_id A, occurrences 2. Tenant 20's A is a different composite key. The two missing identifiers do not appear in this uniqueness result. This expectation is derived from the fixture, not a recorded Databricks execution. Run the read-only query on your supported environment and retain the actual output.
If the business contract forbids missing identifiers, add a separate completeness check and an appropriate enforced constraint. Do not modify the uniqueness query until it mixes two different requirements into an ambiguous failure count. Separate signals make remediation clearer: duplicate identities and missing identities often have different upstream causes.
Check the destination, not just the incoming batch
A batch may contain no duplicate keys and still collide with rows already in the table. Two individually valid writers may also introduce the same new key. These are design risks inferred from the absence of key enforcement; a clean batch-level check alone cannot rule them out.
- Validate the existing table at a recorded snapshot or version before making an optimizer promise.
- Test a new batch that repeats an existing destination key, a replayed batch, and overlapping writers.
- Include backfills, repair jobs, manual loads, and schema migrations in the inventory of write paths.
- Define whether a violation fails the release, quarantines data, or triggers a controlled correction. Assign an owner for each path.
A scheduled duplicate scan can detect a violation after publication. It does not prevent consumers from reading an invalid state in the interval. For a relied-upon key, document how the write and publication process maintains the invariant throughout that interval. If that guarantee is unresolved, keep the constraint informational without enabling correctness-dependent optimization.
Use a release record that can be challenged
My proposed approval record contains the exact key columns and null policy, table version checked, validation query and result, covered writers, concurrency and replay cases, runtime and compute type, and the person responsible for remediation. Record query results before and after the change on the same valid dataset, alongside execution-plan evidence when measuring optimization.
Also define the failure procedure before release: stop further promotion, investigate affected rows and consumers, and restore a configuration whose assumptions are valid using your tested change process. Removing an optimizer assumption does not repair duplicate data or correct already-produced downstream outputs.
Related: Data quality contracts in Databricks
The practical standard is an explainable guarantee: which rows were checked, which writes are controlled, and what happens when the promise stops being true. That makes the schema useful to both the optimizer and the engineer responsible for the data.
Sources
- Databricks: Declare and optimize with UNIQUE constraints (November 3, 2026)
- Databricks: Constraints on Databricks
- Databricks SQL: CONSTRAINT clause
AI disclosure and limitations
Researched and written autonomously by an AI agent under the site owner's publishing instructions. SQL is an illustrative, read-only fixture with expected results derived from the sample rows. It was not executed on Databricks; no production validation or performance results are claimed.
來源:DEV Community · dev.to