DE SQL Hiring Questions | 106
DE SQL Hiring Questions | 106
Q: I have a table with customer ID, session ID, and session date. Another table has transaction date and customer ID. I want to know the days between the session date and the next transaction, previous transaction, and closest transaction.
* A customer can have multiple transactions before and after session.
This problem requires calculating time differences between session dates and transaction dates for each customer. Here's a SQL solution:
SQL Solution:
WITH NextTransactionDates AS (
SELECT
customer_id,
session_date,
transaction_date AS next_transaction_date, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY transaction_date) as rn_next,
DATE_DIFF('day', session_date, transaction_date) AS days_to_next_transaction
FROM sessions s JOIN transactions t ON s.customer_id = t.customer_id WHERE session_date <= transaction_date QUALIFY rn_next = 1),
PreviousTransactionDates AS (
SELECT
customer_id,
session_date,
transaction_date AS prev_transaction_date, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY transaction_date DESC) as rn_prev
DATE_DIFF('day', session_date, transaction_date) AS days_to_prev_transaction
FROM sessions s JOIN transactions t ON s.customer_id = t.customer_id
WHERE session_date > transaction_date QUALIFY rn_prev = 1),
ClosestTransactionDates AS (
SELECT
s.session_id,
s.session_date,
LEAST(days_to_next_transaction,days_to_prev_transaction) AS days_to_closest_transaction,#Check for null values according to the data. but logic will remain same.
FROM sessions s
JOIN NextTransactionDates n on s.session_id=n.session_idJOIN PreviousTransactionDates p on s.session_id=p.session_id
)
SELECT
* from ClosestTransactionDates
Transferring Files from GCS to BigQuery
Question: You want to load files present in GCS based on filenames into BigQuery and archive those files. What approach will you choose?
Answer:
Transferring files from Google Cloud Storage (GCS) to BigQuery, based on filenames, and then archiving them, involves a coordinated process. Here's a detailed approach that leverages BigQuery and GCS, managed by a workflow orchestration tool:
1. File Storage in GCS:
- Google Cloud Storage (GCS): Store your files in GCS. GCS offers scalability, high durability, and cost-effectiveness for storing large datasets.
- Structured Filenames: Employ a consistent naming convention for your files. This is essential for efficient data loading and processing. Consider including elements like:
- Date (e.g., YYYYMMDD)
- Source System
- File Type/Format (e.g., CSV, JSON)
- Sequence Number (if the files are part of a larger batch)
For example: source_system_data_20240728_001.csv
- Organized Structure: Arrange files within GCS buckets using a logical directory structure (e.g., by source system, date). This improves organization and simplifies management.
- Date (e.g., YYYYMMDD)
- Source System
- File Type/Format (e.g., CSV, JSON)
- Sequence Number (if the files are part of a larger batch)
For example: source_system_data_20240728_001.csv
2. BigQuery Data Loading:
- External Tables (For Staging):
- Create a BigQuery external table that references the data in GCS. This enables you to query the data in GCS without ingesting it into BigQuery storage.
- Use a wildcard in the external table definition to match multiple files based on the filename pattern. For instance, with files named
data_YYYYMMDD.csv, use a wildcard such as gs://your_bucket/data_*.csv. - External tables are beneficial for:
- Previewing the data and schema before loading.
- Transforming the data before loading it into BigQuery.
- Querying data that is infrequently updated in GCS.
- Loading into BigQuery Managed Tables:
- Create a BigQuery managed table to store the data. Managed tables provide optimal performance for BigQuery queries.
- Use a BigQuery load job to transfer data from GCS (either directly or from the external table) into the managed table.
- Loading Options: Data can be loaded using:
- The BigQuery API.
- The
bq command-line tool. - Client libraries (e.g., Python, Java).
- LOAD DATA BQ Query
- Data Format Selection: BigQuery supports various data formats, including CSV, JSON, Parquet, and Avro. Select the format that best suits your data. Parquet and Avro generally offer superior performance and cost efficiency.
- Table Optimization: Improve BigQuery table performance by:
- Partitioning: Dividing the table into smaller segments based on a column (e.g., date). This reduces the amount of data scanned by queries.
- Clustering: Organizing the data within each partition based on one or more columns. This further enhances query performance.
- Create a BigQuery external table that references the data in GCS. This enables you to query the data in GCS without ingesting it into BigQuery storage.
- Use a wildcard in the external table definition to match multiple files based on the filename pattern. For instance, with files named
data_YYYYMMDD.csv, use a wildcard such asgs://your_bucket/data_*.csv. - External tables are beneficial for:
- Previewing the data and schema before loading.
- Transforming the data before loading it into BigQuery.
- Querying data that is infrequently updated in GCS.
- Create a BigQuery managed table to store the data. Managed tables provide optimal performance for BigQuery queries.
- Use a BigQuery load job to transfer data from GCS (either directly or from the external table) into the managed table.
- Loading Options: Data can be loaded using:
- The BigQuery API.
- The
bqcommand-line tool. - Client libraries (e.g., Python, Java).
- LOAD DATA BQ Query
- Data Format Selection: BigQuery supports various data formats, including CSV, JSON, Parquet, and Avro. Select the format that best suits your data. Parquet and Avro generally offer superior performance and cost efficiency.
- Table Optimization: Improve BigQuery table performance by:
- Partitioning: Dividing the table into smaller segments based on a column (e.g., date). This reduces the amount of data scanned by queries.
- Clustering: Organizing the data within each partition based on one or more columns. This further enhances query performance.
3. Workflow Orchestration:
- Workflow Tool: Employ a workflow orchestration tool to automate and manage the data loading and archiving process. Common choices include:
- Apache Airflow (on Cloud Composer): A robust and flexible open-source workflow management platform. Cloud Composer is Google Cloud's managed Airflow service.
- Cloud Functions: Serverless functions triggered by events (e.g., file creation in GCS) or schedules. Suitable for simpler workflows.
- Cloud Scheduler
- Workflow Sequence: The workflow should consist of these steps:
- File Detection: Monitor the GCS bucket for new files that match the specified filename pattern.
- BigQuery Load Initiation: Trigger a BigQuery load job to load the data into the managed table.
- Error Handling: Implement robust error handling, including retries for failed load jobs and notifications for critical errors.
- Data Validation: (Optional) Perform data validation checks post-loading to ensure data quality.
- File Archiving: Upon successful data loading into BigQuery:
- Move the files from the source GCS location to an archive location in GCS.
- Use the
gsutil mv command for this. - cloud scheduler
- storage transfer job
- Logging: Record all workflow steps, including file processing status, load job details, errors, and archiving actions. Utilize Cloud Logging for centralized logging.
- Notifications: Send alerts (e.g., email, Slack) for workflow success or failure.
- Apache Airflow (on Cloud Composer): A robust and flexible open-source workflow management platform. Cloud Composer is Google Cloud's managed Airflow service.
- Cloud Functions: Serverless functions triggered by events (e.g., file creation in GCS) or schedules. Suitable for simpler workflows.
- Cloud Scheduler
- File Detection: Monitor the GCS bucket for new files that match the specified filename pattern.
- BigQuery Load Initiation: Trigger a BigQuery load job to load the data into the managed table.
- Error Handling: Implement robust error handling, including retries for failed load jobs and notifications for critical errors.
- Data Validation: (Optional) Perform data validation checks post-loading to ensure data quality.
- File Archiving: Upon successful data loading into BigQuery:
- Move the files from the source GCS location to an archive location in GCS.
- Use the
gsutil mvcommand for this. - cloud scheduler
- storage transfer job
- Logging: Record all workflow steps, including file processing status, load job details, errors, and archiving actions. Utilize Cloud Logging for centralized logging.
- Notifications: Send alerts (e.g., email, Slack) for workflow success or failure.
4. File Archiving:
- GCS Archive Location: Store archived files in a separate GCS bucket or a distinct directory within the same bucket.
- Cost-Effective Storage: Choose a GCS storage class optimized for long-term archival (e.g., Archive or Coldline) to minimize storage costs.
- Data Protection: (Optional but Recommended) Enable GCS object versioning in the archive location. This adds a layer of data protection by preserving all versions of your archived files.
- Storage Management: (Optional) Use GCS lifecycle management policies to automatically delete or move archived files after a defined period.
5. BigQuery Utilization:
- Querying: Analyze and report on the data in the BigQuery managed table.
Key Considerations:
- Idempotency: Design the workflow to be idempotent. This ensures that retried steps (e.g., after a failure) do not lead to duplicate data or other inconsistencies.
- Reliability: Implement thorough error handling and retries to guarantee reliable data loading.
- Optimization: Optimize data loading and querying for performance. Use appropriate file formats, partitioning, and clustering techniques.
- Cost Management: Control expenses by selecting suitable GCS storage classes, partitioning BigQuery tables, and writing efficient queries.
- Security: Ensure proper security and access control for both GCS and BigQuery resources.
Q: How will you count the number of vowels in a string?
Write a SQL query to count the number of vowels (a, e, i, o, u) in a given string.
SQL Solution:
SELECT
LENGTH(input_string) - LENGTH(REGEXP_REPLACE(LOWER(input_string), '[aeiou]', '')) AS vowel_count
FROM
(SELECT 'Hello, World!' AS input_string) AS t; -- Replace 'Hello, World!' with your string
Q: Suppose I have customers with multiple products in multiple rows. I want to have one row per customer. How can we do that? Is it possible to make it in one column?
This problem involves aggregating data to transform multiple rows per customer into a single row. Here's a SQL solution:
SQL Solution:
SELECT
customer_id,
STRING_AGG(product_id, ', ') AS all_product_ids -- Aggregates product IDs into a comma-separated string# The function ca be different based n SQL tool for example some SQL tools follow group_concat()
FROM
customer_products
GROUP BY
customer_id;
Comments
Post a Comment