Snowflake Advanced ยท Interview Prep
ETL/ELT Patterns & Transformations
Difficulty: Medium-Hard ยท Commonly asked at Amazon, Apple, Netflix
Interview Question
"Compare ETL vs ELT approaches in Snowflake. When would you choose one over the other? Walk me through implementing a slowly changing dimension (SCD Type 2) using Snowflake's native features."
โน๏ธ
Companies Asking This: Amazon (L6 Data Engineer), Apple (Senior Data Engineer), Netflix (Staff Data Engineer), Meta (Data Platform Engineer)
ETL vs ELT
When to Use Each
-- ELT: Transform in Snowflake (recommended for most cases)
-- Step 1: Load raw data into staging
COPY INTO staging.raw_orders
FROM @s3_stage/orders/
FILE_FORMAT = (TYPE = 'PARQUET');
-- Step 2: Transform in Snowflake using SQL
CREATE TABLE prod.orders_transformed AS
SELECT
order_id,
customer_id,
order_date,
total_amount,
status,
-- Data quality transformations
TRIM(UPPER(status)) AS status_cleaned,
COALESCE(discount, 0) AS discount_amount,
total_amount - COALESCE(discount, 0) AS net_amount,
-- Derived columns
DATEDIFF('day', order_date, CURRENT_DATE()) AS days_since_order,
CASE
WHEN total_amount > 1000 THEN 'HIGH_VALUE'
WHEN total_amount > 100 THEN 'MEDIUM_VALUE'
ELSE 'LOW_VALUE'
END AS value_tier,
-- Timestamp
CURRENT_TIMESTAMP() AS transformed_at
FROM staging.raw_orders
WHERE order_date >= DATEADD(year, -1, CURRENT_DATE());
-- ETL: Transform outside Snowflake (use for complex transformations)
-- Example: Using dbt, Spark, or other tools
-- These tools connect to Snowflake, extract data, transform externally,
-- and load back
ELT is the default for most Snowflake workloads because the transform step runs on the same
compute cluster that loaded the data. There is no separate ETL server to provision, no
per-row vendor license, and no network hop between load and transform. A nightly batch that
stages 500 GB of Parquet and rebuilds a star schema completes inside one session: the
COPY INTO is I/O bound, the transform CREATE TABLE AS is a single full scan, and both
bill against the same warehouse.
ETL still earns its place in three situations. First, when a transform must run before data
reaches a shared system โ PII tokenization cannot safely happen inside a database that
hundreds of roles can query. Second, when the workload is not SQL-shaped: graph traversal
for fraud rings, a GPU scoring step, or an embedded model that needs a runtime Snowflake
does not ship. Third, when the source system is the bottleneck rather than the target,
because pushing row filtering into the extraction tool protects an OLTP database from a
full-table scan at 2 p.m. Teams that need all three usually end up hybrid: bulk load with
COPY INTO, one external step for the odd workload, SQL for everything else.
Decision Matrix: When Each Pattern Wins
| Signal in the workload | Pick | Why |
|---|---|---|
| Under 100 GB per day, set-based logic | ELT | One system to monitor, no egress billing |
| Transform needs a graph or GPU engine | ETL | Snowflake SQL cannot express the operation |
| Source is an OLTP database under load | ETL | Filter before extraction, protect production |
| Sub-5-minute latency from a CDC stream | ELT with Streams | Change rows land in seconds, transform is a merge |
| Heavy PII with strict pre-load rules | ETL | Tokenize outside a broadly queryable store |
| Analysts own the transformation logic | ELT | SQL is the skill the team already has |
The middle rows are where interviewers push. Ask what happens when the transform is wrong: with ELT you re-run the SQL against staged data and the fix ships in minutes, while with ETL you must re-extract from the source, which may no longer hold the original values. That reversibility argument is the strongest practical case for staging raw data in its original form and deferring every lossy decision until the last possible moment.
SCD Type 2 Implementation
-- 1. Create target SCD table
CREATE TABLE prod.customers_scd (
customer_key NUMBER AUTOINCREMENT,
customer_id VARCHAR(100),
customer_name VARCHAR(200),
email VARCHAR(200),
segment VARCHAR(50),
effective_start_date TIMESTAMP_NTZ,
effective_end_date TIMESTAMP_NTZ DEFAULT TO_TIMESTAMP_NTZ('9999-12-31'),
is_current BOOLEAN DEFAULT TRUE,
_ingestion_time TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),
_source_system VARCHAR(50)
);
-- 2. Create staging table for new/changed records
CREATE TABLE staging.customer_changes (
customer_id VARCHAR(100),
customer_name VARCHAR(200),
email VARCHAR(200),
segment VARCHAR(50),
_change_type VARCHAR(10), -- INSERT, UPDATE, DELETE
_change_timestamp TIMESTAMP_NTZ
);
-- 3. SCD Type 2 merge procedure
CREATE OR REPLACE PROCEDURE merge_scd_type2()
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
merge_count NUMBER DEFAULT 0;
insert_count NUMBER DEFAULT 0;
BEGIN
-- Close existing records for changed customers
MERGE INTO prod.customers_scd t
USING staging.customer_changes s
ON t.customer_id = s.customer_id
AND t.is_current = TRUE
AND s._change_type = 'UPDATE'
WHEN MATCHED AND (
t.customer_name != s.customer_name OR
t.email != s.email OR
t.segment != s.segment
) THEN
UPDATE SET
effective_end_date = s._change_timestamp,
is_current = FALSE;
merge_count := SQLROWCOUNT;
-- Insert new current records
INSERT INTO prod.customers_scd (
customer_id, customer_name, email, segment,
effective_start_date, is_current, _source_system
)
SELECT
s.customer_id,
s.customer_name,
s.email,
s.segment,
s._change_timestamp,
TRUE,
'SOURCE_SYSTEM'
FROM staging.customer_changes s
WHERE s._change_type IN ('INSERT', 'UPDATE')
AND NOT EXISTS (
SELECT 1 FROM prod.customers_scd t
WHERE t.customer_id = s.customer_id
AND t.is_current = TRUE
AND t.customer_name = s.customer_name
AND t.email = s.email
AND t.segment = s.segment
);
insert_count := SQLROWCOUNT;
-- Handle soft deletes
UPDATE prod.customers_scd
SET is_current = FALSE,
effective_end_date = CURRENT_TIMESTAMP()
WHERE customer_id IN (
SELECT customer_id FROM staging.customer_changes
WHERE _change_type = 'DELETE'
)
AND is_current = TRUE;
RETURN 'SCD2 merge complete. Closed: ' || merge_count ||
', Inserted: ' || insert_count;
END;
$$;
Three details in that procedure decide whether it survives a production week. The
effective_end_date default of 9999-12-31 gives you a sentinel that survives NULL-comparison
bugs: WHERE effective_end_date = '9999-12-31' is a fast, index-friendly test for the current
row, whereas WHERE effective_end_date IS NULL breaks the moment a source feed delivers a real
NULL. The NOT EXISTS guard in the insert branch is what makes the job idempotent โ re-running
the merge after a partial failure does not create a second current row for the same customer,
because the guard confirms no identical current version already exists. Keep the compared
column list in that guard byte-for-byte aligned with the change detection logic above it; a
mismatch means a silent double insert that only surfaces months later as a fan-out join.
Querying an SCD2 table correctly matters just as much as writing it. Business questions ask for the version that was current at a point in time, not the row that is current now:
-- Version of each customer as of a reporting date
SELECT
customer_id,
customer_name,
segment,
effective_start_date,
effective_end_date
FROM prod.customers_scd
WHERE effective_start_date <= '2024-06-30'
AND effective_end_date > '2024-06-30'
ORDER BY customer_id;
Because the change detection and the merge run in separate statements, two merges firing
concurrently on the same customer can interleave. Serialize the procedure with a Snowflake
task that has no overlap, or wrap it in a lock using a single-row control table. Finally,
budget for table growth: an SCD2 table with 2 million customers and 6 changes per customer
per year holds roughly 12 million rows after a year, so cluster on customer_id and
effective_start_date to keep the current-row lookup pruning instead of scanning.
Incremental Loads with Streams and Tasks
A full reload of a 40-billion-row fact table is not a strategy, it is an outage waiting for
a calendar slot. Streams give you change data capture directly on the table: they record
inserts, updates and deletes in a persisted offset, and consuming that offset in a MERGE
advances it atomically. Pair the stream with a task and the pipeline runs on a schedule
without an external orchestrator.
CREATE OR REPLACE STREAM orders_cdc
ON TABLE prod.orders
APPEND_ONLY = FALSE
SHOW_INITIAL_ROWS = TRUE;
CREATE OR REPLACE TASK hourly_order_rollup
WAREHOUSE = analytics_wh
SCHEDULE = 'USING CRON 0 * * * * UTC'
WHEN SYSTEM$STREAM_HAS_DATA('orders_cdc')
AS
MERGE INTO prod.orders_daily_summary t
USING (
SELECT
TO_DATE(order_date) AS day,
COUNT(*) AS order_count,
SUM(net_amount) AS revenue
FROM orders_cdc
WHERE METADATA$ACTION IN ('INSERT', 'UPDATE')
GROUP BY 1
) s
ON t.day = s.day
WHEN MATCHED THEN UPDATE SET
t.order_count = s.order_count,
t.revenue = s.revenue
WHEN NOT MATCHED THEN INSERT (day, order_count, revenue)
VALUES (s.day, s.order_count, s.revenue);
Two behaviors catch teams out. A stream expires if nothing consumes it โ Snowflake keeps roughly 24 hours of offset for a standard stream, after which the stream reports as stale and must be refreshed. And a task that fails part-way does not roll back the stream offset for rows it already consumed, so the merge itself has to be idempotent. Rebuild the summary from the group-by rather than applying a delta, and a replay costs you a few seconds instead of a weekend of reconciliation.
Late Arrivals, Duplicates, and Idempotent Re-runs
Sources rarely deliver a clean, ordered feed. Mobile clients replay events after a network
drop, CDC tools emit the same row twice when a transaction straddles a batch boundary, and
backfills arrive days after the fact with timestamps in the past. Three rules cover most of
this. Deduplicate on a source-provided event key with QUALIFY ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY _ingestion_time DESC) = 1, so replay becomes a no-op instead of a
double count. Route late events into the partition they belong to rather than the partition
they arrived in, and accept that a downstream daily aggregate will need re-running. Design
every load statement so that running it twice leaves the same state as running it once โ
either it overwrites its target slice or it merges on a natural key.
The practical test is simple: kill the pipeline halfway through, run it again, and compare row counts against the source. If the numbers move, the job is not idempotent and no amount of retry logic upstream will save it.
Real-World Scenario: Amazon
Question: "Design a data pipeline that ingests data from multiple sources (APIs, databases, files), applies data quality rules, and loads into a star schema."
Solution: Multi-Source Pipeline
-- 1. Create raw ingestion layer
CREATE SCHEMA raw;
CREATE SCHEMA staging;
CREATE SCHEMA prod;
-- 2. Raw tables for each source
CREATE TABLE raw.api_orders (
payload VARIANT,
_source VARCHAR(50),
_ingestion_time TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);
CREATE TABLE raw.db_inventory (
payload VARIANT,
_source VARCHAR(50),
_ingestion_time TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);
-- 3. Data quality UDFs
CREATE OR REPLACE FUNCTION validate_order(order_data VARIANT)
RETURNS BOOLEAN
LANGUAGE SQL
AS
'order_data:order_id::VARCHAR IS NOT NULL
AND order_data:amount::NUMBER > 0
AND order_data:order_date::DATE IS NOT NULL';
-- 4. Staging with quality checks
CREATE TABLE staging.orders_staged AS
SELECT
payload:order_id::VARCHAR AS order_id,
payload:customer_id::VARCHAR AS customer_id,
payload:order_date::DATE AS order_date,
payload:amount::NUMBER AS amount,
payload:status::VARCHAR AS status,
validate_order(payload) AS is_valid,
CASE
WHEN NOT validate_order(payload) THEN 'INVALID_DATA'
ELSE 'VALID'
END AS quality_flag,
_source,
_ingestion_time
FROM raw.api_orders;
-- 5. Quality check procedure
CREATE OR REPLACE PROCEDURE run_quality_checks()
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
invalid_count NUMBER;
total_count NUMBER;
BEGIN
SELECT COUNT(*) INTO invalid_count
FROM staging.orders_staged
WHERE quality_flag = 'INVALID_DATA';
SELECT COUNT(*) INTO total_count
FROM staging.orders_staged;
IF invalid_count > total_count * 0.1 THEN
RETURN 'ERROR: ' || invalid_count || ' invalid records (' ||
ROUND(invalid_count * 100.0 / total_count, 2) || '%). Pipeline halted.';
ELSE
RETURN 'Quality check passed. Invalid: ' || invalid_count ||
' (' || ROUND(invalid_count * 100.0 / total_count, 2) || '%)';
END IF;
END;
$$;
-- 6. Star schema loading
-- Fact table
INSERT INTO prod.fact_orders
SELECT
s.order_id,
s.customer_id,
s.order_date,
s.amount,
s.status,
d.date_key,
c.customer_key
FROM staging.orders_staged s
JOIN prod.dim_date d ON s.order_date = d.full_date
JOIN prod.dim_customer c ON s.customer_id = c.customer_id
WHERE s.quality_flag = 'VALID';
Best Practices
| Practice | Recommendation |
|---|---|
| ELT over ETL | Use Snowflake's compute for transformations |
| Staging layer | Always stage raw data before transformation |
| Data quality | Implement quality checks in staging |
| Incremental loads | Use Streams for change detection |
| Idempotency | Design pipelines to be re-runnable |
| Documentation | Document transformation logic |
โ ๏ธ
Common Pitfalls:
- Loading directly to prod โ Always use staging layer
- No error handling โ Implement TRY/CATCH and rollback
- Full reloads โ Use incremental loads for large tables
- No data quality checks โ Validate before loading to prod
- Ignoring dependencies โ Schedule tasks based on dependencies
Key Takeaways
- ELT keeps transformation inside Snowflake so one warehouse bills for both load and transform, while ETL wins when the step must run before data touches a shared store or needs a non-SQL engine.
- Stage raw data in its original form first: a wrong transformation can then be re-run in minutes instead of re-extracted from a source that has already overwritten the values.
- SCD Type 2 needs a sentinel end date, an idempotent NOT EXISTS guard, and a merge serialized through a single task so two runs cannot both insert a current row.
- Streams and tasks give in-database change capture, but a stale stream expires after about a day and the consuming merge must be idempotent because offsets do not roll back.