Zero Labs
Industry News / AI

Designing a Scalable, Production-Ready E-commerce Database in BigQuery

Source · Towards AI By Gift Ojeabulu

From the publisher’s feed, collected in the ZeroLabs newsroom.

A deep-dive into Google’s eCommerce dataset with corrected, production-verified SQLPhoto by Christina @ wocintechchat.com on UnsplashThe Interview That Froze My BrainDesign an e-commerce database schema.You have 45 minutes.Share your screen.Gift opened his code editor, cursor blinking in an empty SQL file.He’d memorised normalisation rules and foreign key constraints, but staring at the blank screen with three interviewers watching made his mind go blank. The senior engineer smiled and added,“Start with what you know; users need to buy products, right?”That simple prompt changed everything. Gift began typing: CREATE TABLE users..., thenproducts, then orders. But then came the hard questions in the chat:How do you handle price changes?What about inventory tracking across different warehouses?Can you write a query for monthly revenue that an accountant would actually trust?He fumbled through it, wishing he had explored a real production database beforehand, not just textbook examples, but something he could actually query, breakdown, and understand deeply.This article is what Gift needed before that interview.We walk through Google BigQuery’s theLook eCommerce dataset: a real, production-quality schema used by thousands of data professionals. Every SQL query here has been verified and corrected, so you can run it directly in your console without surprises.Setting Up BigQueryBefore we dive in, let’s get you set up so you can explore alongside us. The eCommerce dataset is publicly available in BigQuery, no credit card required:BigQuery Console: Explorer Panel LayoutQuick Setup (5 minutes):Go to the BigQuery console (requires a free Google account)In the Explorer panel, click “+ ADD” → “Public Datasets”Search for thelook_ecommerce and click "View Dataset"You will see it appear as bigquery-public-data.thelook_ecommerce in your ExplorerBigQuery’s free tier gives you 1 TB of queries per month — more than enough to explore this entire dataset multiple times. Start with a simple warm-up query:-- Try your first query (free!)SELECT category, COUNT(*) as product_countFROM `bigquery-public-data.thelook_ecommerce.products`GROUP BY categoryORDER BY product_count DESC;Every SQL query in this article can be run directly in your console.If you are preparing for a database design interview, one of the best ways to learn is by studying how real-world databases are structured. In this example, we will explore a fictional yet realistic clothing store database designed to resemble the systems used by professional data teams and companies today.Table of ContentsWhy Study Real-World Schemas?Exploring the Schema StructureThe Schema Design Principles in ActionReal-World Query PatternsInterview-Ready Design InsightsAdvanced Patterns: Event TrackingWhat This Schema Teaches YouKey TakeawaysWhy Study Real-World Schemas?TheLook eCommerce is a public dataset in BigQuery containing synthetic yet realistic data on customers, products, orders, logistics, web events, and marketing campaigns.Unlike textbook examples, this schema reflects decisions made by experienced engineers on Google’s Looker team. Understanding why each design choice was made is the difference between a junior and a senior interview answer.Exploring the Schema StructureThe dataset has seven interconnected tables. Here is a concise overview of each one and what role it plays in the broader system.Schema overview: How the seven tables connect in TheLook E-CommerceLet’s examine the core entities:Core Tables Overviewusers: Stores customer information. Each user has a unique ID, email, age, gender, country, and latitude/longitude coordinates. The geographic fields are not decorative; they enable real shipping-distance calculations (covered later).products: The product catalogue: category, brand, retail price, and cost. Products belong to categories like “Jeans”, “Intimates”, or “Active”. Crucially, this table stores both retail_price and cost, making profit analysis possible.orders: The order header: links a customer to a purchase. Contains user_id, order status (Complete, Cancelled, Returned), item count, creation timestamp, and shipping details. This is the bridge between users and their line items.order_items: The line items for each order. This table connects orders to specific products and stores the sale_price at the moment of purchase, not a reference to the current product price. It carries its own user_id for direct customer analysis, plus four timestamps: created_at, shipped_at, delivered_at, and returned_at..inventory_items: Tracks individual physical units, not aggregate stock counts. Each record knows its specific product, which distribution centre holds it, whether it has been sold, and its acquisition cost.distribution_centers : Warehouse locations with names and geographic coordinates. Combined with user latitude/longitude, this enables distance-based shipping optimisation.events: Web analytics: page views, cart additions, and purchase events, with traffic source, browser, and URI tracking. This is how the transactional system connects to behavioural and marketing analysis.The Schema Design Principles1. Normalizing Product DataProducts and inventory are deliberately separate. The products table stores catalogue information (name, category, brand, retail price), while inventory_items tracks physical units. This means updating a product’s retail price does not require touching thousands of inventory records.-- Products table structureSELECT id, cost, category, name, brand, retail_price, department, skuFROM `bigquery-public-data.thelook_ecommerce.products`LIMIT 5;2. Historical Price Trackingorder_items stores sale_price at the moment of purchase, not a foreign key to the current product price. This is a must-have for financial reporting accuracy: a refund issued six months later must reflect what the customer originally paid, not today’s sale price.3. Many-to-Many With Business ValueOrders and products have a many-to-many relationship. order_items is the junction table, but it carries real business value: individual item status, the sale price, four per-item timestamps, and its own user_id for direct customer analysis. This goes well beyond a simple bridge table.4. Strategic Denormalizationorder_items stores user_id directly even though it already links toorders, which itself links to users. This deliberate duplication means you can analyse customer purchasing behaviour without always joining through orders , a meaningful performance win at scale, and a deliberate design choice, not an accident.Production-Verified Query PatternsIn a technical interview, writing correct SQL is only half the task. The other half is explaining the assumptions behind each decision.Monthly Revenue AnalysisGoal: Calculate how much money the business makes each month, in a way an accountant would actually trust.Because order_items carries its own user_id, you can count unique customers directly, no join through orders required for that metric alone. However, joining through orders is still useful when you need order-level attributes like num_of_item or the order-level status.SELECT DATE_TRUNC(DATE(created_at), MONTH) AS month, SUM(sale_price) AS gross_revenue, COUNT(DISTINCT order_id) AS total_orders, COUNT(DISTINCT user_id) AS unique_customersFROM `bigquery-public-data.thelook_ecommerce.order_items`WHERE status = 'Complete'GROUP BY 1ORDER BY 1 DESC;Why these decisions matter:Filter for 'Complete' only. Never SUM(sale_price) across all statuses; cancelled or returned items inflate revenue. Filtering on status is the difference between a number that passes audit and one that does not.Name it gross_revenue. This signals to the interviewer that you understand shipping costs and taxes may still need to be deducted for net revenue.Product Performance by CategoryGoal: Compare revenue and profit across product categories, using cost data from inventory.SELECT p.category, COUNT(DISTINCT oi.order_id) AS orders, SUM(oi.sale_price) AS revenue, SUM(oi.sale_price - ii.cost) AS profitFROM `bigquery-public-data.thelook_ecommerce.order_items` oiJOIN `bigquery-public-data.thelook_ecommerce.inventory_items` ii ON oi.inventory_item_id = ii.idJOIN `bigquery-public-data.thelook_ecommerce.products` p ON ii.product_id = p.idWHERE oi.status = 'Complete'GROUP BY p.categoryORDER BY revenue DESC;Why join through inventory_items?The cost per unit lives in inventory_items, not in products. You need it to calculate profit. The join path is order_items → inventory_items → products.Customer Geographic AnalysisGoal: Understand which countries drive the most revenue, filtering out cancelled and returned orders.Since order_items carries user_id, you can join directly to users:SELECT u.country, COUNT(DISTINCT u.id) AS customer_count, COUNT(DISTINCT oi.order_id) AS total_orders, ROUND(SUM(oi.sale_price), 2) AS total_revenueFROM `bigquery-public-data.thelook_ecommerce.users` uJOIN `bigquery-public-data.thelook_ecommerce.order_items` oi ON u.id = oi.user_idWHERE oi.status NOT IN ('Cancelled', 'Returned')GROUP BY u.countryORDER BY total_revenue DESCLIMIT 10;Interview-Ready Design InsightsStatus Management StrategyTheLook uses string-based status fields ('Complete', 'Cancelled', 'Returned') rather than foreign keys to a status table. For an interview, acknowledge both approaches: string enumerations are simpler to query but less flexible than a status table that can carry metadata like transition timestamps or allowed state transitions.Timestamp TrackingEvery transaction table includes timestamps: created_at, shipped_at, delivered_at, returned_at. This granular tracking enables customer service queries ("when was it shipped?"), logistics analysis (average delivery time), fraud detection (suspicious timing patterns), and cohort analysis.Geographic Data for Distance CalculationsBoth users and distribution_centers store latitude and longitude. This enables distance-based queries for shipping optimisation:SELECT u.id AS user_id, dc.name AS warehouse, ROUND( 6371 * ACOS( LEAST(1.0, COS(u.latitude * PI() / 180) * COS(dc.latitude * PI() / 180) * COS((dc.longitude - u.longitude) * PI() / 180) + SIN(u.latitude * PI() / 180) * SIN(dc.latitude * PI() / 180) ) ), 2 ) AS distance_kmFROM `bigquery-public-data.thelook_ecommerce.users` uCROSS JOIN `bigquery-public-data.thelook_ecommerce.distribution_centers` dc;Note the LEAST(1.0, ...) wrapper inside ACOS. Floating-point arithmetic can produce values like 1.0000000000000002 due to rounding, which causes ACOS to throw a domain error. Always guard it.Inventory Item GranularityThe inventory_items table tracks individual units, not just aggregate counts. Each item knows its specific product, which distribution centre holds it, whether it has been sold, and its acquisition cost.This granularity supports sophisticated inventory management but increases storage significantly.In an interview, discuss this trade-off — it suits a fashion retailer with thousands of distinct SKUs, but would not suit a grocery chain selling millions of identical units.Conversion Funnel AnalysisThe events table captures web analytics with fields like event_type, traffic_source, browser, and uri. This demonstrates how transactional systems integrate with behavioural data for marketing analysis.WITH funnel AS ( SELECT user_id, COUNTIF(event_type = 'home') AS homepage_visits, COUNTIF(event_type = 'product') AS product_views, COUNTIF(event_type = 'cart') AS cart_adds, COUNTIF(event_type = 'purchase') AS purchases FROM `bigquery-public-data.thelook_ecommerce.events` GROUP BY user_id)SELECT COUNT(*) AS total_users, SUM(IF(homepage_visits > 0, 1, 0)) AS reached_homepage, SUM(IF(product_views > 0, 1, 0)) AS viewed_products, SUM(IF(cart_adds > 0, 1, 0)) AS added_to_cart, SUM(IF(purchases > 0, 1, 0)) AS completed_purchaseFROM funnel;The CTE first aggregates per-user event counts. The outer query then converts those counts into binary flags, giving you the classic funnel shape: how many users made it from homepage to purchase.What This Schema Teaches YouFor Interview SuccessSeparate concerns cleanly: Products, inventory, and orders are distinct entities with clear relationships. Conflating them leads to update anomalies and brittle queries.Preserve history at transaction time: sale_price lives in order_items, not as a reference to products.retail_price. Every historical order reflects what the customer actually paid.Understand what denormalisation buys you: order_items carries user_id even though orders already links to users. This is not redundancy for its own sake; it enables direct customer analysis on the most-queried table in the system without an extra join.Plan for analytics: Timestamps and geographic data are not decorative. They are the raw material for delivery SLA tracking, fraud detection, and shipping optimisation.Think about scale: Individual inventory tracking works for fashion retail with thousands of distinct SKUs. It would not work for a grocery chain. Always tie your design choices to the specific business context.Common Interview Questions“Why separate inventory_items from products?" Products are catalogue entries. Inventory items are physical units. You need separate records per unit to track which distribution centre holds each item, what it cost per shipment batch, and whether it has been sold. A single product can have hundreds of inventory records at any given time.“Why store sale_price in order_items instead of referencing products?" Prices change. Historical orders must reflect what customers actually paid for accurate financial reporting, correct refund calculations, and audit-proof accounting. If you referenced the current product price, every historical order value would silently drift as prices change.“Why does order_items have both order_id and user_id?" This is strategic denormalisation. user_id can be derived by joining throughorders, but storing it directly on order_items eliminates that join for the most common analytical queries: customer revenue, customer activity, customer cohorts, on the highest-volume table in the system. The storage cost is trivial; the query performance benefit at scale is real.“How would you optimise for high query volume?” Add indexes on foreign key columns (user_id, product_id, order_id). Create materialised views for common aggregations like daily revenue by category. Partition orders and order_items by date to limit scan size. In BigQuery specifically, cluster on high-cardinality filter columns.“What’s missing from this schema?” Real-world extensions would likely include payment processing details, shipping carrier and tracking number integration, product reviews and ratings, wishlist functionality, promotional codes and discount tracking, and customer service ticket linking.Key TakeawaysTheLook eCommerce demonstrates professional database design principles in action. The schema balances normalisation with strategic denormalisation, preserves historical data at transaction time, and includes thoughtful details like geographic coordinates and granular per-item status tracking.The patterns that come up again and again in production and in interviews are:Separate concerns cleanly: Products, inventory, and orders are distinct entities.Preserve history: Store prices and statuses at transaction time, never by reference.Understand your join paths: Know which tables carry which foreign keys and why order_items carries user_id directly, which is a deliberate design choice worth explaining.Guard your arithmetic: Floating-point edge cases break ACOS always use LEAST(1.0, ...).Tie every design decision to the business context. The best database designs are not the most theoretically pure; they are the ones that solve real business problems efficiently. TheLook eCommerce exemplifies this pragmatic approach.For your interview preparation, the best next step is hands-on.Go to the BigQuery console and try answering these business questions yourself:Which product category generates the most profit?What is the average order value by country?How many days on average separate order creation and delivery?Which traffic source drives the highest purchase conversion rate?Connect with me on LinkedInConnect with me on TwitterDesigning a Scalable, Production-Ready E-commerce Database in BigQuery was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.