Skip to main content

This is a three-part article series looks at different ways to extract insights from Google Analytics using the raw data from Big Query. Working with Matt Janes on a couple of client projects, this article focuses on New v Returning customers, the other 2 articles focuses on Time Lag from first visit to purchase and RFM Customer Segmentation. 

Working with an E-commerce bakery who had gone from having a bakery store for 15 years with consumer behaviours changing they launched an e-commerce website in 2021. In 2022 re-positioned as an E-commerce only bakery, the bakery was not available to consumers to dine in, the bakery became a kitchen hub for all the baking. Any leftovers at the end of the day were sold to local consumers or were distributed to shelters. 

The bakery launched a new e-commerce website; they needed assistance with better understanding their analytics and making sure they are getting the best out of Google Analytics 4 and took advantage of integrating with Big Query to future proof their data. Previously they had a got a lot of good insights from GA3 but also found it bit of a bottleneck as they were unable to cut and slice the data in different ways to en-rich the insights.  

One of the key questions they wanted to be able to answer was the split between new v returning customers. GA3 did not provide a great view on new v returning.    

(Image from Google Merch Shop GA3 demo account)

Some of the key questions the bakery wanted to answer:

  • What was the split between new v returning customers.
  • What is the impact of campaigns and seasonality on driving new v returning customers.  
  • What channels are driving new v returning customers.
  • What is the contribution of revenue between new v returning.
  • Also understand the frequency of purchases.

This is where Google Analytics 4 event model and the integration with Big Query was invaluable being able to answer the split of new v returning customers but also frequency of purchase. The event_name = purchase (this is triggered by a tag built in Google Tag Manager) is what the code is built around. The core components of building the query:

  • user_id – is a unique ID generated when a user logs-in to the website. The user_id will be recognised when the user logs into the site again from any device or browser.
  • user_pesudo_id – is generated when the user first visits the website. The user_pseudo_id will be recognized when the user visits the site again from the same device and browser.
  • event_date – the date on which the event was logged.
  • order_id – the unique order ID of the customer’s purchase
  • purchase_revenue – the revenue generated for that purchase associated to the order_id

This would generate an output with the column called customer_type which is the key column in calculating new or returning or frequency of purchase.

To enrich the data to provide greater context also added:

  • source – name of the traffic source i.e., facebook
  • medium – name of the medium i.e., paidsocial
  • name – name of the campaign i.e., summer2024

The caveat being that a new customer may not necessarily be their first purchase with the brand.

Building the Query

To understand new v returning customers and purchase frequency, we constructed an optimised SQL query centered on a single Common Table Expression (CTE) named ranked_purchases. By focusing exclusively on purchase events, we efficiently process order histories while maintaining lean BigQuery scan costs

Query 1 – New v Returning

We have identified and categorised customers into two primary segments: “new customer” and “returning customer.”

  • Single CTE Architecture: Our main query processes order records through a single CTE (ranked_purchases), eliminating unnecessary secondary grouping steps.
  • User-Stitching: Unifies cross-device customer histories using COALESCE(user_id, user_pseudo_id) so registered buyers returning on different devices are accurately recognized.
  • Chronological Ranking: Employs the DENSE_RANK() window function partitioned by customer ID and ordered by event_timestamp ASC to evaluate each purchase’s position in the customer’s lifetime.
  • Customer Classification: The CASE statement assigns ‘new customer’ for rank 1 (first purchase) and ‘returning customer’ for all subsequent orders (rank > 1).
  • Performance & Hygiene: Restricts dataset scans using _TABLE_SUFFIX partition pruning and filters out null transaction IDs to ensure clean data quality.

Breakdown of the Code 

Lines 3 & 14: Cross-Device User Stitching: Uses COALESCE(user_id, user_pseudo_id) to unify guest browsing IDs with authenticated login IDs, ensuring buyers returning on different devices are identified correctly

COALESCE(user_id, user_pseudo_id) AS customer_id,
ecommerce.transaction_id AS order_id,
ecommerce.purchase_revenue AS revenue,
DATE(TIMESTAMP_MICROS(event_timestamp)) AS order_date,
TIMESTAMP_MICROS(event_timestamp) AS order_timestamp,
traffic_source.source AS source,
traffic_source.medium AS medium,
traffic_source.name AS campaign,

-- Rank purchases chronologically per customer
DENSE_RANK() OVER (
PARTITION BY COALESCE(user_id, user_pseudo_id) 

Line 6: Efficient Date Conversion: Converts TIMESTAMP_MICROS(event_timestamp) directly to a DATE object (order_date) rather than parsing strings

 DATE(TIMESTAMP_MICROS(event_timestamp)) AS order_date,

Lines 13–16: Chronological Purchase Ranking: Applies DENSE_RANK() OVER (PARTITION BY COALESCE(user_id, user_pseudo_id) ORDER BY event_timestamp ASC) to order every purchase chronologically for each user

DENSE_RANK() OVER (
PARTITION BY COALESCE(user_id, user_pseudo_id) 
ORDER BY event_timestamp ASC
) AS purchase_rank

Lines 20–22: Partition Pruning & Data Hygiene: Applies _TABLE_SUFFIX >= FORMAT_DATE(…) to restrict BigQuery byte scans to the last 24 months, and excludes ecommerce.transaction_id IS NOT NULL to keep broken tags from skewing results

 _TABLE_SUFFIX >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 24 MONTH))
AND event_name = 'purchase'
AND ecommerce.transaction_id IS NOT NULL

Lines 33–36: Segment Classification: The CASE statement flags purchase_rank = 1 as ‘new customer’ and all higher ranks as ‘returning customer’

CASE
WHEN purchase_rank = 1 THEN 'new customer'
ELSE 'returning customer'
END AS customer_type

Query 2 – Frequency of Purchase

We have identified and categorised customers into four primary segments: “first purchase”, “second purchase”, “repeat purchase”, and “recurring customer”.

The categorisation for tracking purchase frequency can easily be adapted to suit specific e-commerce business models.

  • Single-Pass Ranking: Evaluates purchase_rank once within the ranked_purchases CTE using DENSE_RANK() OVER (PARTITION BY COALESCE(user_id, user_pseudo_id) ORDER BY event_timestamp ASC). This avoids re-evaluating the window function multiple times inside the main statement.
  • Cross-Device User Stitching: Uses COALESCE(user_id, user_pseudo_id) to ensure repeat purchases across different devices are accurately tied to a single customer profile.
  • Streamlined CASE Logic: The main query reads the pre-calculated purchase_rank integer directly to assign granular frequency labels:
    • ‘first purchase’ for a customer’s initial transaction (purchase_rank = 1).
    • ‘second purchase’ for their second order (purchase_rank = 2).
    • ‘repeat purchase’ for orders occurring between 3 and 5 times (purchase_rank BETWEEN 3 AND 5).
    • ‘recurring customer’ for purchase frequencies exceeding 5 orders (purchase_rank > 5).
  • Optimised Execution & Hygiene: Restricts table scans via _TABLE_SUFFIX partition pruning and excludes missing transaction_id records to ensure data integrity.
WITH ranked_purchases AS (
SELECT
COALESCE(user_id, user_pseudo_id) AS customer_id,
ecommerce.transaction_id AS order_id,
ecommerce.purchase_revenue AS revenue,
DATE(TIMESTAMP_MICROS(event_timestamp)) AS order_date,
TIMESTAMP_MICROS(event_timestamp) AS order_timestamp,
traffic_source.source AS source,
traffic_source.medium AS medium,
traffic_source.name AS campaign,

 -- Evaluate rank once in the CTE to avoid repeating window functions
DENSE_RANK() OVER (
PARTITION BY COALESCE(user_id, user_pseudo_id) 
ORDER BY event_timestamp ASC
) AS purchase_rank
FROM
`enter.tablename_123456.events_*`
WHERE
_TABLE_SUFFIX >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 24 MONTH))
AND event_name = 'purchase'
AND ecommerce.transaction_id IS NOT NULL
)

SELECT
customer_id,
order_id,
revenue,
order_date,
source,
medium,
campaign,
purchase_rank,
CASE
WHEN purchase_rank = 1 THEN 'first purchase'
WHEN purchase_rank = 2 THEN 'second purchase'
WHEN purchase_rank BETWEEN 3 AND 5 THEN 'repeat purchase'
ELSE 'recurring customer'
END AS customer_type
FROM
ranked_purchases
ORDER BY
order_date DESC,
order_timestamp DESC;

Lines 13–16: Single Window Evaluation: Computes purchase_rank once inside the ranked_purchases CTE using DENSE_RANK(). This avoids running expensive window functions multiple times across conditional logic branches

DENSE_RANK() OVER (
PARTITION BY COALESCE(user_id, user_pseudo_id) 
ORDER BY event_timestamp ASC
) AS purchase_rank

Lines 34–38: Granular Frequency Mapping: Evaluates the integer value of purchase_rank to assign explicit customer lifecycle tiers (‘first purchase’, ‘second purchase’, ‘repeat purchase’, and ‘recurring customer’)

 CASE
WHEN purchase_rank = 1 THEN 'first purchase'
WHEN purchase_rank = 2 THEN 'second purchase'
WHEN purchase_rank BETWEEN 3 AND 5 THEN 'repeat purchase'
ELSE 'recurring customer'

Why Use a Single CTE Architecture? By structuring the transformation inside a clean Common Table Expression (CTE), the query isolates raw event extraction from business logic classification. This improves code readability, streamlines maintenance, and optimizes BigQuery’s execution engine over traditional subqueries or temporary tables.

Modifying the query for the business model  

The two queries built are for an e-commerce business model, any business model that focuses on acquisition and retention would want to understand new v returning customers and frequency of purchase. The context of the insights will change depending on the business model. (link to GitHub to download SQL code)

  • For lead generation it may be getting a user to complete a registration form so within the query the purchase event would need to be replaced with the registration
    • It will provide insights; how many of those registrations are coming from new v returning.
    • Also understand how many times a registration has been completed against i.e., user_pesudo_id
  • For a specific business model, it may require the user to log-in the user_pseudo_id can be replaced with user_id.

Visualisation

Having a rich data set is the first step, then it’s all about visualisations to provide insights to those burning questions. There are many ways to build out visualization using Big Query, there is a connector to Looker Studio (Data Studio) or Python or Tableau all depending on the ecosystem in place. 

(Data in the charts has been modified for this article)

This chart looks at the % revenue driven by new v returning customers by month.

This chart looks at the frequency of purchase and how the revenue is split.

This is an example the kind of insights possible but there is a wealth of data available that can be cut and sliced in different ways to answer the business questions.

Looking ahead

Being able to analyse the split between new v returning customers and measure true purchase frequency is a critical piece of the data puzzle for growing e-commerce brands. Achieving this level of clarity relies on high-quality historical data, a robust Google Tag Manager and Google Analytics 4 implementation, seamless user stitching, and a clean pipeline into BigQuery. Most importantly, it requires a well-defined strategy centered on asking the right business questions to turn raw event tables into actionable growth levers.

Worked on this project with Jeffrey Ohene who built the SQL code in Big Query.