logoSemaphor

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' END evaluates each of the 1,000 rows to categorize them
  • A calculated metric like SUM(Revenue) / SUM(Cost) first computes SUM(Revenue) and SUM(Cost) across all rows, then divides the two results

Calculated Metrics

Create derived metrics by combining existing fields with mathematical operations.

Supported Operations

OperationDescriptionExample
SumAdd two valuesRevenue + Shipping
DifferenceSubtract one value from anotherRevenue - Cost
RatioDivide one value by anotherRevenue / Orders
Percent of TotalCalculate percentage contributionRegion 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

  1. Open the Explorer and click + Add Calculated Field
  2. Select Calculated Metric
  3. Enter a name (e.g., "Profit Margin")
  4. Choose an operation (e.g., Ratio)
  5. Select fields for Input A and Input B
  6. Choose aggregation functions for each input
  7. Click Create Metric

Example: Average Order Value

To calculate average order value:

  • Operation: Ratio
  • Input A: Amount with SUM aggregation
  • Input B: Order ID with COUNT DISTINCT aggregation
  • 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:

CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END

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

  1. Open the Explorer and click + Add Calculated Field
  2. Select Calculated Dimension
  3. Enter a name (e.g., "Order Size Bucket")
  4. Write your SQL expression using {FieldName} tokens
  5. Click Validate Expression to check for errors
  6. Select the output type (String, Number, or Date)
  7. Click Create Dimension

Common Expression Patterns

Categorize values into buckets:

CASE
  WHEN {Amount} > 1000 THEN 'Large'
  WHEN {Amount} > 100 THEN 'Medium'
  ELSE 'Small'
END

Extract date parts:

DATE_TRUNC('month', {Order Date})

Combine text fields:

CONCAT({City}, ', ', {State})

Handle null values:

COALESCE({Discount}, 0)

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

  1. Click Generate with AI in the expression editor
  2. Describe your calculation in natural language
  3. Review the generated expression
  4. 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:

Tokens Found:
  {Amount} -> orders.amount (number)
  {Quantity} -> orders.quantity (number)

Inferred Output Type: number

Common Validation Errors

ErrorCauseSolution
Unknown field tokenField name doesn't match any available fieldCheck spelling or use the field picker
Self-reference detectedExpression references the field being editedRemove the circular reference
Unsupported functionDatabase doesn't support this SQL functionUse 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:

  1. Your card/dashboard is connected to a semantic domain (not a direct database connection)
  2. You are an organization user (tenant users cannot save to domain)

Permissions by User Type

ActionOrganization UserTenant User
View and use calculated fieldsYesYes
Create card-scoped fieldsYesYes
Create dashboard-scoped fieldsYesYes
Edit/delete card-scoped fieldsYesYes
Edit/delete dashboard-scoped fieldsYesYes
Save fields to domain scopeYesNo
Edit/delete domain-scoped fieldsYesNo

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:

ScopeAvailable ToUse Case
CardAll usersExperimental calculations, one-time analysis
DashboardAll usersFields shared across multiple charts in one dashboard
DomainOrg users onlyStandard KPIs, business metrics, and reusable dimensions used organization-wide

What can be saved to domain scope:

Field TypeDomain ScopeExample
Calculated MetricYes"Profit Margin %" — standardized calculation used across all sales dashboards
Calculated DimensionYes"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 NULLIF to prevent division by zero, COALESCE for null handling
  • Consider performance: Complex expressions on large datasets may impact query speed

Division by zero protection:

{Revenue} / NULLIF({Orders}, 0)

Null-safe calculations:

COALESCE({Discount}, 0) * {Amount}

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:

CASE
  WHEN {Total Spend} > 10000 THEN 'Enterprise'
  WHEN {Total Spend} > 1000 THEN 'Mid-Market'
  ELSE 'Small Business'
END

Output Type: String

Year-over-Year Growth

Type: Calculated Metric Expression (custom):

(SUM({Current Year Revenue}) - SUM({Previous Year Revenue}))
/ NULLIF(SUM({Previous Year Revenue}), 0)

Format: Percentage

Fiscal Quarter

Type: Calculated Dimension Expression:

CONCAT('Q', EXTRACT(QUARTER FROM {Order Date}), ' ', EXTRACT(YEAR FROM {Order Date}))

Output Type: String