Skip to main content
SQL billing rules for MSPs let you modify cost data using SQL statements to apply custom pricing adjustments, discounts, markups, and exclusions based on your customer agreements. You can write SQL queries that run against either raw AWS Cost and Usage Report (CUR) data or processed Vantage cost data.

Need Help Writing a Rule?

AI assistant conversation preview showing a billing rule being drafted

AI-Assisted Billing Rules

Describe what you need in plain language. The docs assistant will draft, validate, or troubleshoot your SQL using the reference on this page.

SQL Billing Rule Datasets

SQL billing rules comprise two different datasets:
DatasetDescriptionWhen to Use
awsRaw AWS Cost and Usage Report (CUR) data.• Modify raw AWS CUR data before processing
• Access columns of data that are not available in Vantage Cost Reports
• Work with Reserved Instances, Savings Plans
costsVantage-processed cost data. Use when inserting or adjusting normalized costs.• Apply provider-agnostic billing rules
Rules written against aws only affect how data appears in Vantage and do not modify the original CUR file.

AWS Dataset

For the aws dataset, you can query a supported subset of AWS CUR columns. Use the Available Columns list in the billing rule editor to see all queryable fields. Custom resource_tag_% columns that vary by account are not supported, though a small set of predefined resource tag columns are available.
See the AWS Data Exports Data Dictionary for column definitions.
Expand the section below for the full list of supported aws columns, organized by CUR table. Use the format aws.table/ColumnName in your SQL (e.g., aws.lineItem/UnblendedCost). Quotes around the column name are optional; the editor accepts both aws.lineItem/UnblendedCost and aws."lineItem/UnblendedCost".
bill: BillingEntity, BillingPeriodEndDate, BillingPeriodStartDate, BillType, InvoiceId, InvoicingEntity, PayerAccountId
The bill/BillingEntity field identifies whether a charge is for an AWS service or an AWS Marketplace purchase. These values are defined by AWS in the CUR Billing Details documentation.
ValueDescription
AWSAWS services (non-Marketplace)
AWS MarketplacePurchases through AWS Marketplace
The bill/BillType field indicates the type of bill that the line item covers. These values are defined by AWS in the CUR Billing Details documentation.
ValueDescription
AnniversaryLine items for services used during the billing month
PurchaseLine items for upfront service fees
RefundLine items for refunds
costCategory: Project, Team, Environmentdiscount: BundledDiscount, TotalDiscountidentity: LineItemId, TimeIntervallineItem: AvailabilityZone, BlendedCost, BlendedRate, CurrencyCode, LegalEntity, LineItemDescription, LineItemType, NetUnblendedRate, NormalizationFactor, NormalizedUsageAmount, Operation, ProductCode, ResourceId, TaxType, UnblendedCost, UnblendedRate, UsageAccountId, UsageAmount, UsageEndDate, UsageStartDate, UsageType
The lineItem/ProductCode field contains the AWS service code for the line item. The table below lists commonly used product codes. This is not an exhaustive list. AWS product codes can change as services are added or renamed.
Product CodeService
AmazonAthenaAmazon Athena
AmazonCloudFrontAmazon CloudFront
AmazonCloudWatchAmazon CloudWatch
AmazonCognitoAmazon Cognito
AmazonDocDBAmazon DocumentDB
AmazonDynamoDBAmazon DynamoDB
AmazonEC2Amazon Elastic Compute Cloud
AmazonECRAmazon Elastic Container Registry
AmazonECSAmazon Elastic Container Service
AmazonEFSAmazon Elastic File System
AmazonEKSAmazon Elastic Kubernetes Service
AmazonElastiCacheAmazon ElastiCache
AmazonEMRAmazon EMR
AmazonESAmazon OpenSearch Service (legacy code)
AmazonGuardDutyAmazon GuardDuty
AmazonKinesisAmazon Kinesis
AmazonLightsailAmazon Lightsail
AmazonMQAmazon MQ
AmazonMSKAmazon Managed Streaming for Apache Kafka
AmazonNeptuneAmazon Neptune
AmazonQuickSightAmazon QuickSight
AmazonRDSAmazon Relational Database Service
AmazonRedshiftAmazon Redshift
AmazonRoute53Amazon Route 53
AmazonS3Amazon Simple Storage Service
AmazonSageMakerAmazon SageMaker
AmazonSESAmazon Simple Email Service
AmazonSNSAmazon Simple Notification Service
AmazonSQSAmazon Simple Queue Service
AmazonVPCAmazon Virtual Private Cloud
AmazonWorkSpacesAmazon WorkSpaces
AWSBackupAWS Backup
AWSCloudTrailAWS CloudTrail
AWSCodeBuildAWS CodeBuild
AWSConfigAWS Config
AWSDataTransferAWS Data Transfer
AWSDirectConnectAWS Direct Connect
AWSELBElastic Load Balancing
AWSFargateAWS Fargate
AWSGlueAWS Glue
AWSKMSAWS Key Management Service
AWSLambdaAWS Lambda
AWSSecretsManagerAWS Secrets Manager
AWSShieldAWS Shield
AWSStepFunctionsAWS Step Functions
AWSSystemsManagerAWS Systems Manager
AWSTransferFamilyAWS Transfer Family
AWSWAFAWS WAF
This is not an exhaustive list. Verify product codes against the AWS Data Exports Data Dictionary or the product code values in your CUR data.
The lineItem/LineItemType field indicates the type of charge on each CUR row. These values are defined by AWS in the CUR Line Item Details documentation.
ValueDescription
BundledDiscountUsage-based discount from using another service or feature
CreditCredits applied to your bill
DiscountDiscounts applied to your usage
DiscountedUsageUsage covered by Reserved Instance benefits
FeeUpfront annual fee for subscriptions (e.g., All Upfront RI)
RefundNegative charges for refunds
RIFeeMonthly recurring fee for Reserved Instance subscriptions
SavingsPlanCoveredUsageOn-demand cost covered by Savings Plans
SavingsPlanNegationOffset cost from Savings Plans benefits
SavingsPlanRecurringFeeRecurring hourly charges for Savings Plans
SavingsPlanUpfrontFeeOne-time upfront fee for Savings Plans
TaxTaxes applied to your bill
UsageUsage charged at on-demand rates
pricing: LeaseContractLength, OfferingClass, publicOnDemandCost, publicOnDemandRate, PurchaseOption, RateCode, RateId, term, unit
The pricing/term field indicates whether usage is On-Demand or Reserved. These values are defined by AWS in the CUR Pricing Details documentation. This field is empty for Spot Instances, Savings Plan rows, and Marketplace purchases.
ValueDescription
OnDemandUsage billed at on-demand rates
ReservedUsage covered by Reserved Instance terms
The pricing/PurchaseOption field indicates the payment model for a Reserved Instance. These values are defined by AWS in the CUR Pricing Details documentation.
ValueDescription
All UpfrontFull upfront payment, no monthly charges
Partial UpfrontPartial upfront payment with recurring monthly charges
No UpfrontNo upfront payment, all recurring monthly charges
product: APICalls, attachmentType, availability, cacheType, capacitystatus, clockspeed, component, databaseedition, dataTransfer, dedicatedEbsThroughput, deploymentoption, description, destinationCountryISOCode, directconnectlocation, directorysize, directorytype, directorytypedescription, disableactivationconfirmationemail, durability, ebsOptimized, ecu, endpointtype, enhancedNetworkingSupported, filesystemtype, findingGroup, findingSource, freeUsageIncluded, fromLocation, fromRegionCode, fromLocationType, gpu, gpuMemory, group, groupdescription, insightsType, instance, instanceFamily, instanceSize, instanceType, instanceTypeFamily, integratingApi, integratingService, intelAvxAvailable, intelAvx2Available, intelTurboAvailable, invocation, licenseModel, location, locationType, logsDestination, maxIopsBurstPerformance, maxIopsvolume, maxThroughputvolume, memory, messageCountfee, messageType, networkPerformance, normalizationSizeFactor, operatingSystem, operation, originationIdType, osType, parameterType, physicalCores, physicalProcessor, platoClassificationType, pricingUnit, primaryplaceofuse, processorArchitecture, processorFeatures, ProductFamily, ProductName, productSchemaDescription, provisioned, provisioningType, PurchaseOption, purchaseterm, region, regioncode, replicationType, resourceAssessment, resourcePriceGroup, routeType, servicecode, servicename, singleOrDualPass, sizeFlex, sku, storage, storageclass, storagemedia, storagetype, tenancy, throughputCapacity, tier, toLocation, toLocationType, toRegionCode, transcodingResult, trialProduct, upfrontCommitment, usagetype, vcpu, videoCodec, videoFrameRate, videoQualitySetting, volumeType, workforceType
The product/ProductFamily field categorizes the type of product. The table below lists commonly seen values. This is not an exhaustive list; product family values vary by service and can change over time.
ValueTypical Services
AlarmCloudWatch Alarms
API RequestS3, DynamoDB, API Gateway
AWS BudgetsAWS Budgets
BundleWorkSpaces, Lightsail
Cache InstanceElastiCache
Cloud ConnectivityDirect Connect, VPN
ComputeEC2
Compute InstanceEC2, RDS, ElastiCache, Redshift
CPU CreditsT-family burstable instances
Data TransferCross-region/cross-AZ transfers, CloudFront
Database InstanceRDS, Neptune, DocumentDB
DNS QueryRoute 53
Elastic IPEC2 Elastic IPs
FeeVarious upfront fees
Hosted ZoneRoute 53
IP AddressPublic IPv4 addresses
Load BalancerClassic Load Balancer
Load Balancer-ApplicationApplication Load Balancer
Load Balancer-NetworkNetwork Load Balancer
Machine LearningSageMaker
NAT GatewayVPC NAT Gateways
Provisioned IOPSEBS io1/io2 IOPS
Provisioned ThroughputDynamoDB
ServerlessLambda, Fargate
StorageS3, EBS, Glacier
Storage SnapshotEBS Snapshots, RDS Snapshots
Stopped InstanceStopped EC2 instances
System OperationEBS, RDS storage operations
This is not an exhaustive list. Product family values vary by service and can change over time. Verify against the AWS Data Exports Data Dictionary or the values in your CUR data.
reservation: AmortizedUpfrontCostForUsage, AmortizedUpfrontFeeForBillingPeriod, AvailabilityZone, EffectiveCost, EndTime, ModificationStatus, NetAmortizedUpfrontCostForUsage, NetAmortizedUpfrontFeeForBillingPeriod, NetEffectiveCost, NetRecurringFeeForUsage, NetUnusedAmortizedUpfrontFeeForBillingPeriod, NetUnusedRecurringFee, NetUpfrontValue, NormalizedUnitsPerReservation, NumberOfReservations, RecurringFeeForUsage, ReservationARN, StartTime, SubscriptionId, TotalReservedNormalizedUnits, TotalReservedUnits, UnitsPerReservation, UnusedAmortizedUpfrontFeeForBillingPeriod, UnusedNormalizedUnitQuantity, UnusedQuantity, UnusedRecurringFee, UpfrontValueresourceTags: user:creator, user:name, user:owner, user:purposesavingsPlan: AmortizedUpfrontCommitmentForBillingPeriod, EndTime, InstanceTypeFamily, NetAmortizedUpfrontCommitmentForBillingPeriod, NetRecurringCommitmentForBillingPeriod, NetSavingsPlanEffectiveCost, OfferingType, PaymentOption, PurchaseTerm, RecurringCommitmentForBillingPeriod, Region, SavingsPlanARN, SavingsPlanEffectiveCost, SavingsPlanRate, StartTime, TotalCommitmentToDate, UsedCommitmentsplitLineItem: ActualUsage, NetSplitCost, NetUnusedCost, ParentResourceId, PublicOnDemandSplitCost, PublicOnDemandUnusedCost, SplitCost, SplitUsage, SplitUsageRatio, UnusedCost

Costs Dataset

The table below is the full data dictionary of all costs columns you can use in billing rule SQL.
ColumnTypeDescriptionExample Values
amountdecimalCost amount in the specified currency100.18
cost_categorystringHigh-level cost categoryAPI Request, Compute Instance, Storage
cost_sub_categorystringDetailed cost subcategoryDataTransfer-Out-Bytes
cost_typestringCharge type (see supported cost_type values below)Usage, SppDiscount, Fee
currency_codestringCurrency codeUSD, EUR
datestringDate of the cost line item2026-01-01
providerstringCloud provider (see supported providers below)aws, azure, gcp, snowflake
provider_account_idstringProvider-level account ID. For AWS, the payer account. For Azure, see Azure-Specific Field Mapping.111111111111
regionstringRegionus-east-1, us-west-2
resource_account_idstringResource-level account ID. For AWS, the linked/usage account. For Azure, see Azure-Specific Field Mapping.222222222222
resource_idstringUnique resource identifierarn:aws:ec2:...
servicestringService name (may differ from CUR product code after normalization)Amazon S3, Azure Databricks
usage_amountdecimalAmount of usage25
usage_unitstringUnit of measurementrequest, GB, Hours

Supported Cost Type Values

The cost_type column corresponds to the Charge Type filter in Cost Reports. Expand the section below for the exact raw costs.cost_type values you can use in SQL.
Exact costs.cost_type ValueDefinition
adjustmentGCP adjustments due to reasons like goodwill or SLA violations.
AllocatedAmortizedDiscountSavings from commitment-based pricing allocated to the account consuming the commitment. Appears as a negative amount that reduces effective cost from on-demand pricing to the commitment rate.
AllocatedAmortizedFeeSavings Plans and Reserved Instances that have been amortized and allocated to an account with usage. This value can appear as a negative cost in the payer account because it is subtracted from the payer account and added to a member account.
AmortizedBundledDiscountAmortized variant of BundledDiscount. Appears when amortization and discounts are both enabled.
AmortizedCreditCredit charges that span multiple billing days, amortized across the covered period.
AmortizedDiscountThe discount portion of a commitment fee that has been spread across the billing period. Represents the difference between the gross and net amortized upfront commitment cost.
AmortizedDistributorDiscountAmortized variant of DistributorDiscount. Appears when amortization and discounts are both enabled.
AmortizedEdpDiscountAmortized variant of EdpDiscount. Appears when amortization and discounts are both enabled.
AmortizedFeeAmortized Savings Plan and Reserved Instance purchases.
AmortizedPrivateRateDiscountAmortized variant of PrivateRateDiscount. Appears when amortization and discounts are both enabled.
AmortizedPurchaseAzure reservation and Savings Plan purchases from the amortized cost dataset.
AmortizedRefundRefund charges that span multiple billing days, amortized across the covered period.
AmortizedRiVolumeDiscountAmortized variant of RiVolumeDiscount. Appears when amortization and discounts are both enabled.
AmortizedSppDiscountAmortized variant of SppDiscount. Appears when amortization and discounts are both enabled.
AmortizedTaxTax charges that span multiple billing days, amortized across the covered period.
AmortizedUsageUsage charges in the amortized cost view. For AWS, this can include commitment-covered usage rewritten to gross cost when blended commitment discounts are enabled.
BundledDiscountDiscounted usage for one product or service based on the usage of another product or service.
COMMITTED_USAGE_DISCOUNTGCP Compute Engine resource-based committed use discounts.
COMMITTED_USAGE_DISCOUNT_DOLLAR_BASEGCP spend-based committed use discounts.
CreditCredits applied to your bill.
DISCOUNTDiscounts applied by a provider for your usage.
DiscountDiscounts applied to AWS usage.
DiscountedUsageReserved Instance discounted spend.
DistributorDiscountDiscounts through the AWS Distribution Resellers Program.
EdpDiscountDiscounts applied through the AWS Enterprise Discount Program (EDP).
FeeUpfront annual fees paid for subscriptions, such as the fee paid for All Upfront subscriptions. Also used for AWS Marketplace and Support fees.
FeeTaxTax related to Fee charges, such as AWS Marketplace tax.
FEE_UTILIZATION_OFFSETCredit that offsets Committed Use Discount fee SKUs when commitments are fully utilized.
FREE_TIERCredits related to GCP Free Tier usage.
Monthly Minimum FeeMinimum fee for Fastly.
PartnerEarnedCreditCredits earned by Azure CSP partners for managing customer Azure resources.
PrivateRateDiscountAWS discount based on private pricing rates.
PROMOTIONGCP promotional credits related to items like marketing promotions.
PurchaseAzure Marketplace purchases.
RefundNegative charges indicating money refunded by a provider.
regularGCP regular charges.
RESELLER_MARGINDiscounts for the GCP Reseller Program.
RIFeeMonthly recurring fees for Reserved Instance subscriptions.
RiVolumeDiscountVolume discounts for large Reserved Instance purchases.
RoundingAdjustmentSmall adjustments for rounding differences in Azure billing calculations.
rounding_errorGCP cost type for rounding errors.
SavingsPlanCoveredUsageSavings Plan discounted spend.
SavingsPlanRecurringFeeHourly recurring charges associated with a No Upfront or Partial Upfront Savings Plan.
SavingsPlanUpfrontFeeOne-time upfront fee from purchasing All Upfront or Partial Upfront Savings Plans.
SppDiscountSolution Provider Program discount.
SUBSCRIPTION_BENEFITCredits earned after purchase of long-term subscriptions.
SUSTAINED_USAGE_DISCOUNTCredit for running certain Compute Engine resources for a large portion of the month.
TaxTaxes applied, such as sales tax.
taxLowercase tax value used by GCP.
UnamortizedBundledDiscountUnamortized variant of BundledDiscount. Appears when amortization is disabled and discounts are included.
UnamortizedCreditThe original lump-sum credit charge before amortization.
UnamortizedDiscountThe discount portion of an unamortized commitment fee.
UnamortizedDistributorDiscountUnamortized variant of DistributorDiscount. Appears when amortization is disabled and discounts are included.
UnamortizedEdpDiscountUnamortized variant of EdpDiscount. Appears when amortization is disabled and discounts are included.
UnamortizedFeeThe original lump-sum fee charge before amortization. For AWS, Savings Plan recurring fees can appear as unamortized when blended commitment discounts are enabled.
UnamortizedPrivateRateDiscountUnamortized variant of PrivateRateDiscount. Appears when amortization is disabled and discounts are included.
UnamortizedPurchaseAzure reservation and Savings Plan purchases from the actual, unamortized cost dataset.
UnamortizedRefundThe original lump-sum refund charge before amortization.
UnamortizedRiVolumeDiscountUnamortized variant of RiVolumeDiscount. Appears when amortization is disabled and discounts are included.
UnamortizedSppDiscountUnamortized variant of SppDiscount.
UnamortizedTaxThe original lump-sum tax charge before amortization.
UnamortizedUsageUsage charges from the actual, unamortized cost dataset.
UnusedReservationCost of unused Azure reservation capacity.
UnusedSavingsPlanCost of unused Azure Savings Plan capacity.
UsageCharges for usage at regular or on-demand rates.
Each AWS discount type in the table above, such as BundledDiscount, EdpDiscount, and PrivateRateDiscount, can also have amortized and unamortized variants that use the raw costs.cost_type value with a prefix. For example, EdpDiscount can also appear as AmortizedEdpDiscount or UnamortizedEdpDiscount.
  • Amortized variants such as AmortizedEdpDiscount appear when amortization and discounts are both enabled. These represent the discount amount on fee rows, such as Marketplace or Enterprise Support charges, that has been spread across the billing period.
  • Unamortized variants such as UnamortizedEdpDiscount appear when amortization is disabled and discounts are included. These represent the discount amount on unamortized fee or commitment rows, such as Reserved Instance fees or Savings Plan recurring fees.
The AWS discount types with these variants are: EdpDiscount, BundledDiscount, SppDiscount, RiVolumeDiscount, PrivateRateDiscount, and DistributorDiscount.

Supported Provider Values

The costs.provider field uses lowercase provider codes. Use these exact values when filtering by provider in your SQL.
ProviderValue
Anthropicanthropic
Anyscaleanyscale
AWSaws
Azureazure
Azure CSPazure_csp
CircleCIcircle_ci
ClickHouseclickhouse
Confluentconfluent
Coralogixcoralogix
Cursorcursor
Databricksdatabricks
Datadogdatadog
Elasticelastic
Fastlyfastly
GCPgcp
GitHubgithub
Grafanagrafana
Kuberneteskubernetes
Linodelinode
MongoDBmongo
New Relicnew_relic
OpenAIopen_ai
Oracleoracle
PlanetScaleplanetscale
Redis Cloudredis_cloud
Snowflakesnowflake
Temporaltemporal
Twiliotwilio
Vercelvercel
Custom Providercustom_provider:<token>
To find the exact values to use in your SQL (service names, categories, regions, etc.), check the filter dropdowns in Cost Reports. You can also use editable VQL to inspect stored values. These vary by workspace and provider.

Azure-Specific Field Mapping

For Azure, costs.provider_account_id and costs.resource_account_id map to different Azure identifiers depending on your workspace configuration:
ColumnDefault (most accounts)Non-default accounts
costs.resource_account_idAzure subscription IDMay hold another dimension (e.g., resource group)
costs.provider_account_idBilling account IDMay hold the subscription ID
Some workspaces use a Vantage setting that swaps these two columns. If your Azure rule is not matching the expected rows, compare the values in your rule against a known cost line (via CSV export or API) to confirm which column holds the subscription for your workspace.

costs to aws Column Mapping

When Vantage processes AWS CUR data, it normalizes CUR columns into the costs schema. If you are choosing between writing a rule against the aws dataset (raw CUR) or the costs dataset (normalized), the table below shows how the primary CUR fields map to costs columns.
Vantage costs Columnaws ColumnNotes
amountlineItem/UnblendedCostPrimary cost field for most usage rows
cost_categoryproduct/productFamilyFalls back to "Other"; marketplace rows use "AWS Marketplace"
cost_sub_categorylineItem/UsageTypeFalls back to "Other" if blank
cost_typelineItem/LineItemTypeMapped to Vantage charge types (e.g., Usage, Fee, SppDiscount)
currency_codelineItem/CurrencyCodeUppercased
datelineItem/UsageStartDateParsed to date only
provider(hardcoded)Always 'aws' for AWS data
provider_account_idbill/PayerAccountIdThe AWS payer (management) account
regionproduct/region
resource_account_idlineItem/UsageAccountIdThe linked (member) account
resource_idlineItem/ResourceIdMay be rewritten for ECS or commitment rows
resource_idreservation/ReservationARNOn commitment fee rows only
resource_idsavingsPlan/SavingsPlanARNOn Savings Plan fee rows only
servicelineItem/ProductCodeAfter service name normalization (e.g., EBS is separated from EC2)
usage_amountlineItem/UsageAmountQuantity of usage
usage_unitpricing/unitPrettified (e.g., Hrs becomes Hours)
Some CUR columns like pricing/publicOnDemandCost and pricing/publicOnDemandRate are only available in the aws dataset. If your rule needs to reference on-demand pricing (e.g., for RI/SP re-rating), use the aws dataset instead of costs.

SQL Syntax Reference

This section covers the supported operations, operators and expressions, and column name format for writing billing rule SQL.
See Troubleshooting for common mistakes and how to fix them.

SQL Operations

Use the following SQL operations to define billing rules:
OperationDescriptionGuideExamples
UPDATEAdjust an existing cost value, such as applying a percentage discount.How to constructDiscounts and Markups
DELETERemove specific line-items from being billed.How to constructExclusions
INSERTAdd new line-items, like charges or credits (costs dataset only).How to constructInsert Line Items

Supported Operators

The following operators and expressions are supported in WHERE clauses and SET assignments:
OperatorDescriptionExample
=Equal tocosts.provider = 'aws'
!= or <>Not equal tocosts.cost_type != 'Credit'
>, <, >=, <=Comparisoncosts.amount >= 100
IN (...)Matches any value in a list. Use this instead of chaining OR with bare values — see Troubleshooting.costs.service IN ('Amazon S3', 'AWS Lambda')
NOT IN (...)Does not match any value in a listcosts.cost_type NOT IN ('Credit', 'Tax')
LIKECase-sensitive pattern match using % as a wildcard. Works on string fields that look numeric, such as account IDs.costs.service LIKE 'Amazon%' (starts with), costs.service LIKE '%S3' (ends with), aws.lineItem/UsageAccountId LIKE '%123456%' (contains)
NOT LIKECase-sensitive pattern exclusioncosts.resource_id NOT LIKE '%reservationorders%'
ILIKECase-insensitive version of LIKE. Same % wildcard. Also works on numeric-looking strings.aws.lineItem/LineItemDescription ILIKE '%enterprise discount%'
NOT ILIKECase-insensitive pattern exclusionaws.product/ProductName NOT ILIKE '%free%'
ANDBoth conditions must be truecosts.provider = 'aws' AND costs.service = 'Amazon S3'
OREither condition can be truecosts.cost_type = 'Credit' OR costs.cost_type = 'Tax'
*Multiplicationcosts.amount = costs.amount * 0.90
||String concatenationaws.savingsPlan/SavingsPlanARN || aws.lineItem/UsageAccountId
LOWER()Lowercase a string before comparing or assigning itLOWER(costs.service) = 'amazonsns'
()Grouping(costs.service LIKE 'Amazon%' OR costs.service LIKE 'AWS%') AND costs.cost_type = 'Usage'
The following are not supported and will cause a validation error: SELECT statements, INSERT INTO aws, subqueries, JOINs, CTEs (WITH), LIMIT, ORDER BY, GROUP BY, division (/), BETWEEN, CASE WHEN, SQL functions other than LOWER() (e.g., UPPER(), COALESCE(), SUM()), and unqualified column names (every column must include the dataset prefix, e.g., costs.amount).

Column Name Format

All column references must be fully qualified with the dataset name:
  • costs dataset: Use costs.column_name format (e.g., costs.amount, costs.service)
  • aws dataset: Use aws.table/ColumnName format (e.g., aws.lineItem/UnblendedCost, aws.bill/BillingEntity)

How to Construct SQL Statements

Step-by-step guides for building UPDATE, DELETE, and INSERT statements.

UPDATE Statements

UPDATE Basic Structure
UPDATE [dataset] 
SET [column] = [new_value]
WHERE [condition]
1

Start with UPDATE

Choose your dataset (costs or aws).
UPDATE costs
2

Specify what to change

Use SET to define the new value. You can update any column from the costs data dictionary or AWS column list, not just amount.
UPDATE costs
SET costs.amount = costs.amount * 0.90
3

Add conditions

Use WHERE to specify which rows to modify.
UPDATE costs
SET costs.amount = costs.amount * 0.90
WHERE costs.service = 'Virtual Machines'
Common patterns:
  • Apply discount: SET costs.amount = costs.amount * 0.90 (10% discount)
  • Apply markup: SET costs.amount = costs.amount * 1.15 (15% markup)
  • Set fixed amount: SET costs.amount = 100.00

DELETE Statements

DELETE Basic Structure
DELETE FROM [dataset]
WHERE [condition]
1

Start with DELETE FROM

Choose your dataset (costs or aws).
DELETE FROM costs
2

Add conditions

Use WHERE to specify which rows to remove.
DELETE FROM costs
WHERE costs.cost_type = 'SppDiscount'
Common patterns:
  • Remove by service: WHERE costs.service LIKE 'AWS Support%'
  • Remove by cost type: WHERE costs.cost_type = 'Fee'
  • Remove by amount: WHERE costs.amount < 0.01
  • Remove by multiple conditions: WHERE costs.provider = 'aws' AND costs.service = 'Amazon S3'
See Exclusions for detailed DELETE examples.

INSERT Statements

INSERT statements can only be used with the costs dataset. INSERT is not supported for the aws dataset. Values must be static literals; you cannot reference columns or use expressions (e.g., costs.amount * 0.10) in the VALUES clause. For dynamic calculations, use an UPDATE rule instead.
INSERT Basic Structure
INSERT INTO costs (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...)
1

Start with INSERT INTO

Use the costs dataset for INSERT statements.
INSERT INTO costs
2

List required columns

Specify all necessary columns.
INSERT INTO costs (provider, service, cost_category, cost_sub_category, cost_type, amount)
3

Add VALUES

Provide values for each column.
INSERT INTO costs (provider, service, cost_category, cost_sub_category, cost_type, amount)
VALUES ('aws', 'One Time Charge', 'One Time Charge', 'One Time Charge', 'Usage', 100)
Common patterns:
  • Add credit: VALUES ('aws', 'Billing Credit', 'Billing Credit', 'Billing Credit', 'Credit', -100)
  • Add processing fee: VALUES ('aws', 'Processing Fee', 'Processing Fee', 'Processing Fee', 'Fee', 5)
See Insert Line Items for detailed INSERT examples.

Create SQL Billing Rules

To create a new SQL billing rule:
1

Create a new custom rule

  • From the top navigation, click Settings.
  • From the left navigation, under Partner Settings, select Billing Rules.
  • Click New Billing Rule, then select Custom.
2

Configure the rule

Add the following rule details:
  • Title: Give your rule a descriptive name.
  • Start Date/End Date: Define the date range for which the rule should apply. Use these fields instead of date logic in your SQL. If you leave both blank, the rule applies to all billing periods (past and future). You can set only a Start Date (applies from that date forward) or only an End Date (applies up to that date).
  • Select whether you want to automatically apply this billing rule to all existing and new managed accounts.
3

Write the rule SQL

  • From the Available Columns list, select either the AWS/aws or Vantage/costs schema. The selected schema must match the dataset in your SQL. If you write a costs rule but leave the schema set to aws, saving will fail.
  • Under Cost Fields, view available fields and click to copy, or type any column from the costs data dictionary or AWS column list directly into the editor.
  • In the SQL editor, write your SQL statement using the selected dataset and columns. The editor supports autocomplete and syntax highlighting.
  • Click Format above the editor to auto-format your SQL with consistent indentation and line breaks.
  • Click Validate to check your query against the selected schema before saving. Validation catches syntax errors, unsupported operations, schema mismatches (e.g., using costs columns against the aws dataset), and common issues like missing spaces before SQL keywords or multiple statements in a single rule.
  • Click Submit to create the rule.
When you save a billing rule, Vantage automatically reprocesses affected cost data. For large accounts, this can take several hours. Finalize your SQL before saving. Saving multiple times restarts the reprocessing cycle each time.
Each workspace can define up to 20 billing rules. If you need more, contact support@vantage.sh. For multiple adjustments with different conditions, create separate rules. The order shown on the Billing Rules list can affect the final result when multiple rules target the same rows. Test after reprocessing to confirm the combined outcome.

Example Rules

Many of the below examples are also documented in the FinOps as Code repository.

Discounts and Markups

Apply a 5% Discount (AWS)

Apply a 5% discount to all cost line items, excluding credits:
UPDATE aws
SET aws.lineItem/UnblendedCost = aws.lineItem/UnblendedCost * 0.95
WHERE aws.lineItem/LineItemType != 'Credit'
At this time, multiplication is supported, but not division.

Apply Service-Specific Markup

Apply a 5% markup to specific services:
UPDATE costs 
SET costs.amount = costs.amount * 1.05
WHERE costs.service IN ('Amazon Relational Database Service', 'AWS Lambda')

Rename a Service

Rename a service label in normalized cost data:
UPDATE costs
SET costs.service = 'Custom Compute'
WHERE costs.provider = 'aws' AND costs.service = 'Amazon Elastic Compute Cloud - Compute'

Apply Markup by Cost Category

Apply a 10% markup to all storage costs:
UPDATE costs 
SET costs.amount = costs.amount * 1.10
WHERE costs.cost_category = 'Storage'

Reduce Costs for a Specific AWS Account

Apply a 50% cost reduction to a specific linked account:
UPDATE aws 
SET aws.lineItem/UnblendedCost = aws.lineItem/UnblendedCost * 0.50
WHERE aws.lineItem/UsageAccountId = '111111111111'

Set Credits to Zero

Zero out all credit line items:
UPDATE costs 
SET costs.amount = 0
WHERE costs.cost_type = 'Credit'

Zero Out Cost and Rate for Internal Accounts

Set both the cost and rate to zero for specific internal accounts (e.g., cost optimization or internal operations accounts):
UPDATE aws 
SET aws.lineItem/UnblendedCost = '0', aws.lineItem/UnblendedRate = '0'
WHERE aws.lineItem/UsageAccountId IN ('111111111111', '222222222222', '333333333333')

Exclusions

Exclude SPP Discounts

Remove Solution Provider Program discounts from billing:
DELETE FROM costs 
WHERE costs.cost_type = 'SppDiscount'

Exclude Multiple SPP Discount Types

Remove both SPP and unamortized SPP discounts:
DELETE FROM costs 
WHERE costs.cost_type IN ('SppDiscount', 'UnamortizedSppDiscount')

Exclude SPP/EDP Discount Line Items (AWS)

Remove Enterprise Discount Program and Solution Provider discount or credit line items at the CUR level:
DELETE FROM aws
WHERE aws.lineItem/LineItemType IN ('Discount', 'Credit')
AND (
  aws.lineItem/LineItemDescription ILIKE '%Enterprise Discount Program%'
  OR aws.lineItem/LineItemDescription ILIKE '%Solution Provider%'
)

Exclude AWS Support Products (AWS)

Remove all AWS Support product costs at the CUR level:
DELETE FROM aws 
WHERE aws.lineItem/ProductCode IN ('AWSSupportBusiness', 'AWSSupportEnterprise', 'AWSSupportDeveloper')

Exclude Support Costs

Remove AWS Business support costs from billing:
DELETE FROM costs 
WHERE costs.service = 'AWS Support (Business)'

Exclude Marketplace Costs

Remove all AWS Marketplace costs from billing:
DELETE FROM costs
WHERE costs.cost_category = 'AWS Marketplace'

Exclude Marketplace by Billing Entity (AWS)

Remove AWS Marketplace costs at the CUR level using the billing entity field:
DELETE FROM aws 
WHERE aws.bill/BillingEntity = 'AWS Marketplace'

Exclude BundledDiscount Line Items (AWS)

Remove BundledDiscount line items from the CUR:
DELETE FROM aws 
WHERE aws.lineItem/LineItemType = 'BundledDiscount'

Remove Costs for Specific AWS Accounts

Exclude all costs from specific linked AWS accounts:
DELETE FROM aws 
WHERE aws.lineItem/UsageAccountId IN (
  '111111111111',
  '222222222222',
  '333333333333'
)
Account-based exclusions must use account IDs, not account names. The AWS CUR does not include an account name column that can be used in billing rules.

Exclude Other Provider Items

Remove Temporal Cloud Actions from billing:
DELETE FROM costs 
WHERE costs.provider = 'temporal' AND costs.service = 'Temporal Cloud' AND costs.cost_sub_category = 'Actions'

Reserved Instance and Savings Plan Adjustments

Unamortize Reserved Instance and Savings Plan Costs

Convert amortized Reserved Instance and Savings Plan costs back to usage-based costs. This rule sets the line item type to Usage when the Savings Plan or reservation does not belong to the linked account (using string concatenation to compare account IDs within ARNs):
UPDATE aws 
SET aws.lineItem/LineItemType = 'Usage'
WHERE aws.lineItem/LineItemType IN ('SavingsPlanCoveredUsage', 'DiscountedUsage') 
AND aws.savingsPlan/SavingsPlanARN || aws.reservation/ReservationARN NOT LIKE '%:' || aws.lineItem/UsageAccountId || ':%'

Unamortize Savings Plans for a Specific Account

Convert Savings Plan covered usage back to on-demand for a specific account by matching the account ID within the Savings Plan ARN:
UPDATE aws 
SET aws.lineItem/LineItemType = 'Usage', aws.savingsPlan/SavingsPlanARN = NULL
WHERE aws.lineItem/LineItemType = 'SavingsPlanCoveredUsage'
AND aws.savingsPlan/SavingsPlanARN LIKE 'arn:aws:savingsplans::111111111111%'

Rerate Reserved Instance Costs to On-Demand Pricing

Replace discounted Reserved Instance costs with public on-demand pricing by copying values from the pricing columns. This sets both the cost and rate to their on-demand equivalents for reservations belonging to specific accounts:
UPDATE aws 
SET aws.lineItem/UnblendedCost = aws.pricing/publicOnDemandCost, aws.lineItem/UnblendedRate = aws.pricing/publicOnDemandRate
WHERE aws.lineItem/LineItemType = 'DiscountedUsage'
AND (
  aws.reservation/ReservationARN LIKE '%111111111111%'
  OR aws.reservation/ReservationARN LIKE '%222222222222%'
)
When filtering by account ID within an ARN field, use LIKE '%account_id%' to match the account ID substring within the full ARN string. Do not use IN with bare account IDs — ARN fields contain full ARN strings (e.g., arn:aws:ec2:us-east-1:111111111111:reserved-instances/...), so an IN comparison against just '111111111111' will never match.

Exclude Reservation Fees for Specific Accounts

Remove Reserved Instance fees that belong to specific internal accounts without affecting other usage on those accounts. Use LIKE to match the account ID within the reservation ARN:
DELETE FROM aws
WHERE aws.lineItem/LineItemType = 'RIFee'
AND (
  aws.reservation/ReservationARN LIKE '%:111111111111:%'
  OR aws.reservation/ReservationARN LIKE '%:222222222222:%'
)

Insert Line Items

INSERT statements can only be used with the costs dataset.

Add a Monthly Charge

Insert a flat monthly charge as a new line item:
INSERT INTO costs (provider, service, cost_category, cost_sub_category, cost_type, amount)
VALUES ('aws', 'Platform Fee', 'Platform Fee', 'Platform Fee', 'Fee', 1100)

Add a Credit

Insert a billing credit as a negative amount:
INSERT INTO costs (provider, service, cost_category, cost_sub_category, cost_type, amount)
VALUES ('aws', 'Billing Credit', 'Billing Credit', 'Billing Credit', 'Credit', -500)

Add a Processing Fee

Insert a processing fee for services rendered:
INSERT INTO costs (provider, service, cost_category, cost_sub_category, cost_type, amount)
VALUES ('aws', 'Processing Fee', 'Processing Fee', 'Processing Fee', 'Fee', 3500)

Add a Support Fee with a Specific Date

Insert a support fee for a specific billing period. You can include the date column to specify which month the charge applies to:
INSERT INTO costs (provider, date, service, cost_category, cost_type, amount)
VALUES ('aws', '2026-01-31', 'Support Fee', 'Support Fee', 'Fee', 5000)

Azure Examples

Azure billing rules use the costs dataset. There is no separate Azure CUR dataset. When writing Azure rules, use costs.provider = 'azure' for standard Azure or costs.provider = 'azure_csp' for Azure CSP. These are distinct provider values, and rules must target the correct one.

Apply Markup to Azure Services

Apply a 10% markup to Azure Virtual Machines:
UPDATE costs 
SET costs.amount = costs.amount * 1.10
WHERE costs.provider = 'azure' AND costs.service = 'Virtual Machines'

Apply Discount Excluding Reservations (Azure)

Apply a discount to all Azure costs while excluding reservation purchases:
UPDATE costs 
SET costs.amount = costs.amount * 0.95
WHERE costs.provider = 'azure' 
AND LOWER(costs.resource_id) NOT LIKE '%/providers/microsoft.capacity/reservationorders%'

Apply Markup by Azure Subscription

Apply a 10% markup to costs from a specific Azure subscription. See the Azure-Specific Field Mapping section to determine whether costs.resource_account_id or costs.provider_account_id contains the subscription ID for your workspace.
UPDATE costs 
SET costs.amount = costs.amount * 1.10
WHERE costs.provider = 'azure' AND costs.resource_account_id = 'your-subscription-id'

Exclude Partner Earned Credit (Azure CSP)

Remove Partner Earned Credits from Azure CSP billing. Note the use of azure_csp as the provider value:
DELETE FROM costs 
WHERE costs.provider = 'azure_csp' AND costs.cost_type = 'PartnerEarnedCredit'

Apply Discount to NCE Licenses (Azure CSP)

Apply a 5% discount to New Commerce Experience (NCE) License purchases for Azure CSP:
UPDATE costs 
SET costs.amount = costs.amount * 0.95
WHERE costs.provider = 'azure_csp' AND costs.service = 'NCE License' AND costs.cost_type = 'Purchase'
Need help writing or debugging a rule? Try the AI assistant at the top of this page.

Troubleshooting

If a billing rule fails to save, the editor displays an error message. Below are common errors and how to resolve them.
Error MessageCauseResolution
”Query contains disallowed keywords: …”The SQL uses an unsupported keyword like LIMIT, JOIN, WITH, GROUP, or ORDERRemove the keyword. See the warning under Supported Operators for the full list.
”Columns must always specify a table: …”A column name is missing the dataset prefixPrefix every column with the dataset name (e.g., costs.amount instead of amount).
”Query contains unknown tables: …”The dataset name is not aws or costsUse only aws or costs as the dataset name.
”Query contains unknown columns: …”A column name is misspelled, uses the wrong casing, or is not available for that datasetCheck the column spelling and casing. Common mistakes include costs.currency instead of costs.currency_code.
”Query cannot be parsed: …”The SQL has a syntax errorCheck for missing or mismatched quotes, unmatched parentheses, missing commas between SET assignments, or typos in keywords.
”Unsupported SQL operation. Only UPDATE, INSERT, and DELETE operations are supported at this time.”Used a SELECT statement or other unsupported operationRewrite as an UPDATE, DELETE, or INSERT statement.
”Unsupported SQL operation. INSERT operations can only be performed on the ‘costs’ schema at this time.”Attempted INSERT INTO awsChange to INSERT INTO costs. INSERT is only supported with the costs dataset.
”Unable to parse relevant SQL statements from input.”The SQL input was empty or didn’t contain a recognizable statementEnter a complete UPDATE, DELETE, or INSERT statement.
”Selected schema doesn’t match schema detected in query.”The schema selected in the Available Columns dropdown (e.g., aws) does not match the dataset used in your SQL (e.g., costs)Switch the Available Columns dropdown to the dataset that matches your SQL before saving.
”Invalid UPDATE statement detected near ’…’. This can happen when columns aren’t prepended with schema.”A SET column is missing the dataset prefixQualify all SET targets with the dataset (e.g., aws.lineItem/UnblendedCost not lineItem/UnblendedCost).
”Title can’t be blank”The rule name field is emptyEnter a descriptive name for the rule.
”must be before end date”The start date is on or after the end dateSet a start date that is earlier than the end date.

Additional Troubleshooting

SymptomLikely CauseResolution
Rule has no effect on costsProvider value uses wrong casing (e.g., 'Azure' instead of 'azure')Provider values are case-sensitive. Always use lowercase: 'aws', 'azure', 'azure_csp', 'gcp'.
Rule has no effect on costsService name doesn’t match actual valuesCheck the Service filter in Cost Reports for the exact service name to use.
Rule deletes all rows unexpectedlyUsed OR 'value' instead of IN ('value1', 'value2')A bare string after OR always evaluates as true. Use IN (...) or write the full comparison on both sides of OR.
Rule doesn’t match expected rows with ARN fieldsUsed IN ('account_id') on a Reservation ARN or Savings Plan ARN fieldARN fields contain full ARN strings. Use LIKE '%account_id%' to match account IDs within ARNs.
Azure rule filters wrong rowsUsing the wrong Azure account field for your workspace’s mappingSee Azure-Specific Field Mapping and verify whether the subscription lives in costs.resource_account_id or costs.provider_account_id for your workspace.
Changes are not visible yetData is still reprocessing after the rule was savedWait for reprocessing to complete. For large accounts, this can take several hours.