Pass BigQuery Gross Margin to Google Ads Offline Conversions

Learn how to import dynamic order gross margin from BigQuery into Google Ads offline conversions to train Smart Bidding on true bottom-line profit.

By AdTurbo Team · 2026-11-27

Optimizing for raw revenue is one of the most common reasons high-volume e-commerce and lead generation accounts hit a growth plateau. When you configure Target ROAS (tROAS) or Maximize Conversion Value on top-line transactional revenue, Google Ads treats a $1,000 order with a 10% margin identically to a $1,000 order with an 80% margin. The bidding algorithm actively bids up on products, audiences, and search queries that generate massive gross transaction value but leave your business with negligible operating income.

To break out of this margin-diluting cycle, sophisticated marketing teams feed calculated net revenue or order-level gross profit back into the bidding ecosystem. By setting up bigquery gross margin google ads offline conversions, you replace surface-level checkout figures with accurate, post-return, COGS-adjusted profit metrics.

This guide outlines the complete engineering and architectural blueprint to extract first-party transaction data, calculate line-item gross margins inside Google Cloud, and automate bigquery offline conversion ingestion via Google Ads offline conversion adjustments or REST API syncs.

---

The Architecture of Margin-Based Bidding

Standard client-side conversion tracking scripts (such as the Google tag or Google Tag Manager web container) execute inside a user's browser right after checkout. At this millisecond in the transaction cycle, your web store only knows what the customer agreed to pay: gross cart value, taxes, shipping charges, and applied coupon codes.

Client-side tags do not possess—and should never publicly expose—internal cost of goods sold (COGS), warehouse fulfillment costs, payment gateway transaction processing fees, or post-purchase return likelihoods. Storing wholesale unit costs in JavaScript variables exposes sensitive business data to any competitor examining your source code.

[Customer Checkout]

│

├─► (Client-Side Tag) ──► Initial "Purchase" (Reports Raw Revenue: $250)

│

└─► [ERP / Shopify / Backend DB]

│

▼

[Google BigQuery Warehouse]

│ (Joins Orders with COGS, Fees & Gateway Costs)

▼

[Calculated Gross Margin: $82.40]

│

▼

(Offline Conversion Adjustment API / Ingestion)

│

▼

[Google Ads Smart Bidding Engine]

To feed first party gross margin smart bidding safely without exposing margin data on the front end, you implement a dual-phase conversion model:

1. Phase 1 (Real-Time Acquisition): The frontend tag captures the initial purchase event along with a unique identifier (orderid or transaction ID) and raw revenue, establishing the conversion immediately to provide Google's auction algorithm real-time volume signals.

2. Phase 2 (Data Enrichment & Offline Adjustment): Your transactional database or enterprise resource planning (ERP) system loads daily orders into Google BigQuery. A scheduled SQL workflow reconciles orders against supplier cost sheets, merchant fees, and cancellations to compute dynamic gross margin. Finally, an automated pipeline imports these adjusted values back into Google Ads via the ConversionAdjustmentUploadService or ConversionUploadService.

---

Why Shifting to Gross Margin Outperforms Revenue Bidding

Optimizing for top-line revenue encourages Smart Bidding to hunt for clearance inventory, heavy discounted SKUs, or low-margin commodity products where consumers are highly price-sensitive. When you import profit values bigquery to google ads, you fundamentally reshape account performance.

Consider this real-world scenario of two customers acquired at the exact same $120 Target CPA:

| Metric | Customer A (Consumer Electronics) | Customer B (Proprietary Consumables) |

| :--- | :--- | :--- |

| Top-Line Order Value | $1,000.00 | $350.00 |

| Reported Revenue (Standard Tracking) | $1,000.00 | $350.00 |

| Cost of Goods Sold (COGS) | $880.00 | $70.00 |

| Merchant & Pick/Pack Fees | $35.00 | $12.00 |

| Realized Gross Profit | $85.00 | $268.00 |

| Ad Spend (CPA) | $120.00 | $120.00 |

| Net Contribution Margin | -$35.00 (Loss) | +$148.00 (Profitable) |

| Standard tROAS Metric | 833% ROAS | 291% ROAS |

Under standard revenue tracking, Google Ads sees Customer A as a massive success (833% ROAS) and allocates more budget toward the keywords and audiences that drove that sale. Customer B appears mediocre (291% ROAS), prompting the algorithm to pull back bids. In reality, Customer A lost your company money after ad spend, while Customer B generated significant bottom-line profit.

By passing gross margin as conversion value, you train Smart Bidding algorithms to locate more buyers like Customer B. If your campaigns feel inefficient despite hitting vanity revenue benchmarks, auditing tracking should be part of your broader PPC audit checklist.

---

Data Prerequisites and Schema Setup in BigQuery

Before writing queries to push data back into Google Ads, you must structure your tables in Google Cloud BigQuery. You need three core datasets:

1. Sales Transactions Table (orders): Contains order identifiers, transaction timestamps, items purchased, customer email/phone (for Enhanced Conversions), and front-end transaction amounts.

2. Product Cost Catalog (cogscatalog): Contains SKU-level historical supplier costs, domestic freight, and unit assembly costs.

3. Google Click Identifiers or Enhanced Conversion Identifiers (clickattribution): Contains the associated gclid, gbraid, wbraid, or hashed user data alongside the transactional orderid.

Sample BigQuery SQL Table Schemas

Your target export table must adhere strictly to Google Ads API requirements. Here is how your enriched conversion table should look inside BigQuery:

sql

CREATE OR REPLACE TABLE yourproject.marketingconversions.googleadsmarginuploads (

orderid STRING NOT NULL,

conversionactionid STRING NOT NULL,

adjustmenttype STRING NOT NULL, -- 'RESTATEMENT' or upload new 'CONVERSION'

adjustmentdatetime STRING NOT NULL, -- Format: 'yyyy-mm-dd hh:mm:ss+|-hh:mm'

adjustedvalue FLOAT64 NOT NULL,

currencycode STRING NOT NULL,

gclid STRING,

hashedemail STRING,

orderstatus STRING

);

To ensure proper synchronization, keep historical records of SKU pricing. If supplier costs change dynamically on the 1st of the month, your query must join on SKU and purchase date to avoid miscalculating margins on historical orders.

---

Calculating True Order-Level Gross Margin in BigQuery

Gross margin calculations vary by organization, but a standard direct-to-consumer or B2B formula accounts for the item sales price minus discounts, supplier unit COGS, estimated variable gateway fees (e.g., Stripe's 2.9% + $0.30), and flat packaging costs.

Production BigQuery SQL Script

Run this query to transform raw data into an adjustment payload ready for Google Ads:

sql

WITH orderitemcosts AS (

SELECT

oi.orderid,

oi.sku,

oi.quantity,

oi.itemprice,

-- Fallback to default COGS if SKU is missing from catalog

COALESCE(c.unitcogs, oi.itemprice 0.50) AS unitcogs

FROM

yourproject.ecommerce.orderitems oi

LEFT JOIN

yourproject.inventory.cogscatalog c

ON oi.sku = c.sku

AND DATE(oi.createdat) = c.validfrom

AND DATE(oi.createdat) <= COALESCE(c.validto, CURRENTDATE())

),

aggregatedmargins AS (

SELECT

orderid,

SUM(quantity itemprice) AS lineitemsubtotal,

SUM(quantity unitcogs) AS totalcogs

FROM

orderitemcosts

GROUP BY

orderid

)

SELECT

o.orderid,

-- Google Ads conversion action resource ID

'1234567890' AS conversionactionid,

'RESTATEMENT' AS adjustmenttype,

-- Timestamp formatted to ISO 8601 with timezone offset

FORMATTIMESTAMP('%Y-%m-%d %H:%M:%S%Ez', o.createdat) AS adjustmentdatetime,

-- Calculate margin: Subtotal - COGS - Payment Processing - Flat Box/Ship Surcharge

ROUND(

(m.lineitemsubtotal - m.totalcogs - (o.totalpaid 0.029 + 0.30) - 4.50),

2

) AS adjustedvalue,

'USD' AS currencycode,

attr.gclid AS gclid,

TOHEX(SHA256(LOWER(TRIM(o.customeremail)))) AS hashedemail

FROM

yourproject.ecommerce.orders o

INNER JOIN

aggregatedmargins m ON o.orderid = m.orderid

LEFT JOIN

yourproject.tracking.clickattribution attr ON o.orderid = attr.orderid

WHERE

-- Process orders from the previous day to allow returns/cancellations to settle

DATE(o.createdat) = DATESUB(CURRENTDATE(), INTERVAL 1 DAY)

AND o.status NOT IN ('CANCELLED', 'REFUNDED')

-- Prevent passing negative values to bidding engines

AND (m.lineitemsubtotal - m.totalcogs) 0;

Handling Returns, Exchanges, and Edge Cases

What happens when an order is partially refunded 4 days later? Google Ads offline conversion adjustments support both RESTATEMENT (changing the value of an existing transaction) and RETRACTION (completely nullifying the conversion). If an order is canceled before fulfillment, issue a retraction payload. If two items out of three are returned, re-run your margin calculation logic and push a RESTATEMENT with the updated, lower gross profit value.

---

Methods for Ingesting BigQuery Data into Google Ads

Once your BigQuery tables contain calculated margin records, choose one of three ingestion pipelines to pipe the data into Google Ads.

┌─────────────────────────────────────────────────────────────┐

│ BigQuery Output Table │

└──────────────────────────────┬──────────────────────────────┘

│

┌──────────────────────┼──────────────────────┐

▼ ▼ ▼

┌────────────────┐ ┌───────────────────┐ ┌────────────────┐

│ Method 1: │ │ Method 2: │ │ Method 3: │

│ Google Ads Data│ │ Scheduled Cloud │ │ Modern Reverse │

│ Manager (Zap) │ │ Functions / API │ │ ETL Pipeline │

│ (No Code/SaaS) │ │ (Custom/Full Code)│ │ (Hightouch/etc)│

└────────────────┘ └───────────────────┘└────────────────┘

Method 1: Google Ads Data Manager (Native BigQuery Connection)

Google Ads natively includes Google Ads Data Manager within the platform interface (under Tools & Settings Data Manager). This feature lets you connect directly to a Google BigQuery dataset without third-party middleware.

1. In Google Ads, navigate to Tools Data Manager Connect Source.

2. Select Google BigQuery.

3. Authenticate using an IAM service account that holds at least BigQuery Data Viewer and BigQuery Job User permissions on your project.

4. Select your target project, dataset, and table (googleadsmarginuploads).

5. Map the fields: map orderid to Transaction ID, adjustedvalue to Conversion Value, adjustmentdatetime to Adjustment Time, and currencycode to Currency.

6. Set a refresh frequency (e.g., daily at 02:00 AM UTC).

Method 2: Custom Python Pipeline via Google Ads REST API

For enterprise environments that require sophisticated logging, error notifications, and conditional retries, deploying a lightweight Google Cloud Function or Cloud Run job written in Python provides maximum control over conversion restatements.

The script queries BigQuery for unuploaded adjustments, constructs a ConversionAdjustment object, and issues an API call via the official google-ads Python SDK:

python

import os

from google.cloud import bigquery

from google.ads.googleads.client import GoogleAdsClient

from google.ads.googleads.errors import GoogleAdsException

def uploadmarginrestatements(event, context):

bqclient = bigquery.Client()

adsclient = GoogleAdsClient.loadfromstorage("google-ads.yaml")

conversionadjustmentservice = adsclient.getservice("ConversionAdjustmentUploadService")

customerid = os.environ.get("GOOGLEADSCUSTOMERID")

query = """

SELECT orderid, conversionactionid, adjustmentdatetime, adjustedvalue, currencycode

FROM yourproject.marketingconversions.googleadsmarginuploads

WHERE uploadedtoads = FALSE

"""

rows = bqclient.query(query).result()

adjustments = []

for row in rows:

adjustment = adsclient.gettype("ConversionAdjustment")

conversionactionservice = adsclient.getservice("ConversionActionService")

adjustment.conversionaction = conversionactionservice.conversionactionpath(

customerid, row.conversionactionid

)

adjustment.adjustmenttype = adsclient.enums.ConversionAdjustmentTypeEnum.RESTATEMENT

adjustment.orderid = row.orderid

adjustment.adjustmentdatetime = row.adjustmentdatetime

adjustment.restatementvalue.adjustedvalue = float(row.adjustedvalue)

adjustment.restatementvalue.currencycode = row.currencycode

adjustments.append(adjustment)

if adjustments:

try:

request = adsclient.gettype("UploadConversionAdjustmentsRequest")

request.customerid = customerid

request.conversionadjustments = adjustments

request.partialfailure = True

response = conversionadjustmentservice.uploadconversionadjustments(request=request)

print(f"Uploaded {len(adjustments)} adjustments with status: {response}")

except GoogleAdsException as ex:

print(f"API request failed: {ex}")

Method 3: Reverse ETL Platforms (Hightouch, Census)

If your engineering team uses Reverse ETL tools, you can point Hightouch or Census at your BigQuery model and select Google Ads Offline Conversions as the destination sync. These platforms handle retry logic, token refresh failures, and payload batching automatically.

---

Configuring Google Ads Conversion Actions for Restatements

To ensure your uploaded margin metrics do not break your conversion history, configure your Google Ads conversion actions correctly:

1. Maintain a Single Conversion Action: Go to Goals Conversions Summary. Select your primary web purchase action. Ensure that Transaction ID tracking is fully enabled on your frontend tag.

2. Set Value Attribution to Use Web Order Defaults Initially: When client-side purchases register, let them report gross revenue initially. Your offline BigQuery restatements will update these records within 24 to 48 hours.

3. Set Your Conversion Window and Adjustment Window: Set the Click-through conversion window to 30 or 60 days, and verify your Conversion Value Adjustment window is set to at least 21 days (ideally 30–55 days). This gives BigQuery ample time to restate orders after cancellations and supplier updates have finalized.

Managing complex data layers alongside regular optimizations can stretch marketing teams thin. Many teams rely on PPC campaign management software to automate structural checks and flag negative-margin search queries while technical teams maintain backend BigQuery integrations.

---

Calibrating Smart Bidding for Gross Margin Targets

Switching from top-line revenue to gross margin causes your reported conversion values to drop instantly. For example, if your store does $500,000 per month in gross sales at an average 40% margin, your total reported conversion value drops from $500,000 to $200,000.

If you leave your target ROAS untouched, your campaigns will stall immediately.

Recalculating Target ROAS (tROAS) for Margin Bidding

Assume you previously ran campaigns at a 400% tROAS under raw revenue tracking:

• Old Model (Revenue): For every $100 in ad spend, you targeted $400 in gross sales.

• Reality at 40% Margin: That $400 in sales yields $160 in gross profit.

• New Target (Margin ROAS or Profit-on-Ad-Spend): To hit the identical bottom-line performance, you want $160 of gross profit for every $100 spent.

• New Formula: Your new Target ROAS should be set to 160% ($160 margin ÷ $100 ad spend).

Old Target ROAS = (Gross Revenue / Ad Spend) 100

New Profit Target ROAS = (Gross Margin / Ad Spend) 100

Adjust your conversion goals gradually:

1. Upload margin restatements silently for 14 days without changing your bidding strategies. This allows Google's neural network to observe the historical relationship between clicks and adjusted values.

2. Review campaigns that bleed spend on low-margin products. Check our breakdown of why Google Ads is so expensive to clean out structural inefficiencies before lowering targets.

3. Lower your target ROAS down to your calculated margin-based target in increments of 15% to 20% every four days until ad spend stabilizes at your desired margin velocity.

If managing these bid migrations and technical data models manually feels overwhelming, automated platforms like AdTurbo leverage machine learning alongside automated account safeguards to adjust campaign bids and preserve bottom-line contribution margins without constant manual math.

---

Troubleshooting Common Offline Ingestion Failures

When debugging bigquery offline conversion ingestion, you will likely encounter these common error responses returned by the Google Ads API:

1. CONVERSIONALREADYEXISTS or CONVERSIONNOTFOUND

• Cause: When issuing a RESTATEMENT, Google Ads cannot find an existing conversion matching the specified orderid within the active adjustment window.

• Fix: Verify that your frontend Google Tag actually passes the transactionid parameter matching your database orderid. If the frontend tag failed to fire or passed an empty string, the restatement upload has nothing to anchor to.

2. Timezone Mismatches (ADJUSTMENTPRECEDESCONVERSION)

• Cause: The adjustmentdatetime string is registered as occurring earlier than the original frontend purchase event.

• Fix: Always explicitly append timezone offsets inside BigQuery (e.g., %Y-%m-%d %H:%M:%S%Ez). If the original conversion occurred at 2026-03-10 14:00:00+00, your adjustment cannot carry a timestamp of 2026-03-10 09:00:00-05 if processing errors misinterpret UTC as local time.

3. GCLID Expiration Beyond 90 Days

• Cause: If you ingest new conversions using click identifiers instead of transaction IDs, any click older than 90 days is discarded.

• Fix: Use orderid restatements for e-commerce. For offline lead conversions, ensure your pipeline executes daily so click identifiers remain well within the eligibility window.

4. Zero or Negative Values Causing Auction Freezes

• Cause: If an order results in a net-negative margin after fulfillment costs, passing a value of -12.50 will trigger an API validation error.

• Fix: Apply a GREATEST(0.01, calculatedmargin) or WHERE margin 0 clause in your BigQuery model. For orders with negative contribution margins, issue a RETRACTION adjustment instead of sending negative numbers.

To audit whether these tracking issues are artificially suppressing your bidding models, review our step-by-step diagnostic guide on Google Ads not working.

---

Related Guides

• PPC Audit Checklist: 12 Steps to Fix a Leaking Google Ads Account

• Why Is Google Ads So Expensive? 7 Reasons (And How to Pay Less)

• Google Ads Not Working? 11 Things to Check Before You Panic

---

Frequently Asked Questions

Can I pass product-level gross margin using standard Google Tag Manager without BigQuery?

While you can technically pass calculated values through client-side code, it requires exposing your wholesale unit costs and supplier margins inside the browser's JavaScript variables. Any competitor, customer, or browser extension can inspect the network payloads and see your exact margins on every product. Processing margin values server-side inside BigQuery ensures your cost data remains entirely private.

How long does it take for Google Smart Bidding to adapt to profit values?

Google's machine learning models generally require between 14 to 28 days to adapt to a shifted conversion value scale. Because your reported conversion values will decrease substantially when switching from gross revenue to gross profit, you must lower your Target ROAS threshold proportionally so the algorithm does not drastically throttle your bids during the transition phase.

Should I upload gross margin as a Restatement or as a new Conversion Action?

If you run an e-commerce website where orders are already tracked by an existing Google tag, using Conversion Restatements on the original Transaction ID is the most reliable method. It preserves same-day conversion signals for your campaigns while updating the attributed dollar value to true margin within 24 to 48 hours once backend inventory and processing calculations settle.

Does Google Ads require a GCLID for offline margin uploads?

No, a GCLID is not mandatory if you use conversion value restatements anchored to an existing orderid (Transaction ID) that was already captured by your website's Google tag. For new offline conversion actions where no prior web conversion fired, you must supply a GCLID, GBRAID/WBRAID, or hashed first-party customer data (Enhanced Conversions for Leads) to tie the sale back to the original ad click.