Calculated Fields
Create custom metrics and dimensions without modifying your data source
Overview
Calculated fields let you create custom metrics and dimensions directly in the Explorer. Derive new insights from your data without writing database queries or modifying your underlying data source.
Two types of calculated fields:
- Calculated Metrics: Combine existing metrics using operations like sum, difference, or ratio
- Calculated Dimensions: Create custom groupings using SQL expressions
Calculated Fields with Semantic Domains
When using a semantic domain, you can save calculated fields to the domain for organization-wide reuse. Domain-level calculated fields are managed by administrators and appear with a Domain badge in the field list.
See Domain-Level Calculated Fields for administrator setup instructions.
When Calculations Happen
Calculated Dimensions are computed before aggregation — they transform each row of data and can be used for grouping (GROUP BY). Think of them as creating new columns at the row level.
Calculated Metrics are computed after aggregation — they operate on already-aggregated values. Think of them as combining totals, averages, or counts that have already been computed.
Example: If you have 1,000 order rows:
- A calculated dimension like
CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' ENDevaluates each of the 1,000 rows to categorize them - A calculated metric like
SUM(Revenue) / SUM(Cost)first computesSUM(Revenue)andSUM(Cost)across all rows, then divides the two results
Calculated Metrics
Create derived metrics by combining existing fields with mathematical operations.
Supported Operations
| Operation | Description | Example |
|---|---|---|
| Sum | Add two values | Revenue + Shipping |
| Difference | Subtract one value from another | Revenue - Cost |
| Ratio | Divide one value by another | Revenue / Orders |
| Percent of Total | Calculate percentage contribution | Region Sales / Total Sales |
Aggregation Functions
Choose how each input field is aggregated before the calculation:
- SUM - Total of all values (default for numeric fields)
- AVG - Average value
- COUNT - Number of rows
- COUNT DISTINCT - Number of unique values
- MIN - Minimum value
- MAX - Maximum value
Creating a Calculated Metric
- Open the Explorer and click + Add Calculated Field
- Select Calculated Metric
- Enter a name (e.g., "Profit Margin")
- Choose an operation (e.g., Ratio)
- Select fields for Input A and Input B
- Choose aggregation functions for each input
- Click Create Metric
Example: Average Order Value
To calculate average order value:
- Operation: Ratio
- Input A:
AmountwithSUMaggregation - Input B:
Order IDwithCOUNT DISTINCTaggregation - Result:
SUM(Amount) / COUNT(DISTINCT Order ID)
Calculated Dimensions
Create custom groupings and categories using SQL expressions. Reference existing fields using token syntax: {FieldName}.
Expression Syntax
Use curly braces to reference fields in your expression:
The {Amount} token references the Amount field from your dataset. Semaphor resolves these tokens to the actual column names when executing the query.
Creating a Calculated Dimension
- Open the Explorer and click + Add Calculated Field
- Select Calculated Dimension
- Enter a name (e.g., "Order Size Bucket")
- Write your SQL expression using
{FieldName}tokens - Click Validate Expression to check for errors
- Select the output type (String, Number, or Date)
- Click Create Dimension
Common Expression Patterns
Categorize values into buckets:
Extract date parts:
Combine text fields:
Handle null values:
Expression syntax varies by database. Semaphor validates expressions against your connection's SQL dialect (PostgreSQL, MySQL, BigQuery, etc.).
AI-Powered Expression Generation
Describe what you want in plain English, and Semaphor generates the SQL expression for you.
Using the AI Generator
- Click Generate with AI in the expression editor
- Describe your calculation in natural language
- Review the generated expression
- Click Use Expression to apply it, or Regenerate for a different approach
Example prompts:
- "Create buckets for order amount: small under 100, medium 100-500, large over 500"
- "Extract the quarter from the order date"
- "Calculate profit as revenue minus cost"
Always review AI-generated expressions before using them. The AI provides a starting point that you can modify as needed.
Expression Validation
Semaphor validates your expressions to catch errors before you save.
What Gets Validated
- Field references: All
{FieldName}tokens must match available fields - SQL syntax: Expression must be valid SQL for your database dialect
- Self-references: Cannot reference the field being edited (prevents circular references)
- Function support: Functions must be supported by your database
Validation Feedback
After clicking Validate Expression, you'll see:
- Tokens found: Which fields were detected and resolved
- Errors: Issues that must be fixed (unknown fields, syntax errors)
- Warnings: Suggestions for improvement (missing ELSE clause, division by zero risk)
- Inferred output type: The detected data type of the result
Example validation result:
Common Validation Errors
| Error | Cause | Solution |
|---|---|---|
| Unknown field token | Field name doesn't match any available field | Check spelling or use the field picker |
| Self-reference detected | Expression references the field being edited | Remove the circular reference |
| Unsupported function | Database doesn't support this SQL function | Use an alternative function for your dialect |
Scope Options
Control where your calculated field is available.
Card Scope (Default)
The field is only available in the current card. Use this for one-off calculations specific to a single visualization.
Dashboard Scope
The field is available to all cards in the current dashboard. Use this when multiple cards need the same derived metric or dimension.
Domain Scope
Save the calculated field to your semantic domain, making it available across all dashboards that use that domain. This is ideal for standardized business metrics and commonly-used dimensions that should be consistent everywhere.
Requirements for Domain Scope
Domain scope is only available when both conditions are met:
- Your card/dashboard is connected to a semantic domain (not a direct database connection)
- You are an organization user (tenant users cannot save to domain)
Permissions by User Type
| Action | Organization User | Tenant User |
|---|---|---|
| View and use calculated fields | Yes | Yes |
| Create card-scoped fields | Yes | Yes |
| Create dashboard-scoped fields | Yes | Yes |
| Edit/delete card-scoped fields | Yes | Yes |
| Edit/delete dashboard-scoped fields | Yes | Yes |
| Save fields to domain scope | Yes | No |
| Edit/delete domain-scoped fields | Yes | No |
Organization users are employees with direct access to Semaphor. Tenant users are end users from your customers who access embedded dashboards. Domain-level fields are read-only for tenant users, ensuring consistent business logic across all customer-facing analytics.
Domain scope requires a description explaining what the field represents. This helps other users understand and correctly use the metric or dimension.
When to use each scope:
| Scope | Available To | Use Case |
|---|---|---|
| Card | All users | Experimental calculations, one-time analysis |
| Dashboard | All users | Fields shared across multiple charts in one dashboard |
| Domain | Org users only | Standard KPIs, business metrics, and reusable dimensions used organization-wide |
What can be saved to domain scope:
| Field Type | Domain Scope | Example |
|---|---|---|
| Calculated Metric | Yes | "Profit Margin %" — standardized calculation used across all sales dashboards |
| Calculated Dimension | Yes | "Fiscal Quarter" — consistent date grouping for financial reporting |
Best Practices
Naming Conventions
- Use descriptive names that explain what the field represents
- Include units when relevant (e.g., "Revenue per Order (USD)")
- Follow your organization's naming standards for consistency
Expression Design
- Keep expressions simple: Break complex calculations into multiple calculated fields
- Handle edge cases: Use
NULLIFto prevent division by zero,COALESCEfor null handling - Consider performance: Complex expressions on large datasets may impact query speed
Division by zero protection:
Null-safe calculations:
Documentation
When saving to domain scope, write clear descriptions:
For metrics:
- What the metric measures
- How it's calculated
- When to use it
- Any caveats or limitations
For dimensions:
- What the dimension represents
- How values are categorized or derived
- When to use this grouping
- Dependencies on specific datasets or fields
Examples
Profit Margin Percentage
Type: Calculated Metric Operation: Ratio Inputs:
- A:
Profit(SUM) - B:
Revenue(SUM)
Formula: SUM(Profit) / SUM(Revenue)
Format: Percentage with 2 decimals
Customer Segment
Type: Calculated Dimension Expression:
Output Type: String
Year-over-Year Growth
Type: Calculated Metric Expression (custom):
Format: Percentage
Fiscal Quarter
Type: Calculated Dimension Expression:
Output Type: String