Snowflake Advanced ยท Interview Prep
CI/CD & Code Promotion
Difficulty: Medium-Hard ยท Commonly asked at Microsoft, Google, Amazon
Interview Question
"How do you implement a CI/CD pipeline for Snowflake schema changes? Walk me through the process of promoting code from dev to staging to production."
โน๏ธ
Companies Asking This: Microsoft (Principal Data Engineer), Google (Senior Cloud Engineer), Amazon (L6 Data Engineer), Meta (Data Platform Engineer)
CI/CD Architecture
Snowflake CLI (snowsql) & Code Management
# Install SnowSQL
pip install snowflake-cli
# Connect to Snowflake
snowsql -a my_account -u my_user -r my_role
# List databases
snowsql -q "SHOW DATABASES"
# Execute SQL file
snowsql -f scripts/create_tables.sql
# Execute with variables
snowsql -q "CREATE DATABASE {{database_name}}" -D database_name=my_db
Schema-as-Code Pattern
-- Example: create_orders.sql
CREATE TABLE IF NOT EXISTS orders (
order_id VARCHAR(100) PRIMARY KEY,
customer_id VARCHAR(100),
order_date TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),
amount NUMBER(12,2),
status VARCHAR(20),
_ingestion_time TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Example: create_orders_view.sql
CREATE OR REPLACE VIEW orders_view AS
SELECT
order_id,
customer_id,
order_date,
amount,
status
FROM orders
WHERE order_date >= DATEADD(year, -1, CURRENT_DATE());
Real-World Scenario: Microsoft
Question: "How do you handle schema migrations in a CI/CD pipeline? What happens when a migration fails in production?"
Solution: Migration Pipeline
-- 1. Create migration tracking table
CREATE TABLE schema_migrations (
migration_id NUMBER AUTOINCREMENT,
version VARCHAR(50) PRIMARY KEY,
description VARCHAR(500),
executed_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),
executed_by VARCHAR(100),
execution_time_ms NUMBER,
status VARCHAR(20) DEFAULT 'SUCCESS',
rollback_script VARCHAR(2000)
);
-- 2. Create migration script example
-- V001__create_orders_table.sql
CREATE TABLE IF NOT EXISTS orders (
order_id VARCHAR(100) PRIMARY KEY,
customer_id VARCHAR(100),
order_date TIMESTAMP_NTZ,
amount NUMBER(12,2),
status VARCHAR(20)
);
-- Insert migration record
INSERT INTO schema_migrations (version, description, rollback_script)
VALUES (
'V001',
'Create orders table',
'DROP TABLE IF EXISTS orders;'
);
-- 3. Migration runner procedure
CREATE OR REPLACE PROCEDURE run_migration(
migration_version VARCHAR,
migration_sql VARCHAR,
rollback_sql VARCHAR
)
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
start_time TIMESTAMP_NTZ;
execution_time NUMBER;
BEGIN
-- Check if migration already applied
IF EXISTS (
SELECT 1 FROM schema_migrations
WHERE version = :migration_version AND status = 'SUCCESS'
) THEN
RETURN 'Migration ' || :migration_version || ' already applied';
END IF;
start_time := CURRENT_TIMESTAMP();
-- Execute migration
EXECUTE IMMEDIATE :migration_sql;
execution_time := TIMESTAMPDIFF('millisecond', start_time, CURRENT_TIMESTAMP());
-- Record success
INSERT INTO schema_migrations (version, description, execution_time_ms, rollback_script)
VALUES (
:migration_version,
'Migration ' || :migration_version,
:execution_time,
:rollback_sql
);
RETURN 'Migration ' || :migration_version || ' applied successfully (' ||
:execution_time || 'ms)';
EXCEPTION
WHEN OTHER THEN
-- Record failure
INSERT INTO schema_migrations (version, description, status, rollback_script)
VALUES (
:migration_version,
'Migration ' || :migration_version || ' - FAILED',
'FAILED',
:rollback_sql
);
RETURN 'Migration ' || :migration_version || ' FAILED: ' || SQLERRM;
END;
$$;
-- 4. Rollback procedure
CREATE OR REPLACE PROCEDURE rollback_migration(migration_version VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
rollback_sql VARCHAR;
BEGIN
SELECT rollback_sql INTO rollback_sql
FROM schema_migrations
WHERE version = :migration_version AND status = 'SUCCESS';
IF (rollback_sql IS NULL) THEN
RETURN 'No rollback script found for migration ' || :migration_version;
END IF;
EXECUTE IMMEDIATE :rollback_sql;
UPDATE schema_migrations
SET status = 'ROLLED_BACK'
WHERE version = :migration_version;
RETURN 'Migration ' || :migration_version || ' rolled back successfully';
END;
$$;
GitHub Actions CI/CD Pipeline
# .github/workflows/snowflake-deploy.yml
name: Snowflake CI/CD
on:
push:
branches: [main, staging]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install SnowSQL
run: |
curl -O https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/snowsql-1.2.21-linux_x86_64.bash
sudo bash snowsql-1.2.21-linux_x86_64.bash
- name: Run Tests
env:
SNOWFLAKE_ACCOUNT: ${{ secrets.SNOWFLAKE_ACCOUNT }}
SNOWFLAKE_USER: ${{ secrets.SNOWFLAKE_USER }}
SNOWFLAKE_PASSWORD: ${{ secrets.SNOWFLAKE_PASSWORD }}
run: |
snowsql -f scripts/test_queries.sql
deploy-staging:
needs: test
if: github.ref == 'refs/heads/staging'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy to Staging
env:
SNOWFLAKE_ACCOUNT: ${{ secrets.SNOWFLAKE_ACCOUNT_STAGING }}
run: |
for f in scripts/migrations/*.sql; do
snowsql -f "$f"
done
deploy-prod:
needs: deploy-staging
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy to Production
env:
SNOWFLAKE_ACCOUNT: ${{ secrets.SNOWFLAKE_ACCOUNT_PROD }}
run: |
for f in scripts/migrations/*.sql; do
snowsql -f "$f"
done
Branch Strategy and Promotion Gates
Every promotion pipeline needs one rule that nobody can override with a hotfix: the artifact that reached staging is byte-identical to the artifact that reaches production. If a team edits SQL by hand in the production worksheet, the pipeline becomes documentation rather than control, and the next incident investigation starts from a guess. Enforce it by having CI render the final SQL from templates and checksum it, then comparing that checksum after each deployment stage.
A three-branch model covers most teams. dev accepts anything that compiles; merges into
staging require the migration suite plus a seed-data reconciliation job; merges into main
require a signed approval and a green staging soak of at least one full business cycle โ a
daily aggregate must have run once before you promote the DDL that feeds it. The gate that
catches the most real bugs is the soak, not the unit tests, because most Snowflake failures
are timing and scheduling problems rather than syntax problems.
| Gate | Blocks merge into staging | Blocks promotion to production |
|---|---|---|
| SQL parses and lints | Yes | Yes |
| Migration up and down on clean database | Yes | Yes |
| Row-count reconciliation on seed data | Yes | Yes |
| Query plan regression check | No | Yes |
| Full business cycle soak | No | Yes |
| Named human approval | No | Yes |
Keep the number of gates small enough that engineers still run them locally. A suite that takes forty minutes will be bypassed within a month, and a bypassed gate gives the same false confidence as no gate at all.
Configuration travels with the code or it does not travel at all. Put warehouse names, schema names, and schedule expressions in a per-environment config file rendered into the SQL at build time, and keep credentials exclusively in the CI secret store โ a pipeline that reads connection details from a worksheet on someone's laptop has an availability problem and a security problem at the same time. The practical test is whether a new engineer can reproduce a production deploy from a clean checkout plus the secret store, with no other knowledge. Anything that fails that test is tribal process wearing a pipeline's name.
What a Migration Test Actually Asserts
Testing DDL is different from testing application code: there is no stack trace when a column
lands with the wrong precision. The cheapest high-value assertion is round-trip verification
โ apply the migration, insert a known fixture, read it back, and compare against the expected
representation. Second is reversibility: run the rollback script and assert the object list
matches the state captured before the migration ran. Third is blast radius: query
account_usage.query_history for the objects the migration touched and assert that no other
object in the account changed definition.
-- Assert: object definitions changed only where the migration intended
SELECT
object_name,
object_type,
DDL
FROM snowflake.account_usage.ddl_history
WHERE start_time >= :migration_start
AND object_name NOT IN ('ORDERS', 'ORDERS_VIEW', 'SCHEMA_MIGRATIONS')
ORDER BY start_time DESC;
-- Assert: fixture round-trip survived the type mapping
SELECT
order_id,
amount,
status,
IFF(amount = 1234.56 AND status = 'OPEN', 'PASS', 'FAIL') AS round_trip
FROM orders
WHERE order_id = 'fixture-0001';
Assertions belong in the repository next to the migration, not in a wiki page. When a gate fails at 3 a.m., the engineer on call reads the assertion file, not the process document.
Drift Detection Between Environments
Two environments diverge quietly: someone adds an index-equivalent clustering key in production during an incident, a reverted change never reaches staging, or a feature flag leaves a column behind. Drift detection compares a canonical export of each environment on a schedule and raises a diff as a pull request, so divergence becomes a code review artifact instead of a surprise six months later.
# Export canonical DDL for every object the pipeline owns
snowsql -c prod -q "SHOW TERSE SCHEMAS IN DATABASE ANALYTICS" -o output_format=csv \
| tail -n +2 | while IFS=, read -r _ name; do
snowsql -c prod -q "SHOW CREATE SCHEMA ANALYTICS.$name" >> prod-schema.sql
done
# Compare against the committed baseline from the repository
diff -u migrations/baseline.sql prod-schema.sql > drift.patch || {
echo "DRIFT DETECTED: $(grep -c '^+' drift.patch) added lines"
exit 1
}
Scope the comparison to objects your pipeline owns. Diffing an entire account produces hundreds of Snowflake-managed differences that train everyone to ignore the alert, which is worse than having no alert.
When a Promotion Fails Halfway
The failure mode that matters is not a migration that errors on the first statement; it is one that applies statement three of eight and then dies on statement four. Your runner must record each statement's outcome as it goes, so the recovery decision uses facts rather than memory. Snowflake executes each statement atomically, so the safe position is always "the last recorded success" โ never "wherever the script stopped reading."
Recovery then has exactly two options, and the rollback column decides between them. If the partial state is additive and harmless โ an extra column, an empty table โ repair forward by resuming from the next unapplied statement. If it is destructive or semantic โ a dropped column, a rewritten view โ roll back to the recorded pre-migration state and re-open the incident as a failed deploy rather than a partial success. Write the decision rule into the runbook with both branches spelled out, because under pressure engineers pick the option that makes the alert stop, not the option that is correct.
Best Practices
| Practice | Recommendation |
|---|---|
| Version control | Store all DDL in Git |
| Migrations | Use versioned migration scripts |
| Testing | Test migrations in dev before prod |
| Rollback | Always have rollback scripts |
| Monitoring | Track migration history |
| Automation | Use CI/CD for all deployments |
โ ๏ธ
CI/CD Anti-Patterns:
- Manual deployments โ Error-prone and unrepeatable
- No rollback plan โ Must always have rollback scripts
- Skipping dev/staging โ Always test in lower environments first
- No migration tracking โ Always record what was applied
- Hardcoded values โ Use variables and secrets management
Key Takeaways
- Promote one checksummed artifact: if anyone edits SQL by hand on the way to production, the pipeline stops being a control and becomes documentation.
- The highest-yield promotion gate is a soak across one full business cycle, because most Snowflake failures are scheduling and timing problems rather than syntax errors.
- Migration tests should assert a fixture round-trip, a reversible rollback, and an unchanged object list โ assertions live next to the migration, not in a wiki page.
- A runner must record per-statement outcomes so a half-applied migration recovers to the last recorded success, choosing repair-forward or rollback from a written rule.