Inferensys

Glossary

Cardinality Estimation

Cardinality estimation is the process by which a database or graph query optimizer predicts the number of rows, nodes, or edges that will be returned by a specific operation in a query execution plan.
Knowledge engineer constructing knowledge base on laptop, document hierarchy visible, casual office setup.
GRAPH QUERY OPTIMIZATION

What is Cardinality Estimation?

Cardinality estimation is the process by which a query optimizer predicts the number of rows or graph elements that will be returned by a specific operation in a query plan, which is fundamental to cost-based optimization.

Cardinality estimation is the foundational process where a database or graph engine's query optimizer predicts the number of intermediate results (e.g., rows, nodes, edges) produced by each operation in a potential execution plan. This prediction feeds into a cost model to compare plans and select the most efficient one. Accurate estimation is critical for optimal join ordering and index selection, directly determining query performance. Inaccurate estimates can lead the optimizer to choose disastrously slow plans.

In graph databases, estimation is complex due to interconnected data. Optimizers analyze labeled property graph schemas, predicate selectivity, and path patterns. Techniques range from simple heuristics and histograms to advanced machine learning models trained on query workloads. Adaptive query processing systems may correct poor estimates at runtime. The core challenge is balancing estimation accuracy with the computational overhead of the analysis itself to avoid slowing down query planning.

GRAPH QUERY OPTIMIZATION

Key Characteristics of Cardinality Estimation

Cardinality estimation is the process by which a query optimizer predicts the number of rows or graph elements that will be returned by a specific operation in a query plan. Accurate estimation is fundamental to cost-based optimization, directly influencing join ordering, access path selection, and overall plan efficiency.

01

Probabilistic Foundation

Cardinality estimation is inherently probabilistic. Optimizers rely on statistical summaries of the data, such as histograms, to estimate selectivity—the fraction of rows that satisfy a given predicate. For graph queries, this extends to estimating the number of nodes matching a label or the edges traversed by a pattern. The accuracy depends heavily on the statistical independence assumption, which often breaks down with correlated data, leading to significant estimation errors.

02

Impact on Join Ordering

The estimated cardinality of intermediate results is the primary driver for join ordering decisions in relational databases and pattern matching order in graph queries. The optimizer aims to sequence joins to minimize the size of intermediate Cartesian products. A poor estimate can cause the optimizer to choose a suboptimal order, resulting in a plan that is orders of magnitude slower. For example, joining a large, incorrectly estimated result set early can blow up memory usage and CPU time.

03

Dependence on Statistics

The quality of estimation is directly tied to the database statistics maintained by the system. Key structures include:

  • Histograms: Distribute column values into buckets to estimate predicate selectivity.
  • Distinct Value Counts: The number of unique values for an attribute or label.
  • Correlation Statistics: Capture relationships between columns (e.g., multi-column statistics).
  • Graph-Specific Statistics: For property graphs, this may include degree distributions for nodes with specific labels. Outdated or missing statistics force the optimizer to use default, often inaccurate, heuristics.
04

Challenge of Correlations

A major source of estimation error is data correlation. Traditional histograms often assume attribute values are independent. In real-world data, correlations are common (e.g., city = 'New York' and state = 'NY'). A query with predicates on both correlated attributes will have its selectivity vastly underestimated if treated independently. Advanced techniques like multi-dimensional histograms, sampling, and machine learning models are used to mitigate this, but they add computational overhead.

05

Graph-Specific Complexities

In graph databases, estimation faces unique challenges:

  • Path Cardinality: Estimating the number of results for a variable-length path (e.g., (:Person)-[:KNOWS*1..5]->(:Person)) is exponentially harder, requiring models of the graph's degree distribution and clustering coefficient.
  • Label and Property Distribution: The distribution of node labels and edge types significantly impacts traversal estimates.
  • Subgraph Isomorphism: For pattern matching, the estimator must predict how many subgraphs in the data match the query pattern, which involves complex combinatorial reasoning.
06

Integration with Cost Model

Cardinality estimates are not used in isolation; they are the critical input to the optimizer's cost model. The cost model translates estimated row counts into predicted consumption of system resources (I/O, CPU cycles, memory). An operation with an estimated cardinality of 10 rows will be assigned a low cost, making it likely to be executed early. Therefore, cardinality errors propagate directly into cost miscalculations, causing the optimizer to select a genuinely expensive plan.

QUERY OPTIMIZATION TECHNIQUES

Cardinality Estimation vs. Related Concepts

A comparison of cardinality estimation with other key query optimization and processing techniques, highlighting their distinct purposes, mechanisms, and outputs.

Feature / MetricCardinality EstimationCost-Based Optimization (CBO)Approximate Query Processing (AQP)Adaptive Query Processing (AQP)

Primary Purpose

Predict the number of rows/elements returned by a query operation.

Select the lowest-cost execution plan from alternatives.

Return fast, statistically approximate answers to aggregate queries.

Dynamically adjust an executing query plan based on runtime feedback.

Core Input

Query predicates, data statistics (e.g., histograms), and graph patterns.

Cardinality estimates and a resource cost model (I/O, CPU).

Data summaries (samples, sketches, synopses).

Runtime metrics (e.g., actual intermediate result sizes).

Core Output

A numeric estimate (e.g., '~500 rows').

A selected query execution plan.

An approximate result with error bounds (e.g., '10,000 ± 200').

A modified, mid-execution query plan.

Accuracy vs. Speed Trade-off

Seeks high accuracy for plan selection; errors degrade optimization.

Depends on accuracy of cardinality estimates and cost model.

Explicitly trades precision for sub-second latency.

Improves accuracy of a running query, adding minor runtime overhead.

Typical Use Case in Query Lifecycle

Planning phase, before any data is read.

Planning phase, after cardinality estimation.

Execution phase, for interactive analytics on large data.

Execution phase, to correct for poor initial estimates.

Key Techniques

Histograms, sampling, sketch-based estimators (HyperLogLog).

Dynamic programming, heuristic search (e.g., Selinger optimizer).

Bloom filters, stratified sampling, Count-Min Sketch.

Mid-query reoptimization, eddies, adaptive join operators.

Direct Dependency on Data Statistics

Can Modify Plan During Execution

Returns Definitive Exact Result

CARDINALITY ESTIMATION

Frequently Asked Questions

Cardinality estimation is the process by which a query optimizer predicts the number of rows or graph elements that will be returned by a specific operation in a query plan, which is fundamental to cost-based optimization.

Cardinality estimation is the process by which a database or graph query optimizer predicts the number of rows, vertices, or edges that will be returned by a specific operation (like a filter, join, or traversal) in a query execution plan. It is the foundational input for cost-based optimization (CBO), which selects the most efficient plan by comparing the estimated resource consumption of alternatives. Poor cardinality estimates can lead the optimizer to choose disastrously slow plans—such as using a nested loop join for billions of rows instead of a hash join—causing query performance to degrade by orders of magnitude. Accurate estimation is therefore non-negotiable for predictable, high-performance data systems.

Prasad Kumkar

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.