4: Preparing and using data for analysis

    Preparing data for visualization. Considerations include

    How it works

    Visualization workloads expose a data warehouse to humans through dashboards, ad hoc explorers, and embedded reports.

    The operating envelope is different from analyst-driven SQL: a Looker dashboard with twelve tiles can fan out into dozens of concurrent BigQuery jobs every time a user changes a filter, and each tile is expected to render in under two seconds.

    The data engineer's job is to shape the data and the access layer so that this interactive load is satisfied at a predictable cost without rewriting the underlying physical model for every consumer.

    Direct scans of fact tables work for analyst notebooks. They do not work for dashboards.

    The exam frames preparing data for visualization as a chain of decisions:

    • which tool connects to the warehouse,
    • what gets precalculated and where,
    • which BigQuery acceleration features absorb the interactive load,
    • how to diagnose a slow tile,
    • how to keep all of this within the security model defined by IAM, policy tags, dynamic data masking, and Cloud DLP.

    The right answer rarely involves a single feature. It involves choosing the cheapest precalculation that meets the latency budget, the smallest BI Engine reservation that covers the active dataset, and the most restrictive access path that still lets the dashboard render.

    Connecting to tools

    The connection layer determines authentication, identity propagation, and query shape.

    Three connection paths cover virtually all visualization exam scenarios:

    • Looker (with LookML)
    • Looker Studio (formerly Data Studio)
    • Third-party tools through JDBC or ODBC

    Each path has its own authentication semantics that the exam tests directly.

    Looker connects to BigQuery through a service account, then layers identity through LookML user attributes and access filters.

    The PDT (persistent derived table) and aggregate awareness features in LookML are precalculation tools that live in the BI layer, not in BigQuery itself.

    A persistent derived table is a Looker-managed scratch table written into a dedicated BigQuery dataset on a schedule defined by datagroup_trigger or sql_trigger_value.

    Aggregate awareness lets a Looker query rewriter substitute a pre-aggregated rollup for a detail query when the requested grain matches.

    Both push precalculation into Looker's control plane and leave BigQuery responsible only for storage and slot execution.

    In practice

    Looker Studio connects through one of two credential models: viewer credentials or owner credentials.

    Owner credentials mean every report consumer queries BigQuery as the report author's identity, which removes the need to grant each consumer access to the underlying dataset but blurs audit lineage.

    Viewer credentials require the consumer to have direct IAM access.

    For shared dashboards across an external audience the owner-credentials model is standard, paired with row-level access controls inside BigQuery that key on SESSION_USER() to scope what each user sees.

    Reports built on BigQuery extracts (snapshot copies stored in Looker Studio's managed storage) avoid live query cost at the price of staleness up to twelve hours per extract.

    JDBC and ODBC connections from tools like Tableau, Power BI, MicroStrategy, and Qlik authenticate either with a service account JSON key (deprecated in many security baselines), OAuth user credentials, or Application Default Credentials when the tool runs on Google Cloud compute.

    JDBC connections honor session parameters like query_label and maximum_bytes_billed, which are the two most reliable cost guardrails for ad hoc BI traffic.

    Setting maximum_bytes_billed on the connection string caps any single query at a known byte count, so an analyst who drops a partition filter cannot accidentally trigger a five-terabyte scan.

    The BigQuery Storage Read API matters here for any tool that pulls large result sets into a local engine.

    Power BI's DirectQuery mode and Tableau's Hyper extract refresh both use the Storage Read API when configured against the BigQuery connector, which streams Arrow-format columnar batches in parallel and avoids the legacy TabledataList REST path.

    The Storage Read API is the right answer whenever the question describes "pulling millions of rows into a BI tool" or "refreshing a Tableau extract from a wide BigQuery table".

    from google.cloud import bigquery_storage_v1
    from google.cloud.bigquery_storage_v1 import types
    
    bqs = bigquery_storage_v1.BigQueryReadClient()
    table = "projects/marketing-prod/datasets/sales_curated/tables/order_facts"
    
    requested_session = types.ReadSession(
     table=table,
     data_format=types.DataFormat.ARROW,
     read_options=types.ReadSession.TableReadOptions(
     selected_fields=["order_id", "customer_id", "order_total", "order_date"],
     row_restriction="order_date >= '2024-01-01'",
     ),
    )
    
    session = bqs.create_read_session(
     parent="projects/marketing-prod",
     read_session=requested_session,
     max_stream_count=8,
    )
    

    Connect Sheets is the path for spreadsheet users.

    It exposes BigQuery tables inside Google Sheets with native pivot and chart support, bounded to one billion rows per refresh and constrained by the connecting account's IAM.

    The exam treats Connect Sheets as the right answer when the consumer is a non-technical analyst who needs spreadsheet ergonomics on top of BigQuery without copying data to a local file.

    💡 Exam Trap: Looker Studio "owner credentials" do not bypass row-level security keyed to SESSION_USER(), because the function returns the credential identity, not the report viewer. If a question asks how to enforce per-viewer row filters through Looker Studio, the answer is Looker Studio Pro with managed user attributes plus viewer credentials, not owner credentials.

    💡 Exam Trap: Service account JSON key files are valid for JDBC and ODBC connections, but Organization Policy constraints/iam.disableServiceAccountKeyCreation blocks their creation in regulated environments. The exam-correct alternative is Workload Identity Federation for the BI tool's compute environment, then service account impersonation from the federated identity.

    Precalculating fields

    Precalculation pushes the cost of computation away from the moment a dashboard tile renders and toward a scheduled batch step. The choice of where precalculation lives is a cost and freshness trade-off across four locations:

    • a presentation-layer table written by a scheduled query or Dataform,
    • a materialized view managed by BigQuery,
    • a BI Engine in-memory representation,
    • a BI-layer aggregate inside Looker or Looker Studio.

    Presentation tables are the broadest tool. They are written by a scheduled query, a Dataform target, a Dataflow job, or a Cloud Composer DAG, and they hold the exact shape the dashboard reads. The advantage is unlimited transformation flexibility, including window functions, calls to remote models, and joins to external sources. The cost is staleness equal to the scheduling cadence and storage equal to the precomputed shape. Presentation tables are typically partitioned by report date and clustered by the highest-cardinality filter dimension.

    Materialized views are the precalculation tool maintained by BigQuery itself. A materialized view holds the result of an aggregation query and is refreshed automatically when the base table changes, subject to a maximum staleness configuration.

    Materialized views support aggregation functions (SUM, COUNT, MIN, MAX, AVG, COUNTIF, ARRAY_AGG, and approximate aggregates), inner joins on equality predicates, and filters. They do not support outer joins, DISTINCT outside COUNT(DISTINCT ...) approximation, window functions, or user-defined functions.

    The query optimizer automatically substitutes a materialized view for a base-table query when the optimizer can prove the view satisfies the request, even when the SQL does not reference the view by name. This optimizer rewrite is the property that makes materialized views worth the storage cost relative to a hand-written rollup table.

    CREATE MATERIALIZED VIEW marketing_prod.sales_mart.order_daily_by_region
    PARTITION BY order_date
    CLUSTER BY region
    OPTIONS (
     enable_refresh = TRUE,
     refresh_interval_minutes = 30,
     max_staleness = INTERVAL "1" HOUR,
     allow_non_incremental_definition = FALSE
    )
    AS
    SELECT
     DATE(order_ts) AS order_date,
     region,
     COUNT(*) AS order_count,
     SUM(order_total) AS order_total,
     COUNT(DISTINCT customer_id) AS customer_count
    FROM marketing_prod.sales_curated.order_facts
    WHERE order_ts >= TIMESTAMP "2023-01-01"
    GROUP BY 1, 2;
    

    Computed columns inside the warehouse can also be implemented through SQL persisted user-defined functions, where the function body is stored in a routine and the dashboard query references the routine.

    The routine pattern centralizes formula logic (revenue net of refunds, customer lifetime value buckets) so dashboards across teams reach the same numerical answer.

    BI-layer precalculation, in contrast, keeps the warehouse free of report-specific rollups.

    Looker aggregate awareness is the canonical example: an aggregate_table defined in LookML registers a pre-aggregated rollup, and Looker's query rewriter substitutes the rollup whenever the user requests a compatible grain.

    The trade-off is that the aggregate rollup is opaque to non-Looker consumers and must be rebuilt for every new BI tool.

    📊 Limit: A BigQuery materialized view supports a single base table per definition. Multi-table aggregation requires either a chained materialized view over a pre-joined view (not supported) or a presentation table written by a scheduled query. The exam-correct answer to "aggregate across three fact tables" is a Dataform-managed table, not a materialized view.

    ⚠️ Anti-Pattern: Writing a presentation table on every dashboard refresh with CREATE OR REPLACE TABLE ... AS SELECT. The job rewrites every partition, costs the full scan each run, and invalidates time travel for downstream tables. Use MERGE against partition predicates, or use a materialized view with max_staleness.

    BigQuery features for business intelligence (e.g., BI Engine, materialized views)

    BigQuery exposes two acceleration layers above the standard query engine: materialized views (covered above) and BI Engine.

    They solve different problems and stack: a query against a materialized view that fits in a BI Engine reservation runs entirely in memory with no slot consumption beyond the metadata path.

    BI Engine is an in-memory columnar cache attached to a project through a capacity reservation expressed in gibibytes. A BI Engine reservation is a project-scoped resource.

    Tables and table partitions are loaded into the cache lazily on first query access, evicted by an LRU policy when the reservation is full, and refreshed automatically when underlying data changes.

    BI Engine accelerates queries that filter on partitioned and clustered tables, aggregations, and joins with cardinality patterns suited to the in-memory engine.

    Queries that BI Engine cannot accelerate fall back to standard slot execution transparently, and the bi_engine_statistics field of the query result describes whether and why acceleration occurred.

    SELECT
     job_id,
     bi_engine_statistics.bi_engine_mode,
     bi_engine_statistics.acceleration_mode,
     ARRAY(
     SELECT AS STRUCT reason.code, reason.message
     FROM UNNEST(bi_engine_statistics.bi_engine_reasons) AS reason
     ) AS rejection_reasons,
     total_bytes_processed,
     total_slot_ms
    FROM `region-us`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
    WHERE creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 DAY)
     AND statement_type = "SELECT"
     AND bi_engine_statistics.bi_engine_mode IS NOT NULL
    ORDER BY creation_time DESC;
    

    BI Engine acceleration modes are:

    • FULL (the query ran entirely in BI Engine)
    • PARTIAL (BI Engine handled part of the plan)
    • DISABLED (the query fell back to standard execution)

    The most common rejection reasons in production are:

    • UNSUPPORTED_SQL (a query feature not yet supported in BI Engine)
    • INPUT_TOO_LARGE (the data exceeded the reservation)
    • OTHER_REASON (a transient cause)

    The exam pattern is to recognize that a dashboard with a 50 GB working set requires a 50 GB reservation plus headroom for concurrent loaded partitions, not a 10 GB reservation that thrashes.

    📊 Limit: A BI Engine reservation is sized between 1 GB and 250 GB per project per region. Reservations are billed by GB-hour and can be modified or removed at any time. A single query is accelerated only if its working set fits within the project's reservation.

    Materialized views and BI Engine compose: the optimizer can rewrite a base-table query into a materialized view query, and the materialized view can be served from BI Engine.

    The combination is the exam answer to "sub-second dashboard latency on a multi-terabyte fact table".

    The materialized view collapses billions of base rows into millions of pre-aggregated rows, and BI Engine holds that smaller result entirely in memory.

    Search indexes are a third acceleration feature relevant to BI workloads that filter on free-text columns.

    A search index built with CREATE SEARCH INDEX accelerates SEARCH() predicates against log-style tables and product catalog tables.

    The index is most useful for needle-in-haystack lookups (find the one order with this confirmation code) rather than analytic aggregation.

    Vector indexes serve embedding-similarity queries and are covered in the AI and ML section.

    💡 Exam Trap: BI Engine is not a separate service. It is a reservation attached to a BigQuery project. Creating a reservation does not migrate data; it allocates memory that will fill on first query access. The exam-correct latency answer is "create a reservation, then run the dashboard to warm the cache", not "create a reservation and immediately measure performance".

    Troubleshooting poor performing queries

    Slow dashboard queries fall into recognizable failure modes. The exam expects fluency with three diagnostic surfaces: the query execution graph (visible in the BigQuery console as the explain plan), INFORMATION_SCHEMA.JOBS_BY_PROJECT and its siblings, and the BigQuery admin resource charts.

    The execution graph reports per-stage byte counts, slot time, shuffle bytes, and wait time.

    The single most useful number is shuffle bytes per stage, because excessive shuffle indicates a join key with skew or a missing cluster on the larger side of the join.

    A stage that reports wait time approaching slot time indicates slot starvation, which means the reservation is undersized for the query mix at that moment.

    INFORMATION_SCHEMA.JOBS_BY_PROJECT exposes per-job statistics including total_bytes_processed, total_slot_ms, total_bytes_shuffled, and cache_hit.

    Slot-millisecond ratios across jobs identify the top consumers, and query_info.resource_warning flags queries that issued warnings such as overly broad partition predicates.

    SELECT
     user_email,
     job_id,
     query_info.resource_warning,
     total_bytes_processed / POW(2, 40) AS tb_processed,
     total_slot_ms / 1000 / 60 AS slot_minutes,
     TIMESTAMP_DIFF(end_time, creation_time, SECOND) AS elapsed_seconds,
     total_bytes_shuffled / POW(2, 30) AS gb_shuffled,
     cache_hit
    FROM `region-us`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
    WHERE creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
     AND statement_type = "SELECT"
     AND state = "DONE"
    ORDER BY total_slot_ms DESC
    LIMIT 50;
    

    The five recurring causes of slow BI queries are:

    • missing partition or cluster filter (the query scans the full table because the partition column is not in the WHERE clause)
    • join skew (one key value dominates the distribution and a single worker processes most of the join)
    • wildcard scan over a large suffix table set (SELECT ... FROM project.dataset.table_* without a _TABLE_SUFFIX filter)
    • unfiltered nested unnest expansion (cross-product growth from UNNEST on a high-cardinality repeated field)
    • BI Engine eviction churn (working set exceeds the reservation and partitions are loaded and evicted repeatedly)

    The query plan visualizer surfaces each of these.

    For partition skipping, the input stage shows "table read" with the partition range that was actually pruned. If the visualizer shows all partitions read, the partition filter is not effective.

    For join skew, the join stage shows max worker time far exceeding average worker time, and the shuffle stage reports bytes per key with one key dominating the distribution. The remedy for skew is to introduce a salt key into the join (concatenate the dominant key with a small random suffix on one side, then explode the other side to match) or to broadcast the smaller table when its size is below the broadcast threshold.

    🎯 Scenario: A Looker dashboard tile that aggregates sales_curated.order_facts by region renders in 14 seconds. The execution graph shows 7.2 TB scanned, with the largest stage consuming 1.2 hours of slot time. The fact table is partitioned by order_date but the LookML view computes order_date from TIMESTAMP(order_ts) instead of using the partition column directly. Because the partition predicate is wrapped in a function, the optimizer cannot prune partitions. The fix is to expose order_date as a stored column and reference it directly in the LookML filter, restoring partition pruning and dropping the scan to 80 GB.

    Query queueing is a separate failure mode. When a reservation runs at capacity, additional jobs queue.

    The pending state visible in INFORMATION_SCHEMA.JOBS_TIMELINE_BY_PROJECT reveals how long a job waited before execution. Queue time is invisible in the per-query plan but shows up as dashboard latency.

    The remedy is either expanding the reservation, moving the dashboard workload to a dedicated reservation through job labels and assignments, or moving the working set to BI Engine.

    Slot autoscaling in BigQuery Editions sets a baseline slot count and a maximum. Autoscaling has a per-block addition latency on the order of a few seconds, which is acceptable for ad hoc analyst load but noticeable for sub-second dashboards.

    Dedicated baseline slots remove this cold-add latency for interactive workloads. The exam pattern is to put the interactive BI workload on a reservation with a non-zero baseline and the batch ETL workload on an autoscaling reservation that runs at zero baseline overnight.

    ⚠️ Anti-Pattern: Adding SELECT * to dashboard queries because LookML or the BI tool generates it. SELECT * negates clustering pruning and inflates Storage Read API bandwidth. Restrict the LookML view to the columns the report actually surfaces, and rely on the BI Engine column filter to keep the in-memory representation narrow.

    💡 Exam Trap: "Cache hit" jobs in BigQuery (where cache_hit = TRUE) are free and return in milliseconds, but the cache is per-user and per-exact-query-text. A Looker dashboard rendered for ten users issues ten distinct query texts (because Looker stamps a query label per user), so the per-user cache never warms across the team. The correct accelerator for cross-user repetition is the materialized view, not the result cache.

    Security, data masking, Identity and Access Management (IAM), and Cloud Data Loss Prevention (Cloud DLP)

    The visualization layer is the surface where the warehouse meets the broadest population of users, which makes it the most aggressive test of the security model. The exam tests four mechanisms in this area:

    • IAM at table and column scope
    • policy tags with dynamic data masking
    • row-level access policies
    • Cloud DLP for sensitive-data discovery and de-identification before publication

    IAM at the table level uses the BigQuery predefined roles (roles/bigquery.dataViewer, roles/bigquery.dataEditor, roles/bigquery.user, roles/bigquery.jobUser) plus dataset-scoped grants and table-scoped grants.

    Authorized views and authorized datasets are the indirection layer: a consumer is granted access to a view in dataset A, the view reads from a table in dataset B, and dataset B authorizes dataset A to read on the consumer's behalf without granting the consumer direct access to dataset B.

    Authorized routines extend the same pattern to user-defined functions and stored procedures.

    Column-level security operates through policy tags managed in Dataplex Catalog. A policy tag taxonomy defines a hierarchy of sensitivity levels (for instance, confidential > restricted > public). Each tag carries IAM grants for the roles/datacatalog.categoryFineGrainedReader role. A BigQuery table column annotated with a policy tag returns NULL (with the policy_tags.maskingRule = "default" option) or raises an error to any principal lacking the fine-grained reader role on that tag, depending on the masking rule configured for the tag.

    Dynamic data masking applies a masking rule to a policy-tagged column instead of denying access entirely. The masking rule options include: DEFAULT_MASKING_VALUE (returns the type's default null-like value) HASH (returns a SHA-256 hash of the value) EMAIL_MASK (preserves the domain and masks the local part) LAST_FOUR_CHARACTERS FIRST_FOUR_CHARACTERS

    A masked principal receives transformed values without an error, which is the right shape for analytics on a column where the analyst needs the data to exist (for join key uniqueness) but does not need the cleartext value.

    ALTER TABLE marketing_prod.customer_curated.customer_dim
    ALTER COLUMN email
    SET OPTIONS (
     description = "Customer email; masked for non-PII reader role"
    );
    
    ALTER TABLE marketing_prod.customer_curated.customer_dim
    ALTER COLUMN email
    SET DATA POLICY ("projects/marketing-prod/locations/us/dataPolicies/mask_email_default");
    

    Row-level access policies filter rows visible to a principal based on a SQL predicate. A row access policy is defined with CREATE ROW ACCESS POLICY and applies to one table. The predicate can reference SESSION_USER() or a join against an IAM-controlled lookup table. Row access policies compose with column-level masking: a viewer might see only the rows for their region and, within those rows, see masked customer emails.

    CREATE OR REPLACE ROW ACCESS POLICY emea_only
    ON marketing_prod.sales_curated.order_facts
    GRANT TO ("group:emea-analysts@example.com")
    FILTER USING (region IN ("UK", "DE", "FR", "ES", "IT", "NL"));
    
    CREATE OR REPLACE ROW ACCESS POLICY north_america_only
    ON marketing_prod.sales_curated.order_facts
    GRANT TO ("group:na-analysts@example.com")
    FILTER USING (region IN ("US", "CA", "MX"));
    

    Cloud DLP (now branded as Sensitive Data Protection) operates on the discovery and de-identification side.

    A DLP inspection job scans a BigQuery table or a Cloud Storage bucket for infoTypes (built-in detectors such as EMAIL_ADDRESS, CREDIT_CARD_NUMBER, US_SOCIAL_SECURITY_NUMBER, plus stored or regex custom detectors), produces findings, and writes them to a BigQuery findings table or to Security Command Center.

    The findings drive policy tag application: a Dataplex automated discovery scan plus DLP results can suggest which columns should carry a restricted policy tag.

    DLP de-identification operates in two patterns relevant to visualization.

    • The inline pattern runs a DLP de-identification template inside a Dataflow pipeline that writes a redacted copy of the source data into a presentation dataset.
    • The presentation dataset becomes the only surface the dashboard touches, and the raw dataset stays behind a more restrictive IAM perimeter.
    • The in-place pattern uses BigQuery remote functions that call DLP de-identification at query time, which is suited to ad hoc tools but adds latency unsuitable for dashboards.
    from google.cloud import dlp_v2
    
    dlp = dlp_v2.DlpServiceClient()
    parent = "projects/marketing-prod/locations/us"
    
    inspect_config = {
     "info_types": [
     {"name": "EMAIL_ADDRESS"},
     {"name": "PHONE_NUMBER"},
     {"name": "CREDIT_CARD_NUMBER"},
     {"name": "US_SOCIAL_SECURITY_NUMBER"},
     ],
     "min_likelihood": dlp_v2.Likelihood.LIKELY,
     "include_quote": False,
    }
    
    storage_config = {
     "big_query_options": {
     "table_reference": {
     "project_id": "marketing-prod",
     "dataset_id": "sales_raw",
     "table_id": "support_tickets",
     }
     }
    }
    
    actions = [
     {
     "save_findings": {
     "output_config": {
     "table": {
     "project_id": "marketing-prod",
     "dataset_id": "dlp_findings",
     "table_id": "support_tickets_findings",
     }
     }
     }
     }
    ]
    
    job = dlp.create_dlp_job(
     request={
     "parent": parent,
     "inspect_job": {
     "inspect_config": inspect_config,
     "storage_config": storage_config,
     "actions": actions,
     },
     }
    )
    

    Decision Anchor: Choosing the Visualization Acceleration Surface

    When to use

    Choose a materialized view when the dashboard query is an aggregation over a single base table, the optimizer can rewrite, and the freshness budget is in the tens of minutes.

    Choose BI Engine when the working set fits in 1 to 250 GB and the latency budget is sub-second.

    Choose a Dataform-managed presentation table when the query joins multiple base tables, uses window functions or non-deterministic UDFs, or needs to be consumed by a BI tool other than the one that authored it.

    Choose Looker aggregate awareness when the precomputed shape is BI-tool-specific and varies with the user's chosen grain.

    Decision Tree: Choosing the precalculation surface for a Looker dashboard

    💡 Exam Trap: Cloud DLP de-identification through a query-time remote function adds 50 ms to 200 ms per row of round-trip latency. A dashboard tile that touches 100,000 rows turns into a multi-second render. The exam-correct pattern for high-volume redaction is a Dataflow pipeline that writes a de-identified table once, then the dashboard reads the de-identified table.

    ⚠️ Anti-Pattern: Granting roles/bigquery.dataViewer on the source dataset to a Looker service account so the dashboard "just works". The viewer role bypasses authorized views and authorized datasets. The exam-correct pattern is to grant the service account access to a curated dataset that contains only authorized views, and to leave the source dataset accessible only to platform principals.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the GCP - Professional Data Engineer learning hub.