A Data Quality Rule is a declarative or programmatic statement that defines a specific condition data must satisfy to be considered valid, such as a column being non-null, values falling within a predefined range, or adhering to a complex business logic. These rules are the executable specifications of data quality, transforming abstract requirements into automated checks. They serve as the core building blocks within frameworks like Great Expectations, dbt tests, and Soda Core, enabling test-driven development for data pipelines.
Glossary
Data Quality Rule

What is a Data Quality Rule?
A foundational concept in automated data testing, a data quality rule is a formalized condition that data must satisfy to be considered valid and fit for use.
Implemented as assertions or unit tests, data quality rules act as quality gates within pipelines, preventing invalid data from propagating. They validate everything from basic schema integrity to complex business rule validation using static or dynamic thresholds. By codifying expectations, these rules make data quality objective, automatable, and integral to the software development lifecycle, forming the basis for data reliability engineering and continuous testing.
Core Characteristics of Data Quality Rules
Data Quality Rules are the fundamental building blocks of automated data testing. They are declarative or programmatic statements that define the conditions data must meet to be considered valid and trustworthy for downstream consumption.
Declarative vs. Programmatic
Data quality rules exist on a spectrum from declarative to programmatic.
- Declarative Rules specify what condition the data must satisfy using configuration (e.g., YAML, SQL). Examples include
column X must be non-nullorvalues in column Y must be between 1 and 100. Frameworks like dbt tests and Soda Core use this approach. - Programmatic Rules define how to check the condition using code (e.g., Python, Scala). This allows for complex, custom logic, such as validating business-specific calculations or multi-column relationships. Libraries like Great Expectations support both paradigms.
The choice depends on the complexity of the validation and the need for custom logic versus simplicity and maintainability.
Scope and Granularity
Rules can be applied at different levels of a dataset, each serving a distinct purpose in the validation hierarchy.
- Schema-Level: Validate structural integrity, such as column existence, data types, and primary/foreign key constraints.
- Column-Level: Check properties of individual fields, including value ranges, allowed enumerations, format patterns (e.g., email, date), and nullability.
- Row-Level: Enforce conditions that apply to each record, like
if column A = 'X', then column B must be > 10. - Dataset-Level: Assess aggregate properties of the entire table or batch, such as row count thresholds, uniqueness of a composite key, or statistical summaries like mean and standard deviation.
Effective test coverage requires a mix of rules across all granularities.
Static vs. Dynamic Thresholds
A critical characteristic is whether a rule's pass/fail criteria are fixed or adaptive.
- Static Thresholds use hard-coded, absolute values (e.g.,
error_rate < 0.01%,latency < 500ms). They are simple to implement but can become brittle if underlying data patterns naturally evolve. - Dynamic Thresholds are calculated automatically based on historical data, often using statistical process control (SPC) methods. For example, a rule might flag a value if it falls outside 3 standard deviations of the 30-day rolling mean. This adapts to seasonality and legitimate data drift, reducing false positives.
Dynamic thresholds are essential for monitoring metrics like daily row counts or aggregate sums in production environments.
Deterministic vs. Probabilistic
Rules differ in their certainty of identifying an issue.
- Deterministic Rules produce a binary, unambiguous result. A value either conforms to a regex pattern or it does not; a foreign key either has a match in the parent table or it does not. These are used for enforcing absolute business logic and contractual guarantees.
- Probabilistic Rules identify anomalies or outliers based on statistical likelihood. They answer "is this data point unusual given historical context?" These are crucial for anomaly detection in metrics like transaction volumes or sensor readings, where some variation is expected, but significant deviations may indicate problems.
Most robust data quality postures employ a combination of both types.
Actionability and Severity
Not all rule violations are equal. A core characteristic is defining the consequence of a failure.
- Severity Levels classify a rule's importance (e.g.,
BLOCKER,WARNING). ABLOCKERfailure on a pipeline-gated test halts the data flow to prevent corrupt data from propagating. AWARNINGmay log an alert for investigation but allows the pipeline to proceed. - Actionability dictates the response. Rules should be designed to trigger specific, useful actions:
- Alert: Notify a team via Slack, PagerDuty, etc.
- Quarantine: Route failing records to a holding area for manual review.
- Block: Fail the pipeline job entirely.
- Auto-remediate: Trigger a predefined corrective workflow.
Clear severity and action links are key to effective data incident management.
Metadata and Lineage Integration
Modern data quality rules are not isolated checks; they are enriched with context and connected to the broader data ecosystem.
- Rule Metadata: Includes the rule's author, creation date, last modified timestamp, business owner, and associated SLAs or SLOs. This is vital for governance and accountability.
- Lineage Awareness: Rules should be linked to the specific data assets (tables, columns) they validate. When a rule fails, data lineage and dependency mapping tools can instantly visualize all downstream consumers impacted, drastically reducing triage time.
- Integration with Catalogs: Rule definitions and historical pass/fail results should be visible within enterprise metadata management and catalogs, providing a single pane of glass for data health.
This integration transforms rules from simple validators into intelligent components of a data observability platform.
How Data Quality Rules Are Implemented
A Data Quality Rule is a declarative or programmatic statement that defines a condition data must satisfy to be considered valid. Implementation involves embedding these rules into automated testing frameworks to enforce integrity throughout the data lifecycle.
Implementation begins by codifying rules as declarative tests or programmatic assertions within a data pipeline. These rules, which define constraints like non-null values or valid ranges, are executed by a test execution engine at specific stages, such as during ingestion or transformation. A failing rule can trigger a pipeline-gated test, halting the workflow to prevent corrupt data from propagating downstream. This practice, known as Data Quality as Code, ensures rules are version-controlled, reviewable, and reproducible.
Effective implementation requires test orchestration to schedule validations and test result aggregation for monitoring. Rules are often grouped into an expectation suite and run via a checkpoint. Advanced implementations use dynamic thresholds calculated from historical data, rather than static values, to adapt to changing data patterns. This systematic approach, integral to Continuous Testing, provides deterministic quality control, transforming subjective assessments into automated, auditable guarantees.
Common Types and Examples of Data Quality Rules
Data quality rules are categorized by the specific dimension of data integrity they enforce. This taxonomy organizes rules from foundational structural checks to complex business logic validation.
Completeness & Validity Rules
These rules enforce the presence and basic correctness of data values. They are the most fundamental checks in any data quality suite.
- Non-null Rule: Ensures a required column contains no null or empty values (e.g.,
customer_id IS NOT NULL). - Format Validity Rule: Validates that string data matches a defined pattern, such as an email address, phone number, or UUID regex.
- Domain Validity Rule: Checks that a value exists within a predefined set of allowed values (e.g.,
status IN ('active', 'inactive', 'pending')).
Accuracy & Conformity Rules
These rules verify that data correctly represents real-world entities and adheres to defined standards and schemas.
- Referential Integrity Rule: Ensures foreign key values in one table have a corresponding primary key in a related table, maintaining relational consistency.
- Schema Conformity Rule: Validates that a dataset's structure (column names, data types, nullability) matches a declared contract or expected schema.
- Cross-field Validation Rule: Checks logical relationships between columns (e.g.,
end_datemust be afterstart_date,discount_amountcannot exceedtotal_amount).
Uniqueness & Consistency Rules
These rules prevent data duplication and ensure uniform representation of information across the system.
- Primary Key Uniqueness Rule: Guarantees that a column or combination of columns meant to be a unique identifier contains no duplicate values.
- Business Key Uniqueness Rule: Ensures uniqueness on a domain-specific natural key (e.g., combination of
user_emailandsignup_date). - Consistency Rule: Validates that the same entity is represented identically across different tables or systems (e.g., a customer's name is spelled the same in all records).
Timeliness & Freshness Rules
These rules monitor the currency and delivery speed of data, which is critical for time-sensitive analytics and decision-making.
- Data Latency Rule: Measures the time elapsed between a real-world event and its availability in the data warehouse (e.g.,
event_ingestion_timestamp - event_occurred_timestamp < 5 minutes). - Pipeline Freshness Rule: Checks that a table or data asset has been updated within an expected time window (e.g.,
MAX(updated_at) > CURRENT_TIMESTAMP - INTERVAL '1 hour'). - SLA/SLO Rule: A business-oriented rule defining the acceptable thresholds for data delivery, often tied to formal service-level agreements.
Statistical & Distribution Rules
These rules use statistical methods to monitor the shape and properties of data, detecting anomalies and drift.
- Value Range Rule: Ensures numerical values fall within a minimum and maximum bound (e.g.,
age BETWEEN 0 AND 120). Can use dynamic thresholds based on historical percentiles. - Statistical Distribution Rule: Monitors that the distribution of values in a column (mean, median, standard deviation) remains within expected bounds, a core technique for data drift detection.
- Volume/Row Count Rule: Validates that the number of records in a dataset is within an expected range (e.g.,
daily_record_count BETWEEN 1000 AND 1500), alerting to ingestion failures or surges.
Business Logic & Custom Rules
These are complex, domain-specific rules that encode critical business knowledge and calculations.
- Calculated Metric Rule: Validates the correctness of a derived metric against its constituent parts (e.g.,
total_revenue = SUM(line_item_price * quantity)). - Multi-Table Business Rule: Enforces logic spanning multiple datasets (e.g., the sum of all regional sales in a fact table must equal the company-wide total in a separate summary table).
- Compliance Rule: Encodes regulatory or legal requirements (e.g.,
data_retention_days >= 7 yearsfor financial records). These are often implemented as business rule validation suites.
Data Quality Rule vs. Related Concepts
A technical comparison of a Data Quality Rule against other core concepts in automated data testing and validation, highlighting differences in scope, enforcement, and lifecycle.
| Feature / Attribute | Data Quality Rule | Data Contract | Assertion (Data) | Unit Test (Data) |
|---|---|---|---|---|
Primary Purpose | Defines a condition data must satisfy to be considered valid. | Defines a formal interface and service-level agreement for a data product. | Programmatically checks a data condition and raises an error on failure. | Validates the logic of a single data transformation against fixed inputs. |
Scope & Granularity | Single condition (e.g., column non-null, value range). | Holistic dataset interface (schema, freshness, quality, semantics). | Can be a single condition or a composite check within a pipeline. | Isolated to a specific function, view, or model logic. |
Enforcement Mechanism | Evaluated by a testing framework; may block or alert. | Enforced through producer/consumer agreement and pipeline gates. | Hard failure that stops pipeline execution if condition is false. | Part of a development test suite; fails the build. |
Lifecycle Stage | Applied continuously in development, staging, and production. | Governs the handoff between stages (e.g., development to production). | Executed at a specific point within a pipeline run. | Executed during development/CI, before deployment. |
Declarative vs. Programmatic | Typically declarative (YAML, SQL). | Declarative, codified as configuration or code. | Can be either declarative or programmatic (Python, Java). | Primarily programmatic, though can use declarative wrappers. |
Ownership & Stakeholders | Data Engineers, Data Quality Engineers. | Data Producers (Engineering) and Data Consumers (Analytics, Apps). | Data Pipeline Developers, Data Engineers. | Data Engineers, Software Developers. |
Example in Practice | 'customer_id' column values must be unique. | Table X will have schema Y, update hourly, with <0.1% nulls in key fields. | Assert that yesterday's sales table row count is within 10% of the previous day. | Test that a SQL function converting currencies returns the correct output for given inputs. |
Output on Failure | Test result (pass/fail), often with metrics. May trigger alerts. | Contract violation; may block consumption, trigger incident, break SLAs. | Pipeline error or exception, causing job failure. | Test suite failure, preventing code merge or deployment. |
Frequently Asked Questions
A data quality rule is a declarative or programmatic statement that defines a condition data must satisfy to be considered valid. These rules are the foundational building blocks of automated data testing, enabling engineers to enforce integrity, consistency, and business logic across data pipelines.
A data quality rule is a formal, executable statement that defines a condition or constraint data must meet to be considered valid, such as a column being non-null or values falling within a specific range. It works by being evaluated against a dataset, producing a pass/fail result or a quantitative metric. In practice, a rule like column 'customer_id' must be unique is codified using a framework like Great Expectations or dbt Tests, which executes a SQL query or a Python function to check for duplicates. The rule engine compares the actual data state against the declared expectation, logging failures and often blocking pipeline progression if critical rules are violated, thus acting as an automated gatekeeper for data integrity.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Data Quality Rules are implemented and executed within a broader ecosystem of testing frameworks, methodologies, and supporting concepts. These related terms define the tools and practices for programmatically validating data integrity.
Assertion (Data)
A programmatic check within a data pipeline that verifies a specific condition about the data and raises an error or warning if false. It is the fundamental building block for enforcing a Data Quality Rule.
- Implementation: Often written as a conditional statement (e.g.,
assert df['column'].isnull().sum() == 0). - Scope: Can validate row counts, value uniqueness, referential integrity, or custom business logic.
- Role: Serves as the executable instantiation of a declarative rule.
Data Contract
A formal agreement, often codified as code, that specifies the expected schema, data types, freshness, and quality guarantees for a data product. Data Quality Rules are a core component of a data contract.
- Purpose: Establishes a clear interface between data producers and consumers.
- Content: Includes structural rules (schema), behavioral rules (freshness SLOs), and quality rules (valid value ranges).
- Enforcement: Violations of contracted rules constitute a breach, triggering alerts or blocking pipeline progression.
Expectation Suite
A collection of Data Quality Rules or assertions that define the expected properties of a specific dataset. Used in frameworks like Great Expectations.
- Composition: A suite contains multiple individual expectations (e.g.,
expect_column_values_to_be_unique,expect_table_row_count_to_be_between). - Management: Suites are versioned and stored as JSON or YAML, enabling Data Quality as Code.
- Execution: Run as a batch by a Checkpoint to validate a dataset snapshot.
Pipeline-Gated Test
A Data Quality Rule whose failure prevents a data pipeline from proceeding to the next stage. It acts as a mandatory quality gate to block invalid data from propagating.
- Function: A critical assertion that halts pipeline execution or triggers a rollback.
- Examples: Verifying a primary key is unique before a merge, or ensuring a required source file has arrived.
- Outcome: Failure creates an incident that must be resolved before data flow resumes.
Declarative Testing (Data)
An approach where Data Quality Rules are specified as configuration stating what the data condition should be, rather than how to check it programmatically.
- Syntax: Uses YAML, SQL, or domain-specific languages (e.g.,
validates_uniqueness_of :user_id). - Frameworks: Exemplified by dbt Tests and Soda Core checks.
- Advantage: Separates the rule definition from the execution engine, improving portability and readability.
Business Rule Validation
The process of testing data against complex, domain-specific logic that defines correct business relationships. This extends Data Quality Rules beyond basic schema checks.
- Scope: Validates calculations, multi-column logic, and compliance with operational policies.
- Examples: "Total invoice amount equals the sum of line items," or "Discount cannot exceed 50% for premium customers."
- Complexity: Often requires custom SQL or Python assertions to implement.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us